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

lightningnetwork / lnd / 16027444140

02 Jul 2025 02:08PM UTC coverage: 57.777% (-0.03%) from 57.803%
16027444140

Pull #10018

github

web-flow
Merge 6574a2b47 into 1d2e5472b
Pull Request #10018: Refactor link's long methods

429 of 808 new or added lines in 1 file covered. (53.09%)

60 existing lines in 9 files now uncovered.

98478 of 170444 relevant lines covered (57.78%)

1.79 hits per line

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

69.47
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

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

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

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

418
        customMessageServer *subscribe.Server
419

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

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

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

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

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

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

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

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

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

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

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

490
                                        s.mu.Lock()
3✔
491

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

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

506
                                        s.mu.Unlock()
3✔
507

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

514
        return nil
3✔
515
}
516

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
698
                listenAddrs: listenAddrs,
3✔
699

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

3✔
704
                torController: torController,
3✔
705

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

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

3✔
722
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
723

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

3✔
726
                tlsManager: tlsManager,
3✔
727

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

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

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

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

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

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

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

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

3✔
769
                return nil
3✔
770
        }
771

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

945
        // If no alias is provided, default to first 10 characters of public
946
        // key.
947
        alias := cfg.Alias
3✔
948
        if alias == "" {
6✔
949
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
950
        }
3✔
951
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
952
        if err != nil {
3✔
953
                return nil, err
×
954
        }
×
955

956
        // TODO(elle): All previously persisted node announcement fields (ie,
957
        //  not just LastUpdate) should be consulted here to ensure that we
958
        //  aren't overwriting any fields that may have been set during the
959
        //  last run of lnd.
960
        nodeLastUpdate := time.Now()
3✔
961
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
962
        switch {
3✔
963
        // If we have a source node persisted in the DB already, then we just
964
        // need to make sure that the new LastUpdate time is at least one
965
        // second after the last update time.
966
        case err == nil:
3✔
967
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
968
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
969
                }
3✔
970

971
        // If we don't have a source node persisted in the DB, then we'll
972
        // create a new one with the current time as the LastUpdate.
973
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
974

975
        // If the above cases are not matched, then we have an unhandled non
976
        // nil error.
977
        default:
×
978
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
979
        }
980

981
        selfNode := &models.LightningNode{
3✔
982
                HaveNodeAnnouncement: true,
3✔
983
                LastUpdate:           nodeLastUpdate,
3✔
984
                Addresses:            selfAddrs,
3✔
985
                Alias:                nodeAlias.String(),
3✔
986
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
987
                Color:                color,
3✔
988
        }
3✔
989
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
990

3✔
991
        // Based on the disk representation of the node announcement generated
3✔
992
        // above, we'll generate a node announcement that can go out on the
3✔
993
        // network so we can properly sign it.
3✔
994
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
995
        if err != nil {
3✔
996
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
997
        }
×
998

999
        // With the announcement generated, we'll sign it to properly
1000
        // authenticate the message on the network.
1001
        authSig, err := netann.SignAnnouncement(
3✔
1002
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
1003
        )
3✔
1004
        if err != nil {
3✔
1005
                return nil, fmt.Errorf("unable to generate signature for "+
×
1006
                        "self node announcement: %v", err)
×
1007
        }
×
1008
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
1009
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
1010
                selfNode.AuthSigBytes,
3✔
1011
        )
3✔
1012
        if err != nil {
3✔
1013
                return nil, err
×
1014
        }
×
1015

1016
        // Finally, we'll update the representation on disk, and update our
1017
        // cached in-memory version as well.
1018
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
1019
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1020
        }
×
1021
        s.currentNodeAnn = nodeAnn
3✔
1022

3✔
1023
        // The router will get access to the payment ID sequencer, such that it
3✔
1024
        // can generate unique payment IDs.
3✔
1025
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1026
        if err != nil {
3✔
1027
                return nil, err
×
1028
        }
×
1029

1030
        // Instantiate mission control with config from the sub server.
1031
        //
1032
        // TODO(joostjager): When we are further in the process of moving to sub
1033
        // servers, the mission control instance itself can be moved there too.
1034
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1035

3✔
1036
        // We only initialize a probability estimator if there's no custom one.
3✔
1037
        var estimator routing.Estimator
3✔
1038
        if cfg.Estimator != nil {
3✔
1039
                estimator = cfg.Estimator
×
1040
        } else {
3✔
1041
                switch routingConfig.ProbabilityEstimatorType {
3✔
1042
                case routing.AprioriEstimatorName:
3✔
1043
                        aCfg := routingConfig.AprioriConfig
3✔
1044
                        aprioriConfig := routing.AprioriConfig{
3✔
1045
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1046
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1047
                                AprioriWeight:         aCfg.Weight,
3✔
1048
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1049
                        }
3✔
1050

3✔
1051
                        estimator, err = routing.NewAprioriEstimator(
3✔
1052
                                aprioriConfig,
3✔
1053
                        )
3✔
1054
                        if err != nil {
3✔
1055
                                return nil, err
×
1056
                        }
×
1057

1058
                case routing.BimodalEstimatorName:
×
1059
                        bCfg := routingConfig.BimodalConfig
×
1060
                        bimodalConfig := routing.BimodalConfig{
×
1061
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1062
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1063
                                        bCfg.Scale,
×
1064
                                ),
×
1065
                                BimodalDecayTime: bCfg.DecayTime,
×
1066
                        }
×
1067

×
1068
                        estimator, err = routing.NewBimodalEstimator(
×
1069
                                bimodalConfig,
×
1070
                        )
×
1071
                        if err != nil {
×
1072
                                return nil, err
×
1073
                        }
×
1074

1075
                default:
×
1076
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1077
                                routingConfig.ProbabilityEstimatorType)
×
1078
                }
1079
        }
1080

1081
        mcCfg := &routing.MissionControlConfig{
3✔
1082
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1083
                Estimator:               estimator,
3✔
1084
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1085
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1086
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1087
        }
3✔
1088

3✔
1089
        s.missionController, err = routing.NewMissionController(
3✔
1090
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1091
        )
3✔
1092
        if err != nil {
3✔
1093
                return nil, fmt.Errorf("can't create mission control "+
×
1094
                        "manager: %w", err)
×
1095
        }
×
1096
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1097
                routing.DefaultMissionControlNamespace,
3✔
1098
        )
3✔
1099
        if err != nil {
3✔
1100
                return nil, fmt.Errorf("can't create mission control in the "+
×
1101
                        "default namespace: %w", err)
×
1102
        }
×
1103

1104
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1105
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1106
                int64(routingConfig.AttemptCost),
3✔
1107
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1108
                routingConfig.MinRouteProbability)
3✔
1109

3✔
1110
        pathFindingConfig := routing.PathFindingConfig{
3✔
1111
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1112
                        routingConfig.AttemptCost,
3✔
1113
                ),
3✔
1114
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1115
                MinProbability: routingConfig.MinRouteProbability,
3✔
1116
        }
3✔
1117

3✔
1118
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1119
        if err != nil {
3✔
1120
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1121
        }
×
1122
        paymentSessionSource := &routing.SessionSource{
3✔
1123
                GraphSessionFactory: dbs.GraphDB,
3✔
1124
                SourceNode:          sourceNode,
3✔
1125
                MissionControl:      s.defaultMC,
3✔
1126
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1127
                PathFindingConfig:   pathFindingConfig,
3✔
1128
        }
3✔
1129

3✔
1130
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1131

3✔
1132
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1133

3✔
1134
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1135
                cfg.Routing.StrictZombiePruning
3✔
1136

3✔
1137
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1138
                SelfNode:            selfNode.PubKeyBytes,
3✔
1139
                Graph:               dbs.GraphDB,
3✔
1140
                Chain:               cc.ChainIO,
3✔
1141
                ChainView:           cc.ChainView,
3✔
1142
                Notifier:            cc.ChainNotifier,
3✔
1143
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1144
                GraphPruneInterval:  time.Hour,
3✔
1145
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1146
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1147
                StrictZombiePruning: strictPruning,
3✔
1148
                IsAlias:             aliasmgr.IsAlias,
3✔
1149
        })
3✔
1150
        if err != nil {
3✔
1151
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1152
        }
×
1153

1154
        s.chanRouter, err = routing.New(routing.Config{
3✔
1155
                SelfNode:           selfNode.PubKeyBytes,
3✔
1156
                RoutingGraph:       dbs.GraphDB,
3✔
1157
                Chain:              cc.ChainIO,
3✔
1158
                Payer:              s.htlcSwitch,
3✔
1159
                Control:            s.controlTower,
3✔
1160
                MissionControl:     s.defaultMC,
3✔
1161
                SessionSource:      paymentSessionSource,
3✔
1162
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1163
                NextPaymentID:      sequencer.NextID,
3✔
1164
                PathFindingConfig:  pathFindingConfig,
3✔
1165
                Clock:              clock.NewDefaultClock(),
3✔
1166
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1167
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1168
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1169
        })
3✔
1170
        if err != nil {
3✔
1171
                return nil, fmt.Errorf("can't create router: %w", err)
×
1172
        }
×
1173

1174
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1175
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1176
        if err != nil {
3✔
1177
                return nil, err
×
1178
        }
×
1179
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1180
        if err != nil {
3✔
1181
                return nil, err
×
1182
        }
×
1183

1184
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1185

3✔
1186
        s.authGossiper = discovery.New(discovery.Config{
3✔
1187
                Graph:                 s.graphBuilder,
3✔
1188
                ChainIO:               s.cc.ChainIO,
3✔
1189
                Notifier:              s.cc.ChainNotifier,
3✔
1190
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1191
                Broadcast:             s.BroadcastMessage,
3✔
1192
                ChanSeries:            chanSeries,
3✔
1193
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1194
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1195
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1196
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1197
                        error) {
3✔
1198

×
1199
                        return s.genNodeAnnouncement(nil)
×
1200
                },
×
1201
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1202
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1203
                RetransmitTicker:        ticker.New(time.Minute * 30),
1204
                RebroadcastInterval:     time.Hour * 24,
1205
                WaitingProofStore:       waitingProofStore,
1206
                MessageStore:            gossipMessageStore,
1207
                AnnSigner:               s.nodeSigner,
1208
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1209
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1210
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1211
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1212
                MinimumBatchSize:        10,
1213
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1214
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1215
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1216
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1217
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1218
                IsAlias:                 aliasmgr.IsAlias,
1219
                SignAliasUpdate:         s.signAliasUpdate,
1220
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1221
                GetAlias:                s.aliasMgr.GetPeerAlias,
1222
                FindChannel:             s.findChannel,
1223
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1224
                ScidCloser:              scidCloserMan,
1225
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1226
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1227
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1228
        }, nodeKeyDesc)
1229

1230
        accessCfg := &accessManConfig{
3✔
1231
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1232
                        error) {
6✔
1233

3✔
1234
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1235
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1236
                                genesisHash[:],
3✔
1237
                        )
3✔
1238
                },
3✔
1239
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1240
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1241
        }
1242

1243
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1244
        if err != nil {
3✔
1245
                return nil, err
×
1246
        }
×
1247

1248
        s.peerAccessMan = peerAccessMan
3✔
1249

3✔
1250
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1251
        //nolint:ll
3✔
1252
        s.localChanMgr = &localchans.Manager{
3✔
1253
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1254
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1255
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1256
                        *models.ChannelEdgePolicy) error) error {
6✔
1257

3✔
1258
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1259
                                func(c *models.ChannelEdgeInfo,
3✔
1260
                                        e *models.ChannelEdgePolicy,
3✔
1261
                                        _ *models.ChannelEdgePolicy) error {
6✔
1262

3✔
1263
                                        // NOTE: The invoked callback here may
3✔
1264
                                        // receive a nil channel policy.
3✔
1265
                                        return cb(c, e)
3✔
1266
                                },
3✔
1267
                        )
1268
                },
1269
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1270
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1271
                FetchChannel:              s.chanStateDB.FetchChannel,
1272
                AddEdge: func(ctx context.Context,
1273
                        edge *models.ChannelEdgeInfo) error {
×
1274

×
1275
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1276
                },
×
1277
        }
1278

1279
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1280
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1281
        )
3✔
1282
        if err != nil {
3✔
1283
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1284
                return nil, err
×
1285
        }
×
1286

1287
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1288
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1289
        )
3✔
1290
        if err != nil {
3✔
1291
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1292
                return nil, err
×
1293
        }
×
1294

1295
        aggregator := sweep.NewBudgetAggregator(
3✔
1296
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1297
                s.implCfg.AuxSweeper,
3✔
1298
        )
3✔
1299

3✔
1300
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1301
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1302
                Wallet:     cc.Wallet,
3✔
1303
                Estimator:  cc.FeeEstimator,
3✔
1304
                Notifier:   cc.ChainNotifier,
3✔
1305
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1306
        })
3✔
1307

3✔
1308
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1309
                FeeEstimator: cc.FeeEstimator,
3✔
1310
                GenSweepScript: newSweepPkScriptGen(
3✔
1311
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1312
                ),
3✔
1313
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1314
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1315
                Mempool:              cc.MempoolNotifier,
3✔
1316
                Notifier:             cc.ChainNotifier,
3✔
1317
                Store:                sweeperStore,
3✔
1318
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1319
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1320
                Aggregator:           aggregator,
3✔
1321
                Publisher:            s.txPublisher,
3✔
1322
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1323
        })
3✔
1324

3✔
1325
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1326
                ChainIO:             cc.ChainIO,
3✔
1327
                ConfDepth:           1,
3✔
1328
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1329
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1330
                Notifier:            cc.ChainNotifier,
3✔
1331
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1332
                Store:               utxnStore,
3✔
1333
                SweepInput:          s.sweeper.SweepInput,
3✔
1334
                Budget:              s.cfg.Sweeper.Budget,
3✔
1335
        })
3✔
1336

3✔
1337
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1338
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1339
                closureType contractcourt.ChannelCloseType) {
6✔
1340
                // TODO(conner): Properly respect the update and error channels
3✔
1341
                // returned by CloseLink.
3✔
1342

3✔
1343
                // Instruct the switch to close the channel.  Provide no close out
3✔
1344
                // delivery script or target fee per kw because user input is not
3✔
1345
                // available when the remote peer closes the channel.
3✔
1346
                s.htlcSwitch.CloseLink(
3✔
1347
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1348
                )
3✔
1349
        }
3✔
1350

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

3✔
1355
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1356
                &contractcourt.BreachConfig{
3✔
1357
                        CloseLink: closeLink,
3✔
1358
                        DB:        s.chanStateDB,
3✔
1359
                        Estimator: s.cc.FeeEstimator,
3✔
1360
                        GenSweepScript: newSweepPkScriptGen(
3✔
1361
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1362
                        ),
3✔
1363
                        Notifier:           cc.ChainNotifier,
3✔
1364
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1365
                        ContractBreaches:   contractBreaches,
3✔
1366
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1367
                        Store: contractcourt.NewRetributionStore(
3✔
1368
                                dbs.ChanStateDB,
3✔
1369
                        ),
3✔
1370
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1371
                },
3✔
1372
        )
3✔
1373

3✔
1374
        //nolint:ll
3✔
1375
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1376
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1377
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1378
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1379
                NewSweepAddr: func() ([]byte, error) {
3✔
1380
                        addr, err := newSweepPkScriptGen(
×
1381
                                cc.Wallet, netParams,
×
1382
                        )().Unpack()
×
1383
                        if err != nil {
×
1384
                                return nil, err
×
1385
                        }
×
1386

1387
                        return addr.DeliveryAddress, nil
×
1388
                },
1389
                PublishTx: cc.Wallet.PublishTransaction,
1390
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1391
                        for _, msg := range msgs {
6✔
1392
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1393
                                if err != nil {
3✔
1394
                                        return err
×
1395
                                }
×
1396
                        }
1397
                        return nil
3✔
1398
                },
1399
                IncubateOutputs: func(chanPoint wire.OutPoint,
1400
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1401
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1402
                        broadcastHeight uint32,
1403
                        deadlineHeight fn.Option[int32]) error {
3✔
1404

3✔
1405
                        return s.utxoNursery.IncubateOutputs(
3✔
1406
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1407
                                broadcastHeight, deadlineHeight,
3✔
1408
                        )
3✔
1409
                },
3✔
1410
                PreimageDB:   s.witnessBeacon,
1411
                Notifier:     cc.ChainNotifier,
1412
                Mempool:      cc.MempoolNotifier,
1413
                Signer:       cc.Wallet.Cfg.Signer,
1414
                FeeEstimator: cc.FeeEstimator,
1415
                ChainIO:      cc.ChainIO,
1416
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1417
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1418
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1419
                        return nil
3✔
1420
                },
3✔
1421
                IsOurAddress: cc.Wallet.IsOurAddress,
1422
                ContractBreach: func(chanPoint wire.OutPoint,
1423
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1424

3✔
1425
                        // processACK will handle the BreachArbitrator ACKing
3✔
1426
                        // the event.
3✔
1427
                        finalErr := make(chan error, 1)
3✔
1428
                        processACK := func(brarErr error) {
6✔
1429
                                if brarErr != nil {
3✔
1430
                                        finalErr <- brarErr
×
1431
                                        return
×
1432
                                }
×
1433

1434
                                // If the BreachArbitrator successfully handled
1435
                                // the event, we can signal that the handoff
1436
                                // was successful.
1437
                                finalErr <- nil
3✔
1438
                        }
1439

1440
                        event := &contractcourt.ContractBreachEvent{
3✔
1441
                                ChanPoint:         chanPoint,
3✔
1442
                                ProcessACK:        processACK,
3✔
1443
                                BreachRetribution: breachRet,
3✔
1444
                        }
3✔
1445

3✔
1446
                        // Send the contract breach event to the
3✔
1447
                        // BreachArbitrator.
3✔
1448
                        select {
3✔
1449
                        case contractBreaches <- event:
3✔
1450
                        case <-s.quit:
×
1451
                                return ErrServerShuttingDown
×
1452
                        }
1453

1454
                        // We'll wait for a final error to be available from
1455
                        // the BreachArbitrator.
1456
                        select {
3✔
1457
                        case err := <-finalErr:
3✔
1458
                                return err
3✔
1459
                        case <-s.quit:
×
1460
                                return ErrServerShuttingDown
×
1461
                        }
1462
                },
1463
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1464
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1465
                },
3✔
1466
                Sweeper:                       s.sweeper,
1467
                Registry:                      s.invoices,
1468
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1469
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1470
                OnionProcessor:                s.sphinx,
1471
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1472
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1473
                Clock:                         clock.NewDefaultClock(),
1474
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1475
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1476
                HtlcNotifier:                  s.htlcNotifier,
1477
                Budget:                        *s.cfg.Sweeper.Budget,
1478

1479
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1480
                QueryIncomingCircuit: func(
1481
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1482

3✔
1483
                        // Get the circuit map.
3✔
1484
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1485

3✔
1486
                        // Lookup the outgoing circuit.
3✔
1487
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1488
                        if pc == nil {
5✔
1489
                                return nil
2✔
1490
                        }
2✔
1491

1492
                        return &pc.Incoming
3✔
1493
                },
1494
                AuxLeafStore: implCfg.AuxLeafStore,
1495
                AuxSigner:    implCfg.AuxSigner,
1496
                AuxResolver:  implCfg.AuxContractResolver,
1497
        }, dbs.ChanStateDB)
1498

1499
        // Select the configuration and funding parameters for Bitcoin.
1500
        chainCfg := cfg.Bitcoin
3✔
1501
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1502
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1503

3✔
1504
        var chanIDSeed [32]byte
3✔
1505
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1506
                return nil, err
×
1507
        }
×
1508

1509
        // Wrap the DeleteChannelEdges method so that the funding manager can
1510
        // use it without depending on several layers of indirection.
1511
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1512
                *models.ChannelEdgePolicy, error) {
6✔
1513

3✔
1514
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1515
                        scid.ToUint64(),
3✔
1516
                )
3✔
1517
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1518
                        // This is unlikely but there is a slim chance of this
×
1519
                        // being hit if lnd was killed via SIGKILL and the
×
1520
                        // funding manager was stepping through the delete
×
1521
                        // alias edge logic.
×
1522
                        return nil, nil
×
1523
                } else if err != nil {
3✔
1524
                        return nil, err
×
1525
                }
×
1526

1527
                // Grab our key to find our policy.
1528
                var ourKey [33]byte
3✔
1529
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1530

3✔
1531
                var ourPolicy *models.ChannelEdgePolicy
3✔
1532
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1533
                        ourPolicy = e1
3✔
1534
                } else {
6✔
1535
                        ourPolicy = e2
3✔
1536
                }
3✔
1537

1538
                if ourPolicy == nil {
3✔
1539
                        // Something is wrong, so return an error.
×
1540
                        return nil, fmt.Errorf("we don't have an edge")
×
1541
                }
×
1542

1543
                err = s.graphDB.DeleteChannelEdges(
3✔
1544
                        false, false, scid.ToUint64(),
3✔
1545
                )
3✔
1546
                return ourPolicy, err
3✔
1547
        }
1548

1549
        // For the reservationTimeout and the zombieSweeperInterval different
1550
        // values are set in case we are in a dev environment so enhance test
1551
        // capacilities.
1552
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1553
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1554

3✔
1555
        // Get the development config for funding manager. If we are not in
3✔
1556
        // development mode, this would be nil.
3✔
1557
        var devCfg *funding.DevConfig
3✔
1558
        if lncfg.IsDevBuild() {
6✔
1559
                devCfg = &funding.DevConfig{
3✔
1560
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1561
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1562
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1563
                }
3✔
1564

3✔
1565
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1566
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1567

3✔
1568
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1569
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1570
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1571
        }
3✔
1572

1573
        //nolint:ll
1574
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1575
                Dev:                devCfg,
3✔
1576
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1577
                IDKey:              nodeKeyDesc.PubKey,
3✔
1578
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1579
                Wallet:             cc.Wallet,
3✔
1580
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1581
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1582
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1583
                },
3✔
1584
                Notifier:     cc.ChainNotifier,
1585
                ChannelDB:    s.chanStateDB,
1586
                FeeEstimator: cc.FeeEstimator,
1587
                SignMessage:  cc.MsgSigner.SignMessage,
1588
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1589
                        error) {
3✔
1590

3✔
1591
                        return s.genNodeAnnouncement(nil)
3✔
1592
                },
3✔
1593
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1594
                NotifyWhenOnline:     s.NotifyWhenOnline,
1595
                TempChanIDSeed:       chanIDSeed,
1596
                FindChannel:          s.findChannel,
1597
                DefaultRoutingPolicy: cc.RoutingPolicy,
1598
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1599
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1600
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1601
                        // For large channels we increase the number
3✔
1602
                        // of confirmations we require for the
3✔
1603
                        // channel to be considered open. As it is
3✔
1604
                        // always the responder that gets to choose
3✔
1605
                        // value, the pushAmt is value being pushed
3✔
1606
                        // to us. This means we have more to lose
3✔
1607
                        // in the case this gets re-orged out, and
3✔
1608
                        // we will require more confirmations before
3✔
1609
                        // we consider it open.
3✔
1610

3✔
1611
                        // In case the user has explicitly specified
3✔
1612
                        // a default value for the number of
3✔
1613
                        // confirmations, we use it.
3✔
1614
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1615
                        if defaultConf != 0 {
6✔
1616
                                return defaultConf
3✔
1617
                        }
3✔
1618

1619
                        minConf := uint64(3)
×
1620
                        maxConf := uint64(6)
×
1621

×
1622
                        // If this is a wumbo channel, then we'll require the
×
1623
                        // max amount of confirmations.
×
1624
                        if chanAmt > MaxFundingAmount {
×
1625
                                return uint16(maxConf)
×
1626
                        }
×
1627

1628
                        // If not we return a value scaled linearly
1629
                        // between 3 and 6, depending on channel size.
1630
                        // TODO(halseth): Use 1 as minimum?
1631
                        maxChannelSize := uint64(
×
1632
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1633
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1634
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1635
                        if conf < minConf {
×
1636
                                conf = minConf
×
1637
                        }
×
1638
                        if conf > maxConf {
×
1639
                                conf = maxConf
×
1640
                        }
×
1641
                        return uint16(conf)
×
1642
                },
1643
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1644
                        // We scale the remote CSV delay (the time the
3✔
1645
                        // remote have to claim funds in case of a unilateral
3✔
1646
                        // close) linearly from minRemoteDelay blocks
3✔
1647
                        // for small channels, to maxRemoteDelay blocks
3✔
1648
                        // for channels of size MaxFundingAmount.
3✔
1649

3✔
1650
                        // In case the user has explicitly specified
3✔
1651
                        // a default value for the remote delay, we
3✔
1652
                        // use it.
3✔
1653
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1654
                        if defaultDelay > 0 {
6✔
1655
                                return defaultDelay
3✔
1656
                        }
3✔
1657

1658
                        // If this is a wumbo channel, then we'll require the
1659
                        // max value.
1660
                        if chanAmt > MaxFundingAmount {
×
1661
                                return maxRemoteDelay
×
1662
                        }
×
1663

1664
                        // If not we scale according to channel size.
1665
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1666
                                chanAmt / MaxFundingAmount)
×
1667
                        if delay < minRemoteDelay {
×
1668
                                delay = minRemoteDelay
×
1669
                        }
×
1670
                        if delay > maxRemoteDelay {
×
1671
                                delay = maxRemoteDelay
×
1672
                        }
×
1673
                        return delay
×
1674
                },
1675
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1676
                        peerKey *btcec.PublicKey) error {
3✔
1677

3✔
1678
                        // First, we'll mark this new peer as a persistent peer
3✔
1679
                        // for re-connection purposes. If the peer is not yet
3✔
1680
                        // tracked or the user hasn't requested it to be perm,
3✔
1681
                        // we'll set false to prevent the server from continuing
3✔
1682
                        // to connect to this peer even if the number of
3✔
1683
                        // channels with this peer is zero.
3✔
1684
                        s.mu.Lock()
3✔
1685
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1686
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1687
                                s.persistentPeers[pubStr] = false
3✔
1688
                        }
3✔
1689
                        s.mu.Unlock()
3✔
1690

3✔
1691
                        // With that taken care of, we'll send this channel to
3✔
1692
                        // the chain arb so it can react to on-chain events.
3✔
1693
                        return s.chainArb.WatchNewChannel(channel)
3✔
1694
                },
1695
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1696
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1697
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1698
                },
3✔
1699
                RequiredRemoteChanReserve: func(chanAmt,
1700
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1701

3✔
1702
                        // By default, we'll require the remote peer to maintain
3✔
1703
                        // at least 1% of the total channel capacity at all
3✔
1704
                        // times. If this value ends up dipping below the dust
3✔
1705
                        // limit, then we'll use the dust limit itself as the
3✔
1706
                        // reserve as required by BOLT #2.
3✔
1707
                        reserve := chanAmt / 100
3✔
1708
                        if reserve < dustLimit {
6✔
1709
                                reserve = dustLimit
3✔
1710
                        }
3✔
1711

1712
                        return reserve
3✔
1713
                },
1714
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1715
                        // By default, we'll allow the remote peer to fully
3✔
1716
                        // utilize the full bandwidth of the channel, minus our
3✔
1717
                        // required reserve.
3✔
1718
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1719
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1720
                },
3✔
1721
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1722
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1723
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1724
                        }
3✔
1725

1726
                        // By default, we'll permit them to utilize the full
1727
                        // channel bandwidth.
1728
                        return uint16(input.MaxHTLCNumber / 2)
×
1729
                },
1730
                ZombieSweeperInterval:         zombieSweeperInterval,
1731
                ReservationTimeout:            reservationTimeout,
1732
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1733
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1734
                MaxPendingChannels:            cfg.MaxPendingChannels,
1735
                RejectPush:                    cfg.RejectPush,
1736
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1737
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1738
                OpenChannelPredicate:          chanPredicate,
1739
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1740
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1741
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1742
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1743
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1744
                DeleteAliasEdge:      deleteAliasEdge,
1745
                AliasManager:         s.aliasMgr,
1746
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1747
                AuxFundingController: implCfg.AuxFundingController,
1748
                AuxSigner:            implCfg.AuxSigner,
1749
                AuxResolver:          implCfg.AuxContractResolver,
1750
        })
1751
        if err != nil {
3✔
1752
                return nil, err
×
1753
        }
×
1754

1755
        // Next, we'll assemble the sub-system that will maintain an on-disk
1756
        // static backup of the latest channel state.
1757
        chanNotifier := &channelNotifier{
3✔
1758
                chanNotifier: s.channelNotifier,
3✔
1759
                addrs:        s.addrSource,
3✔
1760
        }
3✔
1761
        backupFile := chanbackup.NewMultiFile(
3✔
1762
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1763
        )
3✔
1764
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1765
                ctx, s.chanStateDB, s.addrSource,
3✔
1766
        )
3✔
1767
        if err != nil {
3✔
1768
                return nil, err
×
1769
        }
×
1770
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1771
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1772
        )
3✔
1773
        if err != nil {
3✔
1774
                return nil, err
×
1775
        }
×
1776

1777
        // Assemble a peer notifier which will provide clients with subscriptions
1778
        // to peer online and offline events.
1779
        s.peerNotifier = peernotifier.New()
3✔
1780

3✔
1781
        // Create a channel event store which monitors all open channels.
3✔
1782
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1783
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1784
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1785
                },
3✔
1786
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1787
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1788
                },
3✔
1789
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1790
                Clock:           clock.NewDefaultClock(),
1791
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1792
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1793
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1794
        })
1795

1796
        if cfg.WtClient.Active {
6✔
1797
                policy := wtpolicy.DefaultPolicy()
3✔
1798
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1799

3✔
1800
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1801
                // protocol operations on sat/kw.
3✔
1802
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1803
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1804
                )
3✔
1805

3✔
1806
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1807

3✔
1808
                if err := policy.Validate(); err != nil {
3✔
1809
                        return nil, err
×
1810
                }
×
1811

1812
                // authDial is the wrapper around the btrontide.Dial for the
1813
                // watchtower.
1814
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1815
                        netAddr *lnwire.NetAddress,
3✔
1816
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1817

3✔
1818
                        return brontide.Dial(
3✔
1819
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1820
                        )
3✔
1821
                }
3✔
1822

1823
                // buildBreachRetribution is a call-back that can be used to
1824
                // query the BreachRetribution info and channel type given a
1825
                // channel ID and commitment height.
1826
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1827
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1828
                        channeldb.ChannelType, error) {
6✔
1829

3✔
1830
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1831
                                nil, chanID,
3✔
1832
                        )
3✔
1833
                        if err != nil {
3✔
1834
                                return nil, 0, err
×
1835
                        }
×
1836

1837
                        br, err := lnwallet.NewBreachRetribution(
3✔
1838
                                channel, commitHeight, 0, nil,
3✔
1839
                                implCfg.AuxLeafStore,
3✔
1840
                                implCfg.AuxContractResolver,
3✔
1841
                        )
3✔
1842
                        if err != nil {
3✔
1843
                                return nil, 0, err
×
1844
                        }
×
1845

1846
                        return br, channel.ChanType, nil
3✔
1847
                }
1848

1849
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1850

3✔
1851
                // Copy the policy for legacy channels and set the blob flag
3✔
1852
                // signalling support for anchor channels.
3✔
1853
                anchorPolicy := policy
3✔
1854
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1855

3✔
1856
                // Copy the policy for legacy channels and set the blob flag
3✔
1857
                // signalling support for taproot channels.
3✔
1858
                taprootPolicy := policy
3✔
1859
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1860
                        blob.FlagTaprootChannel,
3✔
1861
                )
3✔
1862

3✔
1863
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1864
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1865
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1866
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1867
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1868
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1869
                                error) {
6✔
1870

3✔
1871
                                return s.channelNotifier.
3✔
1872
                                        SubscribeChannelEvents()
3✔
1873
                        },
3✔
1874
                        Signer: cc.Wallet.Cfg.Signer,
1875
                        NewAddress: func() ([]byte, error) {
3✔
1876
                                addr, err := newSweepPkScriptGen(
3✔
1877
                                        cc.Wallet, netParams,
3✔
1878
                                )().Unpack()
3✔
1879
                                if err != nil {
3✔
1880
                                        return nil, err
×
1881
                                }
×
1882

1883
                                return addr.DeliveryAddress, nil
3✔
1884
                        },
1885
                        SecretKeyRing:      s.cc.KeyRing,
1886
                        Dial:               cfg.net.Dial,
1887
                        AuthDial:           authDial,
1888
                        DB:                 dbs.TowerClientDB,
1889
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1890
                        MinBackoff:         10 * time.Second,
1891
                        MaxBackoff:         5 * time.Minute,
1892
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1893
                }, policy, anchorPolicy, taprootPolicy)
1894
                if err != nil {
3✔
1895
                        return nil, err
×
1896
                }
×
1897
        }
1898

1899
        if len(cfg.ExternalHosts) != 0 {
3✔
1900
                advertisedIPs := make(map[string]struct{})
×
1901
                for _, addr := range s.currentNodeAnn.Addresses {
×
1902
                        advertisedIPs[addr.String()] = struct{}{}
×
1903
                }
×
1904

1905
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1906
                        Hosts:         cfg.ExternalHosts,
×
1907
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1908
                        LookupHost: func(host string) (net.Addr, error) {
×
1909
                                return lncfg.ParseAddressString(
×
1910
                                        host, strconv.Itoa(defaultPeerPort),
×
1911
                                        cfg.net.ResolveTCPAddr,
×
1912
                                )
×
1913
                        },
×
1914
                        AdvertisedIPs: advertisedIPs,
1915
                        AnnounceNewIPs: netann.IPAnnouncer(
1916
                                func(modifier ...netann.NodeAnnModifier) (
1917
                                        lnwire.NodeAnnouncement, error) {
×
1918

×
1919
                                        return s.genNodeAnnouncement(
×
1920
                                                nil, modifier...,
×
1921
                                        )
×
1922
                                }),
×
1923
                })
1924
        }
1925

1926
        // Create liveness monitor.
1927
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1928

3✔
1929
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1930
        for i, listenAddr := range listenAddrs {
6✔
1931
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1932
                // doesn't need to call the general lndResolveTCP function
3✔
1933
                // since we are resolving a local address.
3✔
1934

3✔
1935
                // RESOLVE: We are actually partially accepting inbound
3✔
1936
                // connection requests when we call NewListener.
3✔
1937
                listeners[i], err = brontide.NewListener(
3✔
1938
                        nodeKeyECDH, listenAddr.String(),
3✔
1939
                        // TODO(yy): remove this check and unify the inbound
3✔
1940
                        // connection check inside `InboundPeerConnected`.
3✔
1941
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1942
                )
3✔
1943
                if err != nil {
3✔
1944
                        return nil, err
×
1945
                }
×
1946
        }
1947

1948
        // Create the connection manager which will be responsible for
1949
        // maintaining persistent outbound connections and also accepting new
1950
        // incoming connections
1951
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1952
                Listeners:      listeners,
3✔
1953
                OnAccept:       s.InboundPeerConnected,
3✔
1954
                RetryDuration:  time.Second * 5,
3✔
1955
                TargetOutbound: 100,
3✔
1956
                Dial: noiseDial(
3✔
1957
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1958
                ),
3✔
1959
                OnConnection: s.OutboundPeerConnected,
3✔
1960
        })
3✔
1961
        if err != nil {
3✔
1962
                return nil, err
×
1963
        }
×
1964
        s.connMgr = cmgr
3✔
1965

3✔
1966
        // Finally, register the subsystems in blockbeat.
3✔
1967
        s.registerBlockConsumers()
3✔
1968

3✔
1969
        return s, nil
3✔
1970
}
1971

1972
// UpdateRoutingConfig is a callback function to update the routing config
1973
// values in the main cfg.
1974
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1975
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1976

3✔
1977
        switch c := cfg.Estimator.Config().(type) {
3✔
1978
        case routing.AprioriConfig:
3✔
1979
                routerCfg.ProbabilityEstimatorType =
3✔
1980
                        routing.AprioriEstimatorName
3✔
1981

3✔
1982
                targetCfg := routerCfg.AprioriConfig
3✔
1983
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1984
                targetCfg.Weight = c.AprioriWeight
3✔
1985
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1986
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1987

1988
        case routing.BimodalConfig:
3✔
1989
                routerCfg.ProbabilityEstimatorType =
3✔
1990
                        routing.BimodalEstimatorName
3✔
1991

3✔
1992
                targetCfg := routerCfg.BimodalConfig
3✔
1993
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1994
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1995
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1996
        }
1997

1998
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1999
}
2000

2001
// registerBlockConsumers registers the subsystems that consume block events.
2002
// By calling `RegisterQueue`, a list of subsystems are registered in the
2003
// blockbeat for block notifications. When a new block arrives, the subsystems
2004
// in the same queue are notified sequentially, and different queues are
2005
// notified concurrently.
2006
//
2007
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2008
// a new `RegisterQueue` call.
2009
func (s *server) registerBlockConsumers() {
3✔
2010
        // In this queue, when a new block arrives, it will be received and
3✔
2011
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
2012
        consumers := []chainio.Consumer{
3✔
2013
                s.chainArb,
3✔
2014
                s.sweeper,
3✔
2015
                s.txPublisher,
3✔
2016
        }
3✔
2017
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
2018
}
3✔
2019

2020
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2021
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2022
// may differ from what is on disk.
2023
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2024
        error) {
3✔
2025

3✔
2026
        data, err := u.DataToSign()
3✔
2027
        if err != nil {
3✔
2028
                return nil, err
×
2029
        }
×
2030

2031
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2032
}
2033

2034
// createLivenessMonitor creates a set of health checks using our configured
2035
// values and uses these checks to create a liveness monitor. Available
2036
// health checks,
2037
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2038
//   - diskCheck
2039
//   - tlsHealthCheck
2040
//   - torController, only created when tor is enabled.
2041
//
2042
// If a health check has been disabled by setting attempts to 0, our monitor
2043
// will not run it.
2044
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2045
        leaderElector cluster.LeaderElector) {
3✔
2046

3✔
2047
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2048
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2049
                srvrLog.Info("Disabling chain backend checks for " +
×
2050
                        "nochainbackend mode")
×
2051

×
2052
                chainBackendAttempts = 0
×
2053
        }
×
2054

2055
        chainHealthCheck := healthcheck.NewObservation(
3✔
2056
                "chain backend",
3✔
2057
                cc.HealthCheck,
3✔
2058
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2059
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2060
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2061
                chainBackendAttempts,
3✔
2062
        )
3✔
2063

3✔
2064
        diskCheck := healthcheck.NewObservation(
3✔
2065
                "disk space",
3✔
2066
                func() error {
3✔
2067
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2068
                                cfg.LndDir,
×
2069
                        )
×
2070
                        if err != nil {
×
2071
                                return err
×
2072
                        }
×
2073

2074
                        // If we have more free space than we require,
2075
                        // we return a nil error.
2076
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2077
                                return nil
×
2078
                        }
×
2079

2080
                        return fmt.Errorf("require: %v free space, got: %v",
×
2081
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2082
                                free)
×
2083
                },
2084
                cfg.HealthChecks.DiskCheck.Interval,
2085
                cfg.HealthChecks.DiskCheck.Timeout,
2086
                cfg.HealthChecks.DiskCheck.Backoff,
2087
                cfg.HealthChecks.DiskCheck.Attempts,
2088
        )
2089

2090
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2091
                "tls",
3✔
2092
                func() error {
3✔
2093
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2094
                                s.cc.KeyRing,
×
2095
                        )
×
2096
                        if err != nil {
×
2097
                                return err
×
2098
                        }
×
2099
                        if expired {
×
2100
                                return fmt.Errorf("TLS certificate is "+
×
2101
                                        "expired as of %v", expTime)
×
2102
                        }
×
2103

2104
                        // If the certificate is not outdated, no error needs
2105
                        // to be returned
2106
                        return nil
×
2107
                },
2108
                cfg.HealthChecks.TLSCheck.Interval,
2109
                cfg.HealthChecks.TLSCheck.Timeout,
2110
                cfg.HealthChecks.TLSCheck.Backoff,
2111
                cfg.HealthChecks.TLSCheck.Attempts,
2112
        )
2113

2114
        checks := []*healthcheck.Observation{
3✔
2115
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2116
        }
3✔
2117

3✔
2118
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2119
        if s.torController != nil {
3✔
2120
                torConnectionCheck := healthcheck.NewObservation(
×
2121
                        "tor connection",
×
2122
                        func() error {
×
2123
                                return healthcheck.CheckTorServiceStatus(
×
2124
                                        s.torController,
×
2125
                                        func() error {
×
2126
                                                return s.createNewHiddenService(
×
2127
                                                        context.TODO(),
×
2128
                                                )
×
2129
                                        },
×
2130
                                )
2131
                        },
2132
                        cfg.HealthChecks.TorConnection.Interval,
2133
                        cfg.HealthChecks.TorConnection.Timeout,
2134
                        cfg.HealthChecks.TorConnection.Backoff,
2135
                        cfg.HealthChecks.TorConnection.Attempts,
2136
                )
2137
                checks = append(checks, torConnectionCheck)
×
2138
        }
2139

2140
        // If remote signing is enabled, add the healthcheck for the remote
2141
        // signing RPC interface.
2142
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2143
                // Because we have two cascading timeouts here, we need to add
3✔
2144
                // some slack to the "outer" one of them in case the "inner"
3✔
2145
                // returns exactly on time.
3✔
2146
                overhead := time.Millisecond * 10
3✔
2147

3✔
2148
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2149
                        "remote signer connection",
3✔
2150
                        rpcwallet.HealthCheck(
3✔
2151
                                s.cfg.RemoteSigner,
3✔
2152

3✔
2153
                                // For the health check we might to be even
3✔
2154
                                // stricter than the initial/normal connect, so
3✔
2155
                                // we use the health check timeout here.
3✔
2156
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2157
                        ),
3✔
2158
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2159
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2160
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2161
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2162
                )
3✔
2163
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2164
        }
3✔
2165

2166
        // If we have a leader elector, we add a health check to ensure we are
2167
        // still the leader. During normal operation, we should always be the
2168
        // leader, but there are circumstances where this may change, such as
2169
        // when we lose network connectivity for long enough expiring out lease.
2170
        if leaderElector != nil {
3✔
2171
                leaderCheck := healthcheck.NewObservation(
×
2172
                        "leader status",
×
2173
                        func() error {
×
2174
                                // Check if we are still the leader. Note that
×
2175
                                // we don't need to use a timeout context here
×
2176
                                // as the healthcheck observer will handle the
×
2177
                                // timeout case for us.
×
2178
                                timeoutCtx, cancel := context.WithTimeout(
×
2179
                                        context.Background(),
×
2180
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2181
                                )
×
2182
                                defer cancel()
×
2183

×
2184
                                leader, err := leaderElector.IsLeader(
×
2185
                                        timeoutCtx,
×
2186
                                )
×
2187
                                if err != nil {
×
2188
                                        return fmt.Errorf("unable to check if "+
×
2189
                                                "still leader: %v", err)
×
2190
                                }
×
2191

2192
                                if !leader {
×
2193
                                        srvrLog.Debug("Not the current leader")
×
2194
                                        return fmt.Errorf("not the current " +
×
2195
                                                "leader")
×
2196
                                }
×
2197

2198
                                return nil
×
2199
                        },
2200
                        cfg.HealthChecks.LeaderCheck.Interval,
2201
                        cfg.HealthChecks.LeaderCheck.Timeout,
2202
                        cfg.HealthChecks.LeaderCheck.Backoff,
2203
                        cfg.HealthChecks.LeaderCheck.Attempts,
2204
                )
2205

2206
                checks = append(checks, leaderCheck)
×
2207
        }
2208

2209
        // If we have not disabled all of our health checks, we create a
2210
        // liveness monitor with our configured checks.
2211
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2212
                &healthcheck.Config{
3✔
2213
                        Checks:   checks,
3✔
2214
                        Shutdown: srvrLog.Criticalf,
3✔
2215
                },
3✔
2216
        )
3✔
2217
}
2218

2219
// Started returns true if the server has been started, and false otherwise.
2220
// NOTE: This function is safe for concurrent access.
2221
func (s *server) Started() bool {
3✔
2222
        return atomic.LoadInt32(&s.active) != 0
3✔
2223
}
3✔
2224

2225
// cleaner is used to aggregate "cleanup" functions during an operation that
2226
// starts several subsystems. In case one of the subsystem fails to start
2227
// and a proper resource cleanup is required, the "run" method achieves this
2228
// by running all these added "cleanup" functions.
2229
type cleaner []func() error
2230

2231
// add is used to add a cleanup function to be called when
2232
// the run function is executed.
2233
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2234
        return append(c, cleanup)
3✔
2235
}
3✔
2236

2237
// run is used to run all the previousely added cleanup functions.
2238
func (c cleaner) run() {
×
2239
        for i := len(c) - 1; i >= 0; i-- {
×
2240
                if err := c[i](); err != nil {
×
2241
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2242
                }
×
2243
        }
2244
}
2245

2246
// startLowLevelServices starts the low-level services of the server. These
2247
// services must be started successfully before running the main server. The
2248
// services are,
2249
// 1. the chain notifier.
2250
//
2251
// TODO(yy): identify and add more low-level services here.
2252
func (s *server) startLowLevelServices() error {
3✔
2253
        var startErr error
3✔
2254

3✔
2255
        cleanup := cleaner{}
3✔
2256

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

2262
        if startErr != nil {
3✔
2263
                cleanup.run()
×
2264
        }
×
2265

2266
        return startErr
3✔
2267
}
2268

2269
// Start starts the main daemon server, all requested listeners, and any helper
2270
// goroutines.
2271
// NOTE: This function is safe for concurrent access.
2272
//
2273
//nolint:funlen
2274
func (s *server) Start(ctx context.Context) error {
3✔
2275
        // Get the current blockbeat.
3✔
2276
        beat, err := s.getStartingBeat()
3✔
2277
        if err != nil {
3✔
2278
                return err
×
2279
        }
×
2280

2281
        var startErr error
3✔
2282

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

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

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

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

2311
                // Start the notification server. This is used so channel
2312
                // management goroutines can be notified when a funding
2313
                // transaction reaches a sufficient number of confirmations, or
2314
                // when the input for the funding transaction is spent in an
2315
                // attempt at an uncooperative close by the counterparty.
2316
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2317
                if err := s.sigPool.Start(); err != nil {
3✔
2318
                        startErr = err
×
2319
                        return
×
2320
                }
×
2321

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

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

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

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

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

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

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

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

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

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

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

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

2398
                // htlcSwitch must be started before chainArb since the latter
2399
                // relies on htlcSwitch to deliver resolution message upon
2400
                // start.
2401
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2402
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2403
                        startErr = err
×
2404
                        return
×
2405
                }
×
2406

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

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

2419
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2420
                if err := s.chainArb.Start(beat); err != nil {
3✔
2421
                        startErr = err
×
2422
                        return
×
2423
                }
×
2424

2425
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2426
                if err := s.graphDB.Start(); err != nil {
3✔
2427
                        startErr = err
×
2428
                        return
×
2429
                }
×
2430

2431
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2432
                if err := s.graphBuilder.Start(); err != nil {
3✔
2433
                        startErr = err
×
2434
                        return
×
2435
                }
×
2436

2437
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2438
                if err := s.chanRouter.Start(); err != nil {
3✔
2439
                        startErr = err
×
2440
                        return
×
2441
                }
×
2442
                // The authGossiper depends on the chanRouter and therefore
2443
                // should be started after it.
2444
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2445
                if err := s.authGossiper.Start(); err != nil {
3✔
2446
                        startErr = err
×
2447
                        return
×
2448
                }
×
2449

2450
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2451
                if err := s.invoices.Start(); err != nil {
3✔
2452
                        startErr = err
×
2453
                        return
×
2454
                }
×
2455

2456
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2457
                if err := s.sphinx.Start(); err != nil {
3✔
2458
                        startErr = err
×
2459
                        return
×
2460
                }
×
2461

2462
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2463
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2464
                        startErr = err
×
2465
                        return
×
2466
                }
×
2467

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

2474
                cleanup.add(func() error {
3✔
2475
                        s.missionController.StopStoreTickers()
×
2476
                        return nil
×
2477
                })
×
2478
                s.missionController.RunStoreTickers()
3✔
2479

3✔
2480
                // Before we start the connMgr, we'll check to see if we have
3✔
2481
                // any backups to recover. We do this now as we want to ensure
3✔
2482
                // that have all the information we need to handle channel
3✔
2483
                // recovery _before_ we even accept connections from any peers.
3✔
2484
                chanRestorer := &chanDBRestorer{
3✔
2485
                        db:         s.chanStateDB,
3✔
2486
                        secretKeys: s.cc.KeyRing,
3✔
2487
                        chainArb:   s.chainArb,
3✔
2488
                }
3✔
2489
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2490
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2491
                                s.chansToRestore.PackedSingleChanBackups,
×
2492
                                s.cc.KeyRing, chanRestorer, s,
×
2493
                        )
×
2494
                        if err != nil {
×
2495
                                startErr = fmt.Errorf("unable to unpack single "+
×
2496
                                        "backups: %v", err)
×
2497
                                return
×
2498
                        }
×
2499
                }
2500
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2501
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2502
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2503
                                s.cc.KeyRing, chanRestorer, s,
3✔
2504
                        )
3✔
2505
                        if err != nil {
3✔
2506
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2507
                                        "backup: %v", err)
×
2508
                                return
×
2509
                        }
×
2510
                }
2511

2512
                // chanSubSwapper must be started after the `channelNotifier`
2513
                // because it depends on channel events as a synchronization
2514
                // point.
2515
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2516
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2517
                        startErr = err
×
2518
                        return
×
2519
                }
×
2520

2521
                if s.torController != nil {
3✔
2522
                        cleanup = cleanup.add(s.torController.Stop)
×
2523
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2524
                                startErr = err
×
2525
                                return
×
2526
                        }
×
2527
                }
2528

2529
                if s.natTraversal != nil {
3✔
2530
                        s.wg.Add(1)
×
2531
                        go s.watchExternalIP()
×
2532
                }
×
2533

2534
                // Start connmgr last to prevent connections before init.
2535
                cleanup = cleanup.add(func() error {
3✔
2536
                        s.connMgr.Stop()
×
2537
                        return nil
×
2538
                })
×
2539

2540
                // RESOLVE: s.connMgr.Start() is called here, but
2541
                // brontide.NewListener() is called in newServer. This means
2542
                // that we are actually listening and partially accepting
2543
                // inbound connections even before the connMgr starts.
2544
                //
2545
                // TODO(yy): move the log into the connMgr's `Start` method.
2546
                srvrLog.Info("connMgr starting...")
3✔
2547
                s.connMgr.Start()
3✔
2548
                srvrLog.Debug("connMgr started")
3✔
2549

3✔
2550
                // If peers are specified as a config option, we'll add those
3✔
2551
                // peers first.
3✔
2552
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2553
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2554
                                peerAddrCfg,
3✔
2555
                        )
3✔
2556
                        if err != nil {
3✔
2557
                                startErr = fmt.Errorf("unable to parse peer "+
×
2558
                                        "pubkey from config: %v", err)
×
2559
                                return
×
2560
                        }
×
2561
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2562
                        if err != nil {
3✔
2563
                                startErr = fmt.Errorf("unable to parse peer "+
×
2564
                                        "address provided as a config option: "+
×
2565
                                        "%v", err)
×
2566
                                return
×
2567
                        }
×
2568

2569
                        peerAddr := &lnwire.NetAddress{
3✔
2570
                                IdentityKey: parsedPubkey,
3✔
2571
                                Address:     addr,
3✔
2572
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2573
                        }
3✔
2574

3✔
2575
                        err = s.ConnectToPeer(
3✔
2576
                                peerAddr, true,
3✔
2577
                                s.cfg.ConnectionTimeout,
3✔
2578
                        )
3✔
2579
                        if err != nil {
3✔
2580
                                startErr = fmt.Errorf("unable to connect to "+
×
2581
                                        "peer address provided as a config "+
×
2582
                                        "option: %v", err)
×
2583
                                return
×
2584
                        }
×
2585
                }
2586

2587
                // Subscribe to NodeAnnouncements that advertise new addresses
2588
                // our persistent peers.
2589
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2590
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2591
                                "addr: %v", err)
×
2592

×
2593
                        startErr = err
×
2594
                        return
×
2595
                }
×
2596

2597
                // With all the relevant sub-systems started, we'll now attempt
2598
                // to establish persistent connections to our direct channel
2599
                // collaborators within the network. Before doing so however,
2600
                // we'll prune our set of link nodes found within the database
2601
                // to ensure we don't reconnect to any nodes we no longer have
2602
                // open channels with.
2603
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2604
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2605

×
2606
                        startErr = err
×
2607
                        return
×
2608
                }
×
2609

2610
                if err := s.establishPersistentConnections(); err != nil {
3✔
2611
                        srvrLog.Errorf("Failed to establish persistent "+
×
2612
                                "connections: %v", err)
×
2613
                }
×
2614

2615
                // setSeedList is a helper function that turns multiple DNS seed
2616
                // server tuples from the command line or config file into the
2617
                // data structure we need and does a basic formal sanity check
2618
                // in the process.
2619
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2620
                        if len(tuples) == 0 {
×
2621
                                return
×
2622
                        }
×
2623

2624
                        result := make([][2]string, len(tuples))
×
2625
                        for idx, tuple := range tuples {
×
2626
                                tuple = strings.TrimSpace(tuple)
×
2627
                                if len(tuple) == 0 {
×
2628
                                        return
×
2629
                                }
×
2630

2631
                                servers := strings.Split(tuple, ",")
×
2632
                                if len(servers) > 2 || len(servers) == 0 {
×
2633
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2634
                                                "seed tuple: %v", servers)
×
2635
                                        return
×
2636
                                }
×
2637

2638
                                copy(result[idx][:], servers)
×
2639
                        }
2640

2641
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2642
                }
2643

2644
                // Let users overwrite the DNS seed nodes. We only allow them
2645
                // for bitcoin mainnet/testnet/signet.
2646
                if s.cfg.Bitcoin.MainNet {
3✔
2647
                        setSeedList(
×
2648
                                s.cfg.Bitcoin.DNSSeeds,
×
2649
                                chainreg.BitcoinMainnetGenesis,
×
2650
                        )
×
2651
                }
×
2652
                if s.cfg.Bitcoin.TestNet3 {
3✔
2653
                        setSeedList(
×
2654
                                s.cfg.Bitcoin.DNSSeeds,
×
2655
                                chainreg.BitcoinTestnetGenesis,
×
2656
                        )
×
2657
                }
×
2658
                if s.cfg.Bitcoin.TestNet4 {
3✔
2659
                        setSeedList(
×
2660
                                s.cfg.Bitcoin.DNSSeeds,
×
2661
                                chainreg.BitcoinTestnet4Genesis,
×
2662
                        )
×
2663
                }
×
2664
                if s.cfg.Bitcoin.SigNet {
3✔
2665
                        setSeedList(
×
2666
                                s.cfg.Bitcoin.DNSSeeds,
×
2667
                                chainreg.BitcoinSignetGenesis,
×
2668
                        )
×
2669
                }
×
2670

2671
                // If network bootstrapping hasn't been disabled, then we'll
2672
                // configure the set of active bootstrappers, and launch a
2673
                // dedicated goroutine to maintain a set of persistent
2674
                // connections.
2675
                if !s.cfg.NoNetBootstrap {
6✔
2676
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2677
                        if err != nil {
3✔
2678
                                startErr = err
×
2679
                                return
×
2680
                        }
×
2681

2682
                        s.wg.Add(1)
3✔
2683
                        go s.peerBootstrapper(
3✔
2684
                                ctx, defaultMinPeers, bootstrappers,
3✔
2685
                        )
3✔
2686
                } else {
3✔
2687
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2688
                }
3✔
2689

2690
                // Start the blockbeat after all other subsystems have been
2691
                // started so they are ready to receive new blocks.
2692
                cleanup = cleanup.add(func() error {
3✔
2693
                        s.blockbeatDispatcher.Stop()
×
2694
                        return nil
×
2695
                })
×
2696
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2697
                        startErr = err
×
2698
                        return
×
2699
                }
×
2700

2701
                // Set the active flag now that we've completed the full
2702
                // startup.
2703
                atomic.StoreInt32(&s.active, 1)
3✔
2704
        })
2705

2706
        if startErr != nil {
3✔
2707
                cleanup.run()
×
2708
        }
×
2709
        return startErr
3✔
2710
}
2711

2712
// Stop gracefully shutsdown the main daemon server. This function will signal
2713
// any active goroutines, or helper objects to exit, then blocks until they've
2714
// all successfully exited. Additionally, any/all listeners are closed.
2715
// NOTE: This function is safe for concurrent access.
2716
func (s *server) Stop() error {
3✔
2717
        s.stop.Do(func() {
6✔
2718
                atomic.StoreInt32(&s.stopping, 1)
3✔
2719

3✔
2720
                ctx := context.Background()
3✔
2721

3✔
2722
                close(s.quit)
3✔
2723

3✔
2724
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2725
                s.connMgr.Stop()
3✔
2726

3✔
2727
                // Stop dispatching blocks to other systems immediately.
3✔
2728
                s.blockbeatDispatcher.Stop()
3✔
2729

3✔
2730
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2731
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2732
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2733
                }
×
2734
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2735
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2736
                }
×
2737
                if err := s.sphinx.Stop(); err != nil {
3✔
2738
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2739
                }
×
2740
                if err := s.invoices.Stop(); err != nil {
3✔
2741
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2742
                }
×
2743
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2744
                        srvrLog.Warnf("failed to stop interceptable "+
×
2745
                                "switch: %v", err)
×
2746
                }
×
2747
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2748
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2749
                                "modifier: %v", err)
×
2750
                }
×
2751
                if err := s.chanRouter.Stop(); err != nil {
3✔
2752
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2753
                }
×
2754
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2755
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2756
                }
×
2757
                if err := s.graphDB.Stop(); err != nil {
3✔
2758
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2759
                }
×
2760
                if err := s.chainArb.Stop(); err != nil {
3✔
2761
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2762
                }
×
2763
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2764
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2765
                }
×
2766
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2767
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2768
                                err)
×
2769
                }
×
2770
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2771
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2772
                }
×
2773
                if err := s.authGossiper.Stop(); err != nil {
3✔
2774
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2775
                }
×
2776
                if err := s.sweeper.Stop(); err != nil {
3✔
2777
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2778
                }
×
2779
                if err := s.txPublisher.Stop(); err != nil {
3✔
2780
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2781
                }
×
2782
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2783
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2784
                }
×
2785
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2786
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2787
                }
×
2788
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2789
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2790
                }
×
2791

2792
                // Update channel.backup file. Make sure to do it before
2793
                // stopping chanSubSwapper.
2794
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2795
                        ctx, s.chanStateDB, s.addrSource,
3✔
2796
                )
3✔
2797
                if err != nil {
3✔
2798
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2799
                                err)
×
2800
                } else {
3✔
2801
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2802
                        if err != nil {
6✔
2803
                                srvrLog.Warnf("Manual update of channel "+
3✔
2804
                                        "backup failed: %v", err)
3✔
2805
                        }
3✔
2806
                }
2807

2808
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2809
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2810
                }
×
2811
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2812
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2813
                }
×
2814
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2815
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2816
                                err)
×
2817
                }
×
2818
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2819
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2820
                                err)
×
2821
                }
×
2822
                s.missionController.StopStoreTickers()
3✔
2823

3✔
2824
                // Disconnect from each active peers to ensure that
3✔
2825
                // peerTerminationWatchers signal completion to each peer.
3✔
2826
                for _, peer := range s.Peers() {
6✔
2827
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2828
                        if err != nil {
3✔
2829
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2830
                                        "received error: %v", peer.IdentityKey(),
×
2831
                                        err,
×
2832
                                )
×
2833
                        }
×
2834
                }
2835

2836
                // Now that all connections have been torn down, stop the tower
2837
                // client which will reliably flush all queued states to the
2838
                // tower. If this is halted for any reason, the force quit timer
2839
                // will kick in and abort to allow this method to return.
2840
                if s.towerClientMgr != nil {
6✔
2841
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2842
                                srvrLog.Warnf("Unable to shut down tower "+
×
2843
                                        "client manager: %v", err)
×
2844
                        }
×
2845
                }
2846

2847
                if s.hostAnn != nil {
3✔
2848
                        if err := s.hostAnn.Stop(); err != nil {
×
2849
                                srvrLog.Warnf("unable to shut down host "+
×
2850
                                        "annoucner: %v", err)
×
2851
                        }
×
2852
                }
2853

2854
                if s.livenessMonitor != nil {
6✔
2855
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2856
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2857
                                        "monitor: %v", err)
×
2858
                        }
×
2859
                }
2860

2861
                // Wait for all lingering goroutines to quit.
2862
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2863
                s.wg.Wait()
3✔
2864

3✔
2865
                srvrLog.Debug("Stopping buffer pools...")
3✔
2866
                s.sigPool.Stop()
3✔
2867
                s.writePool.Stop()
3✔
2868
                s.readPool.Stop()
3✔
2869
        })
2870

2871
        return nil
3✔
2872
}
2873

2874
// Stopped returns true if the server has been instructed to shutdown.
2875
// NOTE: This function is safe for concurrent access.
2876
func (s *server) Stopped() bool {
3✔
2877
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2878
}
3✔
2879

2880
// configurePortForwarding attempts to set up port forwarding for the different
2881
// ports that the server will be listening on.
2882
//
2883
// NOTE: This should only be used when using some kind of NAT traversal to
2884
// automatically set up forwarding rules.
2885
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2886
        ip, err := s.natTraversal.ExternalIP()
×
2887
        if err != nil {
×
2888
                return nil, err
×
2889
        }
×
2890
        s.lastDetectedIP = ip
×
2891

×
2892
        externalIPs := make([]string, 0, len(ports))
×
2893
        for _, port := range ports {
×
2894
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2895
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2896
                        continue
×
2897
                }
2898

2899
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2900
                externalIPs = append(externalIPs, hostIP)
×
2901
        }
2902

2903
        return externalIPs, nil
×
2904
}
2905

2906
// removePortForwarding attempts to clear the forwarding rules for the different
2907
// ports the server is currently listening on.
2908
//
2909
// NOTE: This should only be used when using some kind of NAT traversal to
2910
// automatically set up forwarding rules.
2911
func (s *server) removePortForwarding() {
×
2912
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2913
        for _, port := range forwardedPorts {
×
2914
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2915
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2916
                                "port %d: %v", port, err)
×
2917
                }
×
2918
        }
2919
}
2920

2921
// watchExternalIP continuously checks for an updated external IP address every
2922
// 15 minutes. Once a new IP address has been detected, it will automatically
2923
// handle port forwarding rules and send updated node announcements to the
2924
// currently connected peers.
2925
//
2926
// NOTE: This MUST be run as a goroutine.
2927
func (s *server) watchExternalIP() {
×
2928
        defer s.wg.Done()
×
2929

×
2930
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2931
        // up by the server.
×
2932
        defer s.removePortForwarding()
×
2933

×
2934
        // Keep track of the external IPs set by the user to avoid replacing
×
2935
        // them when detecting a new IP.
×
2936
        ipsSetByUser := make(map[string]struct{})
×
2937
        for _, ip := range s.cfg.ExternalIPs {
×
2938
                ipsSetByUser[ip.String()] = struct{}{}
×
2939
        }
×
2940

2941
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2942

×
2943
        ticker := time.NewTicker(15 * time.Minute)
×
2944
        defer ticker.Stop()
×
2945
out:
×
2946
        for {
×
2947
                select {
×
2948
                case <-ticker.C:
×
2949
                        // We'll start off by making sure a new IP address has
×
2950
                        // been detected.
×
2951
                        ip, err := s.natTraversal.ExternalIP()
×
2952
                        if err != nil {
×
2953
                                srvrLog.Debugf("Unable to retrieve the "+
×
2954
                                        "external IP address: %v", err)
×
2955
                                continue
×
2956
                        }
2957

2958
                        // Periodically renew the NAT port forwarding.
2959
                        for _, port := range forwardedPorts {
×
2960
                                err := s.natTraversal.AddPortMapping(port)
×
2961
                                if err != nil {
×
2962
                                        srvrLog.Warnf("Unable to automatically "+
×
2963
                                                "re-create port forwarding using %s: %v",
×
2964
                                                s.natTraversal.Name(), err)
×
2965
                                } else {
×
2966
                                        srvrLog.Debugf("Automatically re-created "+
×
2967
                                                "forwarding for port %d using %s to "+
×
2968
                                                "advertise external IP",
×
2969
                                                port, s.natTraversal.Name())
×
2970
                                }
×
2971
                        }
2972

2973
                        if ip.Equal(s.lastDetectedIP) {
×
2974
                                continue
×
2975
                        }
2976

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

×
2979
                        // Next, we'll craft the new addresses that will be
×
2980
                        // included in the new node announcement and advertised
×
2981
                        // to the network. Each address will consist of the new
×
2982
                        // IP detected and one of the currently advertised
×
2983
                        // ports.
×
2984
                        var newAddrs []net.Addr
×
2985
                        for _, port := range forwardedPorts {
×
2986
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2987
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2988
                                if err != nil {
×
2989
                                        srvrLog.Debugf("Unable to resolve "+
×
2990
                                                "host %v: %v", addr, err)
×
2991
                                        continue
×
2992
                                }
2993

2994
                                newAddrs = append(newAddrs, addr)
×
2995
                        }
2996

2997
                        // Skip the update if we weren't able to resolve any of
2998
                        // the new addresses.
2999
                        if len(newAddrs) == 0 {
×
3000
                                srvrLog.Debug("Skipping node announcement " +
×
3001
                                        "update due to not being able to " +
×
3002
                                        "resolve any new addresses")
×
3003
                                continue
×
3004
                        }
3005

3006
                        // Now, we'll need to update the addresses in our node's
3007
                        // announcement in order to propagate the update
3008
                        // throughout the network. We'll only include addresses
3009
                        // that have a different IP from the previous one, as
3010
                        // the previous IP is no longer valid.
3011
                        currentNodeAnn := s.getNodeAnnouncement()
×
3012

×
3013
                        for _, addr := range currentNodeAnn.Addresses {
×
3014
                                host, _, err := net.SplitHostPort(addr.String())
×
3015
                                if err != nil {
×
3016
                                        srvrLog.Debugf("Unable to determine "+
×
3017
                                                "host from address %v: %v",
×
3018
                                                addr, err)
×
3019
                                        continue
×
3020
                                }
3021

3022
                                // We'll also make sure to include external IPs
3023
                                // set manually by the user.
3024
                                _, setByUser := ipsSetByUser[addr.String()]
×
3025
                                if setByUser || host != s.lastDetectedIP.String() {
×
3026
                                        newAddrs = append(newAddrs, addr)
×
3027
                                }
×
3028
                        }
3029

3030
                        // Then, we'll generate a new timestamped node
3031
                        // announcement with the updated addresses and broadcast
3032
                        // it to our peers.
3033
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3034
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3035
                        )
×
3036
                        if err != nil {
×
3037
                                srvrLog.Debugf("Unable to generate new node "+
×
3038
                                        "announcement: %v", err)
×
3039
                                continue
×
3040
                        }
3041

3042
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3043
                        if err != nil {
×
3044
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3045
                                        "announcement to peers: %v", err)
×
3046
                                continue
×
3047
                        }
3048

3049
                        // Finally, update the last IP seen to the current one.
3050
                        s.lastDetectedIP = ip
×
3051
                case <-s.quit:
×
3052
                        break out
×
3053
                }
3054
        }
3055
}
3056

3057
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3058
// based on the server, and currently active bootstrap mechanisms as defined
3059
// within the current configuration.
3060
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3061
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3062

3✔
3063
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3064

3✔
3065
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3066
        // this can be used by default if we've already partially seeded the
3✔
3067
        // network.
3✔
3068
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3069
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3070
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3071
        )
3✔
3072
        if err != nil {
3✔
3073
                return nil, err
×
3074
        }
×
3075
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3076

3✔
3077
        // If this isn't using simnet or regtest mode, then one of our
3✔
3078
        // additional bootstrapping sources will be the set of running DNS
3✔
3079
        // seeds.
3✔
3080
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
3081
                //nolint:ll
×
3082
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3083

×
3084
                // If we have a set of DNS seeds for this chain, then we'll add
×
3085
                // it as an additional bootstrapping source.
×
3086
                if ok {
×
3087
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3088
                                "seeds: %v", dnsSeeds)
×
3089

×
3090
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3091
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3092
                        )
×
3093
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3094
                }
×
3095
        }
3096

3097
        return bootStrappers, nil
3✔
3098
}
3099

3100
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3101
// needs to ignore, which is made of three parts,
3102
//   - the node itself needs to be skipped as it doesn't make sense to connect
3103
//     to itself.
3104
//   - the peers that already have connections with, as in s.peersByPub.
3105
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3106
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3107
        s.mu.RLock()
3✔
3108
        defer s.mu.RUnlock()
3✔
3109

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

3✔
3112
        // We should ignore ourselves from bootstrapping.
3✔
3113
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3114
        ignore[selfKey] = struct{}{}
3✔
3115

3✔
3116
        // Ignore all connected peers.
3✔
3117
        for _, peer := range s.peersByPub {
3✔
3118
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3119
                ignore[nID] = struct{}{}
×
3120
        }
×
3121

3122
        // Ignore all persistent peers as they have a dedicated reconnecting
3123
        // process.
3124
        for pubKeyStr := range s.persistentPeers {
3✔
3125
                var nID autopilot.NodeID
×
3126
                copy(nID[:], []byte(pubKeyStr))
×
3127
                ignore[nID] = struct{}{}
×
3128
        }
×
3129

3130
        return ignore
3✔
3131
}
3132

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

3✔
3141
        defer s.wg.Done()
3✔
3142

3✔
3143
        // Before we continue, init the ignore peers map.
3✔
3144
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3145

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

3✔
3150
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3151
        // peers.
3✔
3152
        //
3✔
3153
        // We'll use a 15 second backoff, and double the time every time an
3✔
3154
        // epoch fails up to a ceiling.
3✔
3155
        backOff := time.Second * 15
3✔
3156

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

3✔
3162
        // We'll use the number of attempts and errors to determine if we need
3✔
3163
        // to increase the time between discovery epochs.
3✔
3164
        var epochErrors uint32 // To be used atomically.
3✔
3165
        var epochAttempts uint32
3✔
3166

3✔
3167
        for {
6✔
3168
                select {
3✔
3169
                // The ticker has just woken us up, so we'll need to check if
3170
                // we need to attempt to connect our to any more peers.
3171
                case <-sampleTicker.C:
×
3172
                        // Obtain the current number of peers, so we can gauge
×
3173
                        // if we need to sample more peers or not.
×
3174
                        s.mu.RLock()
×
3175
                        numActivePeers := uint32(len(s.peersByPub))
×
3176
                        s.mu.RUnlock()
×
3177

×
3178
                        // If we have enough peers, then we can loop back
×
3179
                        // around to the next round as we're done here.
×
3180
                        if numActivePeers >= numTargetPeers {
×
3181
                                continue
×
3182
                        }
3183

3184
                        // If all of our attempts failed during this last back
3185
                        // off period, then will increase our backoff to 5
3186
                        // minute ceiling to avoid an excessive number of
3187
                        // queries
3188
                        //
3189
                        // TODO(roasbeef): add reverse policy too?
3190

3191
                        if epochAttempts > 0 &&
×
3192
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3193

×
3194
                                sampleTicker.Stop()
×
3195

×
3196
                                backOff *= 2
×
3197
                                if backOff > bootstrapBackOffCeiling {
×
3198
                                        backOff = bootstrapBackOffCeiling
×
3199
                                }
×
3200

3201
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3202
                                        "%v", backOff)
×
3203
                                sampleTicker = time.NewTicker(backOff)
×
3204
                                continue
×
3205
                        }
3206

3207
                        atomic.StoreUint32(&epochErrors, 0)
×
3208
                        epochAttempts = 0
×
3209

×
3210
                        // Since we know need more peers, we'll compute the
×
3211
                        // exact number we need to reach our threshold.
×
3212
                        numNeeded := numTargetPeers - numActivePeers
×
3213

×
3214
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3215
                                "peers", numNeeded)
×
3216

×
3217
                        // With the number of peers we need calculated, we'll
×
3218
                        // query the network bootstrappers to sample a set of
×
3219
                        // random addrs for us.
×
3220
                        //
×
3221
                        // Before we continue, get a copy of the ignore peers
×
3222
                        // map.
×
3223
                        ignoreList = s.createBootstrapIgnorePeers()
×
3224

×
3225
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3226
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3227
                        )
×
3228
                        if err != nil {
×
3229
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3230
                                        "peers: %v", err)
×
3231
                                continue
×
3232
                        }
3233

3234
                        // Finally, we'll launch a new goroutine for each
3235
                        // prospective peer candidates.
3236
                        for _, addr := range peerAddrs {
×
3237
                                epochAttempts++
×
3238

×
3239
                                go func(a *lnwire.NetAddress) {
×
3240
                                        // TODO(roasbeef): can do AS, subnet,
×
3241
                                        // country diversity, etc
×
3242
                                        errChan := make(chan error, 1)
×
3243
                                        s.connectToPeer(
×
3244
                                                a, errChan,
×
3245
                                                s.cfg.ConnectionTimeout,
×
3246
                                        )
×
3247
                                        select {
×
3248
                                        case err := <-errChan:
×
3249
                                                if err == nil {
×
3250
                                                        return
×
3251
                                                }
×
3252

3253
                                                srvrLog.Errorf("Unable to "+
×
3254
                                                        "connect to %v: %v",
×
3255
                                                        a, err)
×
3256
                                                atomic.AddUint32(&epochErrors, 1)
×
3257
                                        case <-s.quit:
×
3258
                                        }
3259
                                }(addr)
3260
                        }
3261
                case <-s.quit:
3✔
3262
                        return
3✔
3263
                }
3264
        }
3265
}
3266

3267
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3268
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3269
// query back off each time we encounter a failure.
3270
const bootstrapBackOffCeiling = time.Minute * 5
3271

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

3✔
3279
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3280
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3281

3✔
3282
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3283
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3284
        var delaySignal <-chan time.Time
3✔
3285
        delayTime := time.Second * 2
3✔
3286

3✔
3287
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3288
        // then the main peer bootstrap logic.
3✔
3289
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3290

3✔
3291
        for attempts := 0; ; attempts++ {
6✔
3292
                // Check if the server has been requested to shut down in order
3✔
3293
                // to prevent blocking.
3✔
3294
                if s.Stopped() {
3✔
3295
                        return
×
3296
                }
×
3297

3298
                // We can exit our aggressive initial peer bootstrapping stage
3299
                // if we've reached out target number of peers.
3300
                s.mu.RLock()
3✔
3301
                numActivePeers := uint32(len(s.peersByPub))
3✔
3302
                s.mu.RUnlock()
3✔
3303

3✔
3304
                if numActivePeers >= numTargetPeers {
6✔
3305
                        return
3✔
3306
                }
3✔
3307

3308
                if attempts > 0 {
3✔
3309
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3310
                                "bootstrap peers (attempt #%v)", delayTime,
×
3311
                                attempts)
×
3312

×
3313
                        // We've completed at least one iterating and haven't
×
3314
                        // finished, so we'll start to insert a delay period
×
3315
                        // between each attempt.
×
3316
                        delaySignal = time.After(delayTime)
×
3317
                        select {
×
3318
                        case <-delaySignal:
×
3319
                        case <-s.quit:
×
3320
                                return
×
3321
                        }
3322

3323
                        // After our delay, we'll double the time we wait up to
3324
                        // the max back off period.
3325
                        delayTime *= 2
×
3326
                        if delayTime > backOffCeiling {
×
3327
                                delayTime = backOffCeiling
×
3328
                        }
×
3329
                }
3330

3331
                // Otherwise, we'll request for the remaining number of peers
3332
                // in order to reach our target.
3333
                peersNeeded := numTargetPeers - numActivePeers
3✔
3334
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3335
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3336
                )
3✔
3337
                if err != nil {
3✔
3338
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3339
                                "peers: %v", err)
×
3340
                        continue
×
3341
                }
3342

3343
                // Then, we'll attempt to establish a connection to the
3344
                // different peer addresses retrieved by our bootstrappers.
3345
                var wg sync.WaitGroup
3✔
3346
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3347
                        wg.Add(1)
3✔
3348
                        go func(addr *lnwire.NetAddress) {
6✔
3349
                                defer wg.Done()
3✔
3350

3✔
3351
                                errChan := make(chan error, 1)
3✔
3352
                                go s.connectToPeer(
3✔
3353
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3354
                                )
3✔
3355

3✔
3356
                                // We'll only allow this connection attempt to
3✔
3357
                                // take up to 3 seconds. This allows us to move
3✔
3358
                                // quickly by discarding peers that are slowing
3✔
3359
                                // us down.
3✔
3360
                                select {
3✔
3361
                                case err := <-errChan:
3✔
3362
                                        if err == nil {
6✔
3363
                                                return
3✔
3364
                                        }
3✔
3365
                                        srvrLog.Errorf("Unable to connect to "+
×
3366
                                                "%v: %v", addr, err)
×
3367
                                // TODO: tune timeout? 3 seconds might be *too*
3368
                                // aggressive but works well.
3369
                                case <-time.After(3 * time.Second):
×
3370
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3371
                                                "to not establishing a "+
×
3372
                                                "connection within 3 seconds",
×
3373
                                                addr)
×
3374
                                case <-s.quit:
×
3375
                                }
3376
                        }(bootstrapAddr)
3377
                }
3378

3379
                wg.Wait()
3✔
3380
        }
3381
}
3382

3383
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3384
// order to listen for inbound connections over Tor.
3385
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3386
        // Determine the different ports the server is listening on. The onion
×
3387
        // service's virtual port will map to these ports and one will be picked
×
3388
        // at random when the onion service is being accessed.
×
3389
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3390
        for _, listenAddr := range s.listenAddrs {
×
3391
                port := listenAddr.(*net.TCPAddr).Port
×
3392
                listenPorts = append(listenPorts, port)
×
3393
        }
×
3394

3395
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3396
        if err != nil {
×
3397
                return err
×
3398
        }
×
3399

3400
        // Once the port mapping has been set, we can go ahead and automatically
3401
        // create our onion service. The service's private key will be saved to
3402
        // disk in order to regain access to this service when restarting `lnd`.
3403
        onionCfg := tor.AddOnionConfig{
×
3404
                VirtualPort: defaultPeerPort,
×
3405
                TargetPorts: listenPorts,
×
3406
                Store: tor.NewOnionFile(
×
3407
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3408
                        encrypter,
×
3409
                ),
×
3410
        }
×
3411

×
3412
        switch {
×
3413
        case s.cfg.Tor.V2:
×
3414
                onionCfg.Type = tor.V2
×
3415
        case s.cfg.Tor.V3:
×
3416
                onionCfg.Type = tor.V3
×
3417
        }
3418

3419
        addr, err := s.torController.AddOnion(onionCfg)
×
3420
        if err != nil {
×
3421
                return err
×
3422
        }
×
3423

3424
        // Now that the onion service has been created, we'll add the onion
3425
        // address it can be reached at to our list of advertised addresses.
3426
        newNodeAnn, err := s.genNodeAnnouncement(
×
3427
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3428
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3429
                },
×
3430
        )
3431
        if err != nil {
×
3432
                return fmt.Errorf("unable to generate new node "+
×
3433
                        "announcement: %v", err)
×
3434
        }
×
3435

3436
        // Finally, we'll update the on-disk version of our announcement so it
3437
        // will eventually propagate to nodes in the network.
3438
        selfNode := &models.LightningNode{
×
3439
                HaveNodeAnnouncement: true,
×
3440
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3441
                Addresses:            newNodeAnn.Addresses,
×
3442
                Alias:                newNodeAnn.Alias.String(),
×
3443
                Features: lnwire.NewFeatureVector(
×
3444
                        newNodeAnn.Features, lnwire.Features,
×
3445
                ),
×
3446
                Color:        newNodeAnn.RGBColor,
×
3447
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3448
        }
×
3449
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3450
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3451
                return fmt.Errorf("can't set self node: %w", err)
×
3452
        }
×
3453

3454
        return nil
×
3455
}
3456

3457
// findChannel finds a channel given a public key and ChannelID. It is an
3458
// optimization that is quicker than seeking for a channel given only the
3459
// ChannelID.
3460
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3461
        *channeldb.OpenChannel, error) {
3✔
3462

3✔
3463
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3464
        if err != nil {
3✔
3465
                return nil, err
×
3466
        }
×
3467

3468
        for _, channel := range nodeChans {
6✔
3469
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3470
                        return channel, nil
3✔
3471
                }
3✔
3472
        }
3473

3474
        return nil, fmt.Errorf("unable to find channel")
3✔
3475
}
3476

3477
// getNodeAnnouncement fetches the current, fully signed node announcement.
3478
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3479
        s.mu.Lock()
3✔
3480
        defer s.mu.Unlock()
3✔
3481

3✔
3482
        return *s.currentNodeAnn
3✔
3483
}
3✔
3484

3485
// genNodeAnnouncement generates and returns the current fully signed node
3486
// announcement. The time stamp of the announcement will be updated in order
3487
// to ensure it propagates through the network.
3488
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3489
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3490

3✔
3491
        s.mu.Lock()
3✔
3492
        defer s.mu.Unlock()
3✔
3493

3✔
3494
        // Create a shallow copy of the current node announcement to work on.
3✔
3495
        // This ensures the original announcement remains unchanged
3✔
3496
        // until the new announcement is fully signed and valid.
3✔
3497
        newNodeAnn := *s.currentNodeAnn
3✔
3498

3✔
3499
        // First, try to update our feature manager with the updated set of
3✔
3500
        // features.
3✔
3501
        if features != nil {
6✔
3502
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3503
                        feature.SetNodeAnn: features,
3✔
3504
                }
3✔
3505
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3506
                if err != nil {
6✔
3507
                        return lnwire.NodeAnnouncement{}, err
3✔
3508
                }
3✔
3509

3510
                // If we could successfully update our feature manager, add
3511
                // an update modifier to include these new features to our
3512
                // set.
3513
                modifiers = append(
3✔
3514
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3515
                )
3✔
3516
        }
3517

3518
        // Always update the timestamp when refreshing to ensure the update
3519
        // propagates.
3520
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3521

3✔
3522
        // Apply the requested changes to the node announcement.
3✔
3523
        for _, modifier := range modifiers {
6✔
3524
                modifier(&newNodeAnn)
3✔
3525
        }
3✔
3526

3527
        // Sign a new update after applying all of the passed modifiers.
3528
        err := netann.SignNodeAnnouncement(
3✔
3529
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3530
        )
3✔
3531
        if err != nil {
3✔
3532
                return lnwire.NodeAnnouncement{}, err
×
3533
        }
×
3534

3535
        // If signing succeeds, update the current announcement.
3536
        *s.currentNodeAnn = newNodeAnn
3✔
3537

3✔
3538
        return *s.currentNodeAnn, nil
3✔
3539
}
3540

3541
// updateAndBroadcastSelfNode generates a new node announcement
3542
// applying the giving modifiers and updating the time stamp
3543
// to ensure it propagates through the network. Then it broadcasts
3544
// it to the network.
3545
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3546
        features *lnwire.RawFeatureVector,
3547
        modifiers ...netann.NodeAnnModifier) error {
3✔
3548

3✔
3549
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3550
        if err != nil {
6✔
3551
                return fmt.Errorf("unable to generate new node "+
3✔
3552
                        "announcement: %v", err)
3✔
3553
        }
3✔
3554

3555
        // Update the on-disk version of our announcement.
3556
        // Load and modify self node istead of creating anew instance so we
3557
        // don't risk overwriting any existing values.
3558
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3559
        if err != nil {
3✔
3560
                return fmt.Errorf("unable to get current source node: %w", err)
×
3561
        }
×
3562

3563
        selfNode.HaveNodeAnnouncement = true
3✔
3564
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3565
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3566
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3567
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3568
        selfNode.Color = newNodeAnn.RGBColor
3✔
3569
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3570

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

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

3577
        // Finally, propagate it to the nodes in the network.
3578
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3579
        if err != nil {
3✔
3580
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3581
                        "announcement to peers: %v", err)
×
3582
                return err
×
3583
        }
×
3584

3585
        return nil
3✔
3586
}
3587

3588
type nodeAddresses struct {
3589
        pubKey    *btcec.PublicKey
3590
        addresses []net.Addr
3591
}
3592

3593
// establishPersistentConnections attempts to establish persistent connections
3594
// to all our direct channel collaborators. In order to promote liveness of our
3595
// active channels, we instruct the connection manager to attempt to establish
3596
// and maintain persistent connections to all our direct channel counterparties.
3597
func (s *server) establishPersistentConnections() error {
3✔
3598
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3599
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3600
        // since other PubKey forms can't be compared.
3✔
3601
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3602

3✔
3603
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3604
        // attempt to connect to based on our set of previous connections. Set
3✔
3605
        // the reconnection port to the default peer port.
3✔
3606
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3607
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3608
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3609
        }
×
3610

3611
        for _, node := range linkNodes {
6✔
3612
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3613
                nodeAddrs := &nodeAddresses{
3✔
3614
                        pubKey:    node.IdentityPub,
3✔
3615
                        addresses: node.Addresses,
3✔
3616
                }
3✔
3617
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3618
        }
3✔
3619

3620
        // After checking our previous connections for addresses to connect to,
3621
        // iterate through the nodes in our channel graph to find addresses
3622
        // that have been added via NodeAnnouncement messages.
3623
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3624
        // each of the nodes.
3625
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3626
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3627

3✔
3628
                // If the remote party has announced the channel to us, but we
3✔
3629
                // haven't yet, then we won't have a policy. However, we don't
3✔
3630
                // need this to connect to the peer, so we'll log it and move on.
3✔
3631
                if !havePolicy {
3✔
3632
                        srvrLog.Warnf("No channel policy found for "+
×
3633
                                "ChannelPoint(%v): ", chanPoint)
×
3634
                }
×
3635

3636
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3637

3✔
3638
                // Add all unique addresses from channel
3✔
3639
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3640
                // connect to for this peer.
3✔
3641
                addrSet := make(map[string]net.Addr)
3✔
3642
                for _, addr := range channelPeer.Addresses {
6✔
3643
                        switch addr.(type) {
3✔
3644
                        case *net.TCPAddr:
3✔
3645
                                addrSet[addr.String()] = addr
3✔
3646

3647
                        // We'll only attempt to connect to Tor addresses if Tor
3648
                        // outbound support is enabled.
3649
                        case *tor.OnionAddr:
×
3650
                                if s.cfg.Tor.Active {
×
3651
                                        addrSet[addr.String()] = addr
×
3652
                                }
×
3653
                        }
3654
                }
3655

3656
                // If this peer is also recorded as a link node, we'll add any
3657
                // additional addresses that have not already been selected.
3658
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3659
                if ok {
6✔
3660
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3661
                                switch lnAddress.(type) {
3✔
3662
                                case *net.TCPAddr:
3✔
3663
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3664

3665
                                // We'll only attempt to connect to Tor
3666
                                // addresses if Tor outbound support is enabled.
3667
                                case *tor.OnionAddr:
×
3668
                                        if s.cfg.Tor.Active {
×
3669
                                                addrSet[lnAddress.String()] = lnAddress
×
3670
                                        }
×
3671
                                }
3672
                        }
3673
                }
3674

3675
                // Construct a slice of the deduped addresses.
3676
                var addrs []net.Addr
3✔
3677
                for _, addr := range addrSet {
6✔
3678
                        addrs = append(addrs, addr)
3✔
3679
                }
3✔
3680

3681
                n := &nodeAddresses{
3✔
3682
                        addresses: addrs,
3✔
3683
                }
3✔
3684
                n.pubKey, err = channelPeer.PubKey()
3✔
3685
                if err != nil {
3✔
3686
                        return err
×
3687
                }
×
3688

3689
                nodeAddrsMap[pubStr] = n
3✔
3690
                return nil
3✔
3691
        })
3692
        if err != nil {
3✔
3693
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3694
                        "%v", err)
×
3695

×
3696
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3697
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3698

×
3699
                        return err
×
3700
                }
×
3701
        }
3702

3703
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3704
                len(nodeAddrsMap))
3✔
3705

3✔
3706
        // Acquire and hold server lock until all persistent connection requests
3✔
3707
        // have been recorded and sent to the connection manager.
3✔
3708
        s.mu.Lock()
3✔
3709
        defer s.mu.Unlock()
3✔
3710

3✔
3711
        // Iterate through the combined list of addresses from prior links and
3✔
3712
        // node announcements and attempt to reconnect to each node.
3✔
3713
        var numOutboundConns int
3✔
3714
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3715
                // Add this peer to the set of peers we should maintain a
3✔
3716
                // persistent connection with. We set the value to false to
3✔
3717
                // indicate that we should not continue to reconnect if the
3✔
3718
                // number of channels returns to zero, since this peer has not
3✔
3719
                // been requested as perm by the user.
3✔
3720
                s.persistentPeers[pubStr] = false
3✔
3721
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3722
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3723
                }
3✔
3724

3725
                for _, address := range nodeAddr.addresses {
6✔
3726
                        // Create a wrapper address which couples the IP and
3✔
3727
                        // the pubkey so the brontide authenticated connection
3✔
3728
                        // can be established.
3✔
3729
                        lnAddr := &lnwire.NetAddress{
3✔
3730
                                IdentityKey: nodeAddr.pubKey,
3✔
3731
                                Address:     address,
3✔
3732
                        }
3✔
3733

3✔
3734
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3735
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3736
                }
3✔
3737

3738
                // We'll connect to the first 10 peers immediately, then
3739
                // randomly stagger any remaining connections if the
3740
                // stagger initial reconnect flag is set. This ensures
3741
                // that mobile nodes or nodes with a small number of
3742
                // channels obtain connectivity quickly, but larger
3743
                // nodes are able to disperse the costs of connecting to
3744
                // all peers at once.
3745
                if numOutboundConns < numInstantInitReconnect ||
3✔
3746
                        !s.cfg.StaggerInitialReconnect {
6✔
3747

3✔
3748
                        go s.connectToPersistentPeer(pubStr)
3✔
3749
                } else {
3✔
3750
                        go s.delayInitialReconnect(pubStr)
×
3751
                }
×
3752

3753
                numOutboundConns++
3✔
3754
        }
3755

3756
        return nil
3✔
3757
}
3758

3759
// delayInitialReconnect will attempt a reconnection to the given peer after
3760
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3761
//
3762
// NOTE: This method MUST be run as a goroutine.
3763
func (s *server) delayInitialReconnect(pubStr string) {
×
3764
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3765
        select {
×
3766
        case <-time.After(delay):
×
3767
                s.connectToPersistentPeer(pubStr)
×
3768
        case <-s.quit:
×
3769
        }
3770
}
3771

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

3✔
3778
        s.mu.Lock()
3✔
3779
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3780
                delete(s.persistentPeers, pubKeyStr)
3✔
3781
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3782
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3783
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3784
                s.mu.Unlock()
3✔
3785

3✔
3786
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3787
                        "peer has no open channels", compressedPubKey)
3✔
3788

3✔
3789
                return
3✔
3790
        }
3✔
3791
        s.mu.Unlock()
3✔
3792
}
3793

3794
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3795
// is instead used to remove persistent peer state for a peer that has been
3796
// disconnected for good cause by the server. Currently, a gossip ban from
3797
// sending garbage and the server running out of restricted-access
3798
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3799
// future, this function may expand when more ban criteria is added.
3800
//
3801
// NOTE: The server's write lock MUST be held when this is called.
3802
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3803
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3804
                delete(s.persistentPeers, remotePub)
×
3805
                delete(s.persistentPeersBackoff, remotePub)
×
3806
                delete(s.persistentPeerAddrs, remotePub)
×
3807
                s.cancelConnReqs(remotePub, nil)
×
3808
        }
×
3809
}
3810

3811
// BroadcastMessage sends a request to the server to broadcast a set of
3812
// messages to all peers other than the one specified by the `skips` parameter.
3813
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3814
// the target peers.
3815
//
3816
// NOTE: This function is safe for concurrent access.
3817
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3818
        msgs ...lnwire.Message) error {
3✔
3819

3✔
3820
        // Filter out peers found in the skips map. We synchronize access to
3✔
3821
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3822
        // exact set of peers present at the time of invocation.
3✔
3823
        s.mu.RLock()
3✔
3824
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3825
        for pubStr, sPeer := range s.peersByPub {
6✔
3826
                if skips != nil {
6✔
3827
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3828
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3829
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3830
                                continue
3✔
3831
                        }
3832
                }
3833

3834
                peers = append(peers, sPeer)
3✔
3835
        }
3836
        s.mu.RUnlock()
3✔
3837

3✔
3838
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3839
        // all messages to each of peers.
3✔
3840
        var wg sync.WaitGroup
3✔
3841
        for _, sPeer := range peers {
6✔
3842
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3843
                        sPeer.PubKey())
3✔
3844

3✔
3845
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3846
                wg.Add(1)
3✔
3847
                s.wg.Add(1)
3✔
3848
                go func(p lnpeer.Peer) {
6✔
3849
                        defer s.wg.Done()
3✔
3850
                        defer wg.Done()
3✔
3851

3✔
3852
                        p.SendMessageLazy(false, msgs...)
3✔
3853
                }(sPeer)
3✔
3854
        }
3855

3856
        // Wait for all messages to have been dispatched before returning to
3857
        // caller.
3858
        wg.Wait()
3✔
3859

3✔
3860
        return nil
3✔
3861
}
3862

3863
// NotifyWhenOnline can be called by other subsystems to get notified when a
3864
// particular peer comes online. The peer itself is sent across the peerChan.
3865
//
3866
// NOTE: This function is safe for concurrent access.
3867
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3868
        peerChan chan<- lnpeer.Peer) {
3✔
3869

3✔
3870
        s.mu.Lock()
3✔
3871

3✔
3872
        // Compute the target peer's identifier.
3✔
3873
        pubStr := string(peerKey[:])
3✔
3874

3✔
3875
        // Check if peer is connected.
3✔
3876
        peer, ok := s.peersByPub[pubStr]
3✔
3877
        if ok {
6✔
3878
                // Unlock here so that the mutex isn't held while we are
3✔
3879
                // waiting for the peer to become active.
3✔
3880
                s.mu.Unlock()
3✔
3881

3✔
3882
                // Wait until the peer signals that it is actually active
3✔
3883
                // rather than only in the server's maps.
3✔
3884
                select {
3✔
3885
                case <-peer.ActiveSignal():
3✔
3886
                case <-peer.QuitSignal():
1✔
3887
                        // The peer quit, so we'll add the channel to the slice
1✔
3888
                        // and return.
1✔
3889
                        s.mu.Lock()
1✔
3890
                        s.peerConnectedListeners[pubStr] = append(
1✔
3891
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3892
                        )
1✔
3893
                        s.mu.Unlock()
1✔
3894
                        return
1✔
3895
                }
3896

3897
                // Connected, can return early.
3898
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3899

3✔
3900
                select {
3✔
3901
                case peerChan <- peer:
3✔
UNCOV
3902
                case <-s.quit:
×
3903
                }
3904

3905
                return
3✔
3906
        }
3907

3908
        // Not connected, store this listener such that it can be notified when
3909
        // the peer comes online.
3910
        s.peerConnectedListeners[pubStr] = append(
3✔
3911
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3912
        )
3✔
3913
        s.mu.Unlock()
3✔
3914
}
3915

3916
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3917
// the given public key has been disconnected. The notification is signaled by
3918
// closing the channel returned.
3919
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3920
        s.mu.Lock()
3✔
3921
        defer s.mu.Unlock()
3✔
3922

3✔
3923
        c := make(chan struct{})
3✔
3924

3✔
3925
        // If the peer is already offline, we can immediately trigger the
3✔
3926
        // notification.
3✔
3927
        peerPubKeyStr := string(peerPubKey[:])
3✔
3928
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3929
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3930
                close(c)
×
3931
                return c
×
3932
        }
×
3933

3934
        // Otherwise, the peer is online, so we'll keep track of the channel to
3935
        // trigger the notification once the server detects the peer
3936
        // disconnects.
3937
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3938
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3939
        )
3✔
3940

3✔
3941
        return c
3✔
3942
}
3943

3944
// FindPeer will return the peer that corresponds to the passed in public key.
3945
// This function is used by the funding manager, allowing it to update the
3946
// daemon's local representation of the remote peer.
3947
//
3948
// NOTE: This function is safe for concurrent access.
3949
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3950
        s.mu.RLock()
3✔
3951
        defer s.mu.RUnlock()
3✔
3952

3✔
3953
        pubStr := string(peerKey.SerializeCompressed())
3✔
3954

3✔
3955
        return s.findPeerByPubStr(pubStr)
3✔
3956
}
3✔
3957

3958
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3959
// which should be a string representation of the peer's serialized, compressed
3960
// public key.
3961
//
3962
// NOTE: This function is safe for concurrent access.
3963
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3964
        s.mu.RLock()
3✔
3965
        defer s.mu.RUnlock()
3✔
3966

3✔
3967
        return s.findPeerByPubStr(pubStr)
3✔
3968
}
3✔
3969

3970
// findPeerByPubStr is an internal method that retrieves the specified peer from
3971
// the server's internal state using.
3972
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3973
        peer, ok := s.peersByPub[pubStr]
3✔
3974
        if !ok {
6✔
3975
                return nil, ErrPeerNotConnected
3✔
3976
        }
3✔
3977

3978
        return peer, nil
3✔
3979
}
3980

3981
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3982
// exponential backoff. If no previous backoff was known, the default is
3983
// returned.
3984
func (s *server) nextPeerBackoff(pubStr string,
3985
        startTime time.Time) time.Duration {
3✔
3986

3✔
3987
        // Now, determine the appropriate backoff to use for the retry.
3✔
3988
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3989
        if !ok {
6✔
3990
                // If an existing backoff was unknown, use the default.
3✔
3991
                return s.cfg.MinBackoff
3✔
3992
        }
3✔
3993

3994
        // If the peer failed to start properly, we'll just use the previous
3995
        // backoff to compute the subsequent randomized exponential backoff
3996
        // duration. This will roughly double on average.
3997
        if startTime.IsZero() {
3✔
3998
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3999
        }
×
4000

4001
        // The peer succeeded in starting. If the connection didn't last long
4002
        // enough to be considered stable, we'll continue to back off retries
4003
        // with this peer.
4004
        connDuration := time.Since(startTime)
3✔
4005
        if connDuration < defaultStableConnDuration {
6✔
4006
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4007
        }
3✔
4008

4009
        // The peer succeed in starting and this was stable peer, so we'll
4010
        // reduce the timeout duration by the length of the connection after
4011
        // applying randomized exponential backoff. We'll only apply this in the
4012
        // case that:
4013
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4014
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4015
        if relaxedBackoff > s.cfg.MinBackoff {
×
4016
                return relaxedBackoff
×
4017
        }
×
4018

4019
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4020
        // the stable connection lasted much longer than our previous backoff.
4021
        // To reward such good behavior, we'll reconnect after the default
4022
        // timeout.
4023
        return s.cfg.MinBackoff
×
4024
}
4025

4026
// shouldDropLocalConnection determines if our local connection to a remote peer
4027
// should be dropped in the case of concurrent connection establishment. In
4028
// order to deterministically decide which connection should be dropped, we'll
4029
// utilize the ordering of the local and remote public key. If we didn't use
4030
// such a tie breaker, then we risk _both_ connections erroneously being
4031
// dropped.
4032
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4033
        localPubBytes := local.SerializeCompressed()
×
4034
        remotePubPbytes := remote.SerializeCompressed()
×
4035

×
4036
        // The connection that comes from the node with a "smaller" pubkey
×
4037
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4038
        // should drop our established connection.
×
4039
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4040
}
×
4041

4042
// InboundPeerConnected initializes a new peer in response to a new inbound
4043
// connection.
4044
//
4045
// NOTE: This function is safe for concurrent access.
4046
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4047
        // Exit early if we have already been instructed to shutdown, this
3✔
4048
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4049
        if s.Stopped() {
3✔
4050
                return
×
4051
        }
×
4052

4053
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4054
        pubSer := nodePub.SerializeCompressed()
3✔
4055
        pubStr := string(pubSer)
3✔
4056

3✔
4057
        var pubBytes [33]byte
3✔
4058
        copy(pubBytes[:], pubSer)
3✔
4059

3✔
4060
        s.mu.Lock()
3✔
4061
        defer s.mu.Unlock()
3✔
4062

3✔
4063
        // If we already have an outbound connection to this peer, then ignore
3✔
4064
        // this new connection.
3✔
4065
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4066
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4067
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4068
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4069

3✔
4070
                conn.Close()
3✔
4071
                return
3✔
4072
        }
3✔
4073

4074
        // If we already have a valid connection that is scheduled to take
4075
        // precedence once the prior peer has finished disconnecting, we'll
4076
        // ignore this connection.
4077
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4078
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4079
                        "scheduled", conn.RemoteAddr(), p)
×
4080
                conn.Close()
×
4081
                return
×
4082
        }
×
4083

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

3✔
4086
        // Check to see if we already have a connection with this peer. If so,
3✔
4087
        // we may need to drop our existing connection. This prevents us from
3✔
4088
        // having duplicate connections to the same peer. We forgo adding a
3✔
4089
        // default case as we expect these to be the only error values returned
3✔
4090
        // from findPeerByPubStr.
3✔
4091
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4092
        switch err {
3✔
4093
        case ErrPeerNotConnected:
3✔
4094
                // We were unable to locate an existing connection with the
3✔
4095
                // target peer, proceed to connect.
3✔
4096
                s.cancelConnReqs(pubStr, nil)
3✔
4097
                s.peerConnected(conn, nil, true)
3✔
4098

4099
        case nil:
3✔
4100
                ctx := btclog.WithCtx(
3✔
4101
                        context.TODO(),
3✔
4102
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4103
                )
3✔
4104

3✔
4105
                // We already have a connection with the incoming peer. If the
3✔
4106
                // connection we've already established should be kept and is
3✔
4107
                // not of the same type of the new connection (inbound), then
3✔
4108
                // we'll close out the new connection s.t there's only a single
3✔
4109
                // connection between us.
3✔
4110
                localPub := s.identityECDH.PubKey()
3✔
4111
                if !connectedPeer.Inbound() &&
3✔
4112
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4113

×
4114
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4115
                                "peer, but already have outbound "+
×
4116
                                "connection, dropping conn",
×
4117
                                fmt.Errorf("already have outbound conn"))
×
4118
                        conn.Close()
×
4119
                        return
×
4120
                }
×
4121

4122
                // Otherwise, if we should drop the connection, then we'll
4123
                // disconnect our already connected peer.
4124
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4125

3✔
4126
                s.cancelConnReqs(pubStr, nil)
3✔
4127

3✔
4128
                // Remove the current peer from the server's internal state and
3✔
4129
                // signal that the peer termination watcher does not need to
3✔
4130
                // execute for this peer.
3✔
4131
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4132
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4133
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4134
                        s.peerConnected(conn, nil, true)
3✔
4135
                }
3✔
4136
        }
4137
}
4138

4139
// OutboundPeerConnected initializes a new peer in response to a new outbound
4140
// connection.
4141
// NOTE: This function is safe for concurrent access.
4142
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4143
        // Exit early if we have already been instructed to shutdown, this
3✔
4144
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4145
        if s.Stopped() {
3✔
4146
                return
×
4147
        }
×
4148

4149
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4150
        pubSer := nodePub.SerializeCompressed()
3✔
4151
        pubStr := string(pubSer)
3✔
4152

3✔
4153
        var pubBytes [33]byte
3✔
4154
        copy(pubBytes[:], pubSer)
3✔
4155

3✔
4156
        s.mu.Lock()
3✔
4157
        defer s.mu.Unlock()
3✔
4158

3✔
4159
        // If we already have an inbound connection to this peer, then ignore
3✔
4160
        // this new connection.
3✔
4161
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4162
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4163
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4164
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4165

3✔
4166
                if connReq != nil {
6✔
4167
                        s.connMgr.Remove(connReq.ID())
3✔
4168
                }
3✔
4169
                conn.Close()
3✔
4170
                return
3✔
4171
        }
4172
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4173
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4174
                s.connMgr.Remove(connReq.ID())
×
4175
                conn.Close()
×
4176
                return
×
4177
        }
×
4178

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

×
4185
                if connReq != nil {
×
4186
                        s.connMgr.Remove(connReq.ID())
×
4187
                }
×
4188

4189
                conn.Close()
×
4190
                return
×
4191
        }
4192

4193
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4194
                conn.RemoteAddr())
3✔
4195

3✔
4196
        if connReq != nil {
6✔
4197
                // A successful connection was returned by the connmgr.
3✔
4198
                // Immediately cancel all pending requests, excluding the
3✔
4199
                // outbound connection we just established.
3✔
4200
                ignore := connReq.ID()
3✔
4201
                s.cancelConnReqs(pubStr, &ignore)
3✔
4202
        } else {
6✔
4203
                // This was a successful connection made by some other
3✔
4204
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4205
                s.cancelConnReqs(pubStr, nil)
3✔
4206
        }
3✔
4207

4208
        // If we already have a connection with this peer, decide whether or not
4209
        // we need to drop the stale connection. We forgo adding a default case
4210
        // as we expect these to be the only error values returned from
4211
        // findPeerByPubStr.
4212
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4213
        switch err {
3✔
4214
        case ErrPeerNotConnected:
3✔
4215
                // We were unable to locate an existing connection with the
3✔
4216
                // target peer, proceed to connect.
3✔
4217
                s.peerConnected(conn, connReq, false)
3✔
4218

4219
        case nil:
3✔
4220
                ctx := btclog.WithCtx(
3✔
4221
                        context.TODO(),
3✔
4222
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4223
                )
3✔
4224

3✔
4225
                // We already have a connection with the incoming peer. If the
3✔
4226
                // connection we've already established should be kept and is
3✔
4227
                // not of the same type of the new connection (outbound), then
3✔
4228
                // we'll close out the new connection s.t there's only a single
3✔
4229
                // connection between us.
3✔
4230
                localPub := s.identityECDH.PubKey()
3✔
4231
                if connectedPeer.Inbound() &&
3✔
4232
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4233

×
4234
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4235
                                "to peer, but already have inbound "+
×
4236
                                "connection, dropping conn",
×
4237
                                fmt.Errorf("already have inbound conn"))
×
4238
                        if connReq != nil {
×
4239
                                s.connMgr.Remove(connReq.ID())
×
4240
                        }
×
4241
                        conn.Close()
×
4242
                        return
×
4243
                }
4244

4245
                // Otherwise, _their_ connection should be dropped. So we'll
4246
                // disconnect the peer and send the now obsolete peer to the
4247
                // server for garbage collection.
4248
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4249

3✔
4250
                // Remove the current peer from the server's internal state and
3✔
4251
                // signal that the peer termination watcher does not need to
3✔
4252
                // execute for this peer.
3✔
4253
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4254
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4255
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4256
                        s.peerConnected(conn, connReq, false)
3✔
4257
                }
3✔
4258
        }
4259
}
4260

4261
// UnassignedConnID is the default connection ID that a request can have before
4262
// it actually is submitted to the connmgr.
4263
// TODO(conner): move into connmgr package, or better, add connmgr method for
4264
// generating atomic IDs
4265
const UnassignedConnID uint64 = 0
4266

4267
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4268
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4269
// Afterwards, each connection request removed from the connmgr. The caller can
4270
// optionally specify a connection ID to ignore, which prevents us from
4271
// canceling a successful request. All persistent connreqs for the provided
4272
// pubkey are discarded after the operationjw.
4273
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4274
        // First, cancel any lingering persistent retry attempts, which will
3✔
4275
        // prevent retries for any with backoffs that are still maturing.
3✔
4276
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4277
                close(cancelChan)
3✔
4278
                delete(s.persistentRetryCancels, pubStr)
3✔
4279
        }
3✔
4280

4281
        // Next, check to see if we have any outstanding persistent connection
4282
        // requests to this peer. If so, then we'll remove all of these
4283
        // connection requests, and also delete the entry from the map.
4284
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4285
        if !ok {
6✔
4286
                return
3✔
4287
        }
3✔
4288

4289
        for _, connReq := range connReqs {
6✔
4290
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4291

3✔
4292
                // Atomically capture the current request identifier.
3✔
4293
                connID := connReq.ID()
3✔
4294

3✔
4295
                // Skip any zero IDs, this indicates the request has not
3✔
4296
                // yet been schedule.
3✔
4297
                if connID == UnassignedConnID {
3✔
4298
                        continue
×
4299
                }
4300

4301
                // Skip a particular connection ID if instructed.
4302
                if skip != nil && connID == *skip {
6✔
4303
                        continue
3✔
4304
                }
4305

4306
                s.connMgr.Remove(connID)
3✔
4307
        }
4308

4309
        delete(s.persistentConnReqs, pubStr)
3✔
4310
}
4311

4312
// handleCustomMessage dispatches an incoming custom peers message to
4313
// subscribers.
4314
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4315
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4316
                peer, msg.Type)
3✔
4317

3✔
4318
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4319
                Peer: peer,
3✔
4320
                Msg:  msg,
3✔
4321
        })
3✔
4322
}
3✔
4323

4324
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4325
// messages.
4326
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4327
        return s.customMessageServer.Subscribe()
3✔
4328
}
3✔
4329

4330
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4331
// the channelNotifier's NotifyOpenChannelEvent.
4332
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4333
        remotePub *btcec.PublicKey) {
3✔
4334

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

4341
        // Notify subscribers about this open channel event.
4342
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4343
}
4344

4345
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4346
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4347
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4348
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4349

3✔
4350
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4351
        // peer.
3✔
4352
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4353
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4354
                        "channel[%v] pending open",
×
4355
                        remotePub.SerializeCompressed(), op)
×
4356
        }
×
4357

4358
        // Notify subscribers about this event.
4359
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4360
}
4361

4362
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4363
// calls the channelNotifier's NotifyFundingTimeout.
4364
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4365
        remotePub *btcec.PublicKey) {
3✔
4366

3✔
4367
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4368
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4369
        if err != nil {
3✔
4370
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4371
                        "channel[%v] pending close",
×
4372
                        remotePub.SerializeCompressed(), op)
×
4373
        }
×
4374

4375
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4376
                // If we encounter an error while attempting to disconnect the
×
4377
                // peer, log the error.
×
4378
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4379
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4380
                }
×
4381
        }
4382

4383
        // Notify subscribers about this event.
4384
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4385
}
4386

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

3✔
4394
        brontideConn := conn.(*brontide.Conn)
3✔
4395
        addr := conn.RemoteAddr()
3✔
4396
        pubKey := brontideConn.RemotePub()
3✔
4397

3✔
4398
        // Only restrict access for inbound connections, which means if the
3✔
4399
        // remote node's public key is banned or the restricted slots are used
3✔
4400
        // up, we will drop the connection.
3✔
4401
        //
3✔
4402
        // TODO(yy): Consider perform this check in
3✔
4403
        // `peerAccessMan.addPeerAccess`.
3✔
4404
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4405
        if inbound && err != nil {
3✔
4406
                pubSer := pubKey.SerializeCompressed()
×
4407

×
4408
                // Clean up the persistent peer maps if we're dropping this
×
4409
                // connection.
×
4410
                s.bannedPersistentPeerConnection(string(pubSer))
×
4411

×
4412
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4413
                        "of restricted-access connection slots: %v.", pubSer,
×
4414
                        err)
×
4415

×
4416
                conn.Close()
×
4417

×
4418
                return
×
4419
        }
×
4420

4421
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4422
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4423

3✔
4424
        peerAddr := &lnwire.NetAddress{
3✔
4425
                IdentityKey: pubKey,
3✔
4426
                Address:     addr,
3✔
4427
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4428
        }
3✔
4429

3✔
4430
        // With the brontide connection established, we'll now craft the feature
3✔
4431
        // vectors to advertise to the remote node.
3✔
4432
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4433
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4434

3✔
4435
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4436
        // found, create a fresh buffer.
3✔
4437
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4438
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4439
        if !ok {
6✔
4440
                var err error
3✔
4441
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4442
                if err != nil {
3✔
4443
                        srvrLog.Errorf("unable to create peer %v", err)
×
4444
                        return
×
4445
                }
×
4446
        }
4447

4448
        // If we directly set the peer.Config TowerClient member to the
4449
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4450
        // the peer.Config's TowerClient member will not evaluate to nil even
4451
        // though the underlying value is nil. To avoid this gotcha which can
4452
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4453
        // TowerClient if needed.
4454
        var towerClient wtclient.ClientManager
3✔
4455
        if s.towerClientMgr != nil {
6✔
4456
                towerClient = s.towerClientMgr
3✔
4457
        }
3✔
4458

4459
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4460
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4461

3✔
4462
        // Now that we've established a connection, create a peer, and it to the
3✔
4463
        // set of currently active peers. Configure the peer with the incoming
3✔
4464
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4465
        // offered that would trigger channel closure. In case of outgoing
3✔
4466
        // htlcs, an extra block is added to prevent the channel from being
3✔
4467
        // closed when the htlc is outstanding and a new block comes in.
3✔
4468
        pCfg := peer.Config{
3✔
4469
                Conn:                    brontideConn,
3✔
4470
                ConnReq:                 connReq,
3✔
4471
                Addr:                    peerAddr,
3✔
4472
                Inbound:                 inbound,
3✔
4473
                Features:                initFeatures,
3✔
4474
                LegacyFeatures:          legacyFeatures,
3✔
4475
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4476
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4477
                ErrorBuffer:             errBuffer,
3✔
4478
                WritePool:               s.writePool,
3✔
4479
                ReadPool:                s.readPool,
3✔
4480
                Switch:                  s.htlcSwitch,
3✔
4481
                InterceptSwitch:         s.interceptableSwitch,
3✔
4482
                ChannelDB:               s.chanStateDB,
3✔
4483
                ChannelGraph:            s.graphDB,
3✔
4484
                ChainArb:                s.chainArb,
3✔
4485
                AuthGossiper:            s.authGossiper,
3✔
4486
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4487
                ChainIO:                 s.cc.ChainIO,
3✔
4488
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4489
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4490
                SigPool:                 s.sigPool,
3✔
4491
                Wallet:                  s.cc.Wallet,
3✔
4492
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4493
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4494
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4495
                Sphinx:                  s.sphinx,
3✔
4496
                WitnessBeacon:           s.witnessBeacon,
3✔
4497
                Invoices:                s.invoices,
3✔
4498
                ChannelNotifier:         s.channelNotifier,
3✔
4499
                HtlcNotifier:            s.htlcNotifier,
3✔
4500
                TowerClient:             towerClient,
3✔
4501
                DisconnectPeer:          s.DisconnectPeer,
3✔
4502
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4503
                        lnwire.NodeAnnouncement, error) {
6✔
4504

3✔
4505
                        return s.genNodeAnnouncement(nil)
3✔
4506
                },
3✔
4507

4508
                PongBuf: s.pongBuf,
4509

4510
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4511

4512
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4513

4514
                FundingManager: s.fundingMgr,
4515

4516
                Hodl:                    s.cfg.Hodl,
4517
                UnsafeReplay:            s.cfg.UnsafeReplay,
4518
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4519
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4520
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4521
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4522
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4523
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4524
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4525
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4526
                HandleCustomMessage:    s.handleCustomMessage,
4527
                GetAliases:             s.aliasMgr.GetAliases,
4528
                RequestAlias:           s.aliasMgr.RequestAlias,
4529
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4530
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4531
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4532
                MaxFeeExposure:         thresholdMSats,
4533
                Quit:                   s.quit,
4534
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4535
                AuxSigner:              s.implCfg.AuxSigner,
4536
                MsgRouter:              s.implCfg.MsgRouter,
4537
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4538
                AuxResolver:            s.implCfg.AuxContractResolver,
4539
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4540
                ShouldFwdExpEndorsement: func() bool {
3✔
4541
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4542
                                return false
3✔
4543
                        }
3✔
4544

4545
                        return clock.NewDefaultClock().Now().Before(
3✔
4546
                                EndorsementExperimentEnd,
3✔
4547
                        )
3✔
4548
                },
4549
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4550
        }
4551

4552
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4553
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4554

3✔
4555
        p := peer.NewBrontide(pCfg)
3✔
4556

3✔
4557
        // Update the access manager with the access permission for this peer.
3✔
4558
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4559

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

3✔
4563
        s.addPeer(p)
3✔
4564

3✔
4565
        // Once we have successfully added the peer to the server, we can
3✔
4566
        // delete the previous error buffer from the server's map of error
3✔
4567
        // buffers.
3✔
4568
        delete(s.peerErrors, pkStr)
3✔
4569

3✔
4570
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4571
        // includes sending and receiving Init messages, which would be a DOS
3✔
4572
        // vector if we held the server's mutex throughout the procedure.
3✔
4573
        s.wg.Add(1)
3✔
4574
        go s.peerInitializer(p)
3✔
4575
}
4576

4577
// addPeer adds the passed peer to the server's global state of all active
4578
// peers.
4579
func (s *server) addPeer(p *peer.Brontide) {
3✔
4580
        if p == nil {
3✔
4581
                return
×
4582
        }
×
4583

4584
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4585

3✔
4586
        // Ignore new peers if we're shutting down.
3✔
4587
        if s.Stopped() {
3✔
4588
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4589
                        pubBytes)
×
4590
                p.Disconnect(ErrServerShuttingDown)
×
4591

×
4592
                return
×
4593
        }
×
4594

4595
        // Track the new peer in our indexes so we can quickly look it up either
4596
        // according to its public key, or its peer ID.
4597
        // TODO(roasbeef): pipe all requests through to the
4598
        // queryHandler/peerManager
4599

4600
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4601
        // be human-readable.
4602
        pubStr := string(pubBytes)
3✔
4603

3✔
4604
        s.peersByPub[pubStr] = p
3✔
4605

3✔
4606
        if p.Inbound() {
6✔
4607
                s.inboundPeers[pubStr] = p
3✔
4608
        } else {
6✔
4609
                s.outboundPeers[pubStr] = p
3✔
4610
        }
3✔
4611

4612
        // Inform the peer notifier of a peer online event so that it can be reported
4613
        // to clients listening for peer events.
4614
        var pubKey [33]byte
3✔
4615
        copy(pubKey[:], pubBytes)
3✔
4616

3✔
4617
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4618
}
4619

4620
// peerInitializer asynchronously starts a newly connected peer after it has
4621
// been added to the server's peer map. This method sets up a
4622
// peerTerminationWatcher for the given peer, and ensures that it executes even
4623
// if the peer failed to start. In the event of a successful connection, this
4624
// method reads the negotiated, local feature-bits and spawns the appropriate
4625
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4626
// be signaled of the new peer once the method returns.
4627
//
4628
// NOTE: This MUST be launched as a goroutine.
4629
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4630
        defer s.wg.Done()
3✔
4631

3✔
4632
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4633

3✔
4634
        // Avoid initializing peers while the server is exiting.
3✔
4635
        if s.Stopped() {
3✔
4636
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4637
                        pubBytes)
×
4638
                return
×
4639
        }
×
4640

4641
        // Create a channel that will be used to signal a successful start of
4642
        // the link. This prevents the peer termination watcher from beginning
4643
        // its duty too early.
4644
        ready := make(chan struct{})
3✔
4645

3✔
4646
        // Before starting the peer, launch a goroutine to watch for the
3✔
4647
        // unexpected termination of this peer, which will ensure all resources
3✔
4648
        // are properly cleaned up, and re-establish persistent connections when
3✔
4649
        // necessary. The peer termination watcher will be short circuited if
3✔
4650
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4651
        // that the server has already handled the removal of this peer.
3✔
4652
        s.wg.Add(1)
3✔
4653
        go s.peerTerminationWatcher(p, ready)
3✔
4654

3✔
4655
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4656
        // will unblock the peerTerminationWatcher.
3✔
4657
        if err := p.Start(); err != nil {
6✔
4658
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4659

3✔
4660
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4661
                return
3✔
4662
        }
3✔
4663

4664
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4665
        // was successful, and to begin watching the peer's wait group.
4666
        close(ready)
3✔
4667

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

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

3✔
4674
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4675
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4676
        pubStr := string(pubBytes)
3✔
4677
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4678
                select {
3✔
4679
                case peerChan <- p:
3✔
4680
                case <-s.quit:
×
4681
                        return
×
4682
                }
4683
        }
4684
        delete(s.peerConnectedListeners, pubStr)
3✔
4685
}
4686

4687
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4688
// and then cleans up all resources allocated to the peer, notifies relevant
4689
// sub-systems of its demise, and finally handles re-connecting to the peer if
4690
// it's persistent. If the server intentionally disconnects a peer, it should
4691
// have a corresponding entry in the ignorePeerTermination map which will cause
4692
// the cleanup routine to exit early. The passed `ready` chan is used to
4693
// synchronize when WaitForDisconnect should begin watching on the peer's
4694
// waitgroup. The ready chan should only be signaled if the peer starts
4695
// successfully, otherwise the peer should be disconnected instead.
4696
//
4697
// NOTE: This MUST be launched as a goroutine.
4698
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4699
        defer s.wg.Done()
3✔
4700

3✔
4701
        ctx := btclog.WithCtx(
3✔
4702
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4703
        )
3✔
4704

3✔
4705
        p.WaitForDisconnect(ready)
3✔
4706

3✔
4707
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4708

3✔
4709
        // If the server is exiting then we can bail out early ourselves as all
3✔
4710
        // the other sub-systems will already be shutting down.
3✔
4711
        if s.Stopped() {
6✔
4712
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4713
                return
3✔
4714
        }
3✔
4715

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

3✔
4722
        pubKey := p.IdentityKey()
3✔
4723

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

3✔
4728
        // Tell the switch to remove all links associated with this peer.
3✔
4729
        // Passing nil as the target link indicates that all links associated
3✔
4730
        // with this interface should be closed.
3✔
4731
        //
3✔
4732
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4733
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4734
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4735
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4736
        }
×
4737

4738
        for _, link := range links {
6✔
4739
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4740
        }
3✔
4741

4742
        s.mu.Lock()
3✔
4743
        defer s.mu.Unlock()
3✔
4744

3✔
4745
        // If there were any notification requests for when this peer
3✔
4746
        // disconnected, we can trigger them now.
3✔
4747
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4748
        pubStr := string(pubKey.SerializeCompressed())
3✔
4749
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4750
                close(offlineChan)
3✔
4751
        }
3✔
4752
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4753

3✔
4754
        // If the server has already removed this peer, we can short circuit the
3✔
4755
        // peer termination watcher and skip cleanup.
3✔
4756
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4757
                delete(s.ignorePeerTermination, p)
3✔
4758

3✔
4759
                pubKey := p.PubKey()
3✔
4760
                pubStr := string(pubKey[:])
3✔
4761

3✔
4762
                // If a connection callback is present, we'll go ahead and
3✔
4763
                // execute it now that previous peer has fully disconnected. If
3✔
4764
                // the callback is not present, this likely implies the peer was
3✔
4765
                // purposefully disconnected via RPC, and that no reconnect
3✔
4766
                // should be attempted.
3✔
4767
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4768
                if ok {
6✔
4769
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4770
                        connCallback()
3✔
4771
                }
3✔
4772
                return
3✔
4773
        }
4774

4775
        // First, cleanup any remaining state the server has regarding the peer
4776
        // in question.
4777
        s.removePeerUnsafe(ctx, p)
3✔
4778

3✔
4779
        // Next, check to see if this is a persistent peer or not.
3✔
4780
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4781
                return
3✔
4782
        }
3✔
4783

4784
        // Get the last address that we used to connect to the peer.
4785
        addrs := []net.Addr{
3✔
4786
                p.NetAddress().Address,
3✔
4787
        }
3✔
4788

3✔
4789
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4790
        // reconnection purposes.
3✔
4791
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4792
        switch {
3✔
4793
        // We found advertised addresses, so use them.
4794
        case err == nil:
3✔
4795
                addrs = advertisedAddrs
3✔
4796

4797
        // The peer doesn't have an advertised address.
4798
        case err == errNoAdvertisedAddr:
3✔
4799
                // If it is an outbound peer then we fall back to the existing
3✔
4800
                // peer address.
3✔
4801
                if !p.Inbound() {
6✔
4802
                        break
3✔
4803
                }
4804

4805
                // Fall back to the existing peer address if
4806
                // we're not accepting connections over Tor.
4807
                if s.torController == nil {
6✔
4808
                        break
3✔
4809
                }
4810

4811
                // If we are, the peer's address won't be known
4812
                // to us (we'll see a private address, which is
4813
                // the address used by our onion service to dial
4814
                // to lnd), so we don't have enough information
4815
                // to attempt a reconnect.
4816
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4817
                        "to inbound peer without advertised address")
×
4818
                return
×
4819

4820
        // We came across an error retrieving an advertised
4821
        // address, log it, and fall back to the existing peer
4822
        // address.
4823
        default:
3✔
4824
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4825
                        "address for peer", err)
3✔
4826
        }
4827

4828
        // Make an easy lookup map so that we can check if an address
4829
        // is already in the address list that we have stored for this peer.
4830
        existingAddrs := make(map[string]bool)
3✔
4831
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4832
                existingAddrs[addr.String()] = true
3✔
4833
        }
3✔
4834

4835
        // Add any missing addresses for this peer to persistentPeerAddr.
4836
        for _, addr := range addrs {
6✔
4837
                if existingAddrs[addr.String()] {
3✔
4838
                        continue
×
4839
                }
4840

4841
                s.persistentPeerAddrs[pubStr] = append(
3✔
4842
                        s.persistentPeerAddrs[pubStr],
3✔
4843
                        &lnwire.NetAddress{
3✔
4844
                                IdentityKey: p.IdentityKey(),
3✔
4845
                                Address:     addr,
3✔
4846
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4847
                        },
3✔
4848
                )
3✔
4849
        }
4850

4851
        // Record the computed backoff in the backoff map.
4852
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4853
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4854

3✔
4855
        // Initialize a retry canceller for this peer if one does not
3✔
4856
        // exist.
3✔
4857
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4858
        if !ok {
6✔
4859
                cancelChan = make(chan struct{})
3✔
4860
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4861
        }
3✔
4862

4863
        // We choose not to wait group this go routine since the Connect
4864
        // call can stall for arbitrarily long if we shutdown while an
4865
        // outbound connection attempt is being made.
4866
        go func() {
6✔
4867
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4868
                        "re-establishment to persistent peer",
3✔
4869
                        "reconnecting_in", backoff)
3✔
4870

3✔
4871
                select {
3✔
4872
                case <-time.After(backoff):
3✔
4873
                case <-cancelChan:
3✔
4874
                        return
3✔
4875
                case <-s.quit:
3✔
4876
                        return
3✔
4877
                }
4878

4879
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4880
                        "connection")
3✔
4881

3✔
4882
                s.connectToPersistentPeer(pubStr)
3✔
4883
        }()
4884
}
4885

4886
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4887
// to connect to the peer. It creates connection requests if there are
4888
// currently none for a given address and it removes old connection requests
4889
// if the associated address is no longer in the latest address list for the
4890
// peer.
4891
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4892
        s.mu.Lock()
3✔
4893
        defer s.mu.Unlock()
3✔
4894

3✔
4895
        // Create an easy lookup map of the addresses we have stored for the
3✔
4896
        // peer. We will remove entries from this map if we have existing
3✔
4897
        // connection requests for the associated address and then any leftover
3✔
4898
        // entries will indicate which addresses we should create new
3✔
4899
        // connection requests for.
3✔
4900
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4901
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4902
                addrMap[addr.String()] = addr
3✔
4903
        }
3✔
4904

4905
        // Go through each of the existing connection requests and
4906
        // check if they correspond to the latest set of addresses. If
4907
        // there is a connection requests that does not use one of the latest
4908
        // advertised addresses then remove that connection request.
4909
        var updatedConnReqs []*connmgr.ConnReq
3✔
4910
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4911
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4912

3✔
4913
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4914
                // If the existing connection request is using one of the
4915
                // latest advertised addresses for the peer then we add it to
4916
                // updatedConnReqs and remove the associated address from
4917
                // addrMap so that we don't recreate this connReq later on.
4918
                case true:
×
4919
                        updatedConnReqs = append(
×
4920
                                updatedConnReqs, connReq,
×
4921
                        )
×
4922
                        delete(addrMap, lnAddr)
×
4923

4924
                // If the existing connection request is using an address that
4925
                // is not one of the latest advertised addresses for the peer
4926
                // then we remove the connecting request from the connection
4927
                // manager.
4928
                case false:
3✔
4929
                        srvrLog.Info(
3✔
4930
                                "Removing conn req:", connReq.Addr.String(),
3✔
4931
                        )
3✔
4932
                        s.connMgr.Remove(connReq.ID())
3✔
4933
                }
4934
        }
4935

4936
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4937

3✔
4938
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4939
        if !ok {
6✔
4940
                cancelChan = make(chan struct{})
3✔
4941
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4942
        }
3✔
4943

4944
        // Any addresses left in addrMap are new ones that we have not made
4945
        // connection requests for. So create new connection requests for those.
4946
        // If there is more than one address in the address map, stagger the
4947
        // creation of the connection requests for those.
4948
        go func() {
6✔
4949
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4950
                defer ticker.Stop()
3✔
4951

3✔
4952
                for _, addr := range addrMap {
6✔
4953
                        // Send the persistent connection request to the
3✔
4954
                        // connection manager, saving the request itself so we
3✔
4955
                        // can cancel/restart the process as needed.
3✔
4956
                        connReq := &connmgr.ConnReq{
3✔
4957
                                Addr:      addr,
3✔
4958
                                Permanent: true,
3✔
4959
                        }
3✔
4960

3✔
4961
                        s.mu.Lock()
3✔
4962
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4963
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4964
                        )
3✔
4965
                        s.mu.Unlock()
3✔
4966

3✔
4967
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4968
                                "channel peer %v", addr)
3✔
4969

3✔
4970
                        go s.connMgr.Connect(connReq)
3✔
4971

3✔
4972
                        select {
3✔
4973
                        case <-s.quit:
3✔
4974
                                return
3✔
4975
                        case <-cancelChan:
3✔
4976
                                return
3✔
4977
                        case <-ticker.C:
3✔
4978
                        }
4979
                }
4980
        }()
4981
}
4982

4983
// removePeerUnsafe removes the passed peer from the server's state of all
4984
// active peers.
4985
//
4986
// NOTE: Server mutex must be held when calling this function.
4987
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4988
        if p == nil {
3✔
4989
                return
×
4990
        }
×
4991

4992
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4993

3✔
4994
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4995
        // will be disconnected in the server shutdown process.
3✔
4996
        if s.Stopped() {
3✔
4997
                return
×
4998
        }
×
4999

5000
        // Capture the peer's public key and string representation.
5001
        pKey := p.PubKey()
3✔
5002
        pubSer := pKey[:]
3✔
5003
        pubStr := string(pubSer)
3✔
5004

3✔
5005
        delete(s.peersByPub, pubStr)
3✔
5006

3✔
5007
        if p.Inbound() {
6✔
5008
                delete(s.inboundPeers, pubStr)
3✔
5009
        } else {
6✔
5010
                delete(s.outboundPeers, pubStr)
3✔
5011
        }
3✔
5012

5013
        // When removing the peer we make sure to disconnect it asynchronously
5014
        // to avoid blocking the main server goroutine because it is holding the
5015
        // server's mutex. Disconnecting the peer might block and wait until the
5016
        // peer has fully started up. This can happen if an inbound and outbound
5017
        // race condition occurs.
5018
        s.wg.Add(1)
3✔
5019
        go func() {
6✔
5020
                defer s.wg.Done()
3✔
5021

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

3✔
5024
                // If this peer had an active persistent connection request,
3✔
5025
                // remove it.
3✔
5026
                if p.ConnReq() != nil {
6✔
5027
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5028
                }
3✔
5029

5030
                // Remove the peer's access permission from the access manager.
5031
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5032
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5033

3✔
5034
                // Copy the peer's error buffer across to the server if it has
3✔
5035
                // any items in it so that we can restore peer errors across
3✔
5036
                // connections. We need to look up the error after the peer has
3✔
5037
                // been disconnected because we write the error in the
3✔
5038
                // `Disconnect` method.
3✔
5039
                s.mu.Lock()
3✔
5040
                if p.ErrorBuffer().Total() > 0 {
6✔
5041
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5042
                }
3✔
5043
                s.mu.Unlock()
3✔
5044

3✔
5045
                // Inform the peer notifier of a peer offline event so that it
3✔
5046
                // can be reported to clients listening for peer events.
3✔
5047
                var pubKey [33]byte
3✔
5048
                copy(pubKey[:], pubSer)
3✔
5049

3✔
5050
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5051
        }()
5052
}
5053

5054
// ConnectToPeer requests that the server connect to a Lightning Network peer
5055
// at the specified address. This function will *block* until either a
5056
// connection is established, or the initial handshake process fails.
5057
//
5058
// NOTE: This function is safe for concurrent access.
5059
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5060
        perm bool, timeout time.Duration) error {
3✔
5061

3✔
5062
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5063

3✔
5064
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5065
        // better granularity.  In certain conditions, this method requires
3✔
5066
        // making an outbound connection to a remote peer, which requires the
3✔
5067
        // lock to be released, and subsequently reacquired.
3✔
5068
        s.mu.Lock()
3✔
5069

3✔
5070
        // Ensure we're not already connected to this peer.
3✔
5071
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5072

3✔
5073
        // When there's no error it means we already have a connection with this
3✔
5074
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5075
        // set, we will ignore the existing connection and continue.
3✔
5076
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5077
                s.mu.Unlock()
3✔
5078
                return &errPeerAlreadyConnected{peer: peer}
3✔
5079
        }
3✔
5080

5081
        // Peer was not found, continue to pursue connection with peer.
5082

5083
        // If there's already a pending connection request for this pubkey,
5084
        // then we ignore this request to ensure we don't create a redundant
5085
        // connection.
5086
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5087
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5088
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5089
        }
3✔
5090

5091
        // If there's not already a pending or active connection to this node,
5092
        // then instruct the connection manager to attempt to establish a
5093
        // persistent connection to the peer.
5094
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5095
        if perm {
6✔
5096
                connReq := &connmgr.ConnReq{
3✔
5097
                        Addr:      addr,
3✔
5098
                        Permanent: true,
3✔
5099
                }
3✔
5100

3✔
5101
                // Since the user requested a permanent connection, we'll set
3✔
5102
                // the entry to true which will tell the server to continue
3✔
5103
                // reconnecting even if the number of channels with this peer is
3✔
5104
                // zero.
3✔
5105
                s.persistentPeers[targetPub] = true
3✔
5106
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5107
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5108
                }
3✔
5109
                s.persistentConnReqs[targetPub] = append(
3✔
5110
                        s.persistentConnReqs[targetPub], connReq,
3✔
5111
                )
3✔
5112
                s.mu.Unlock()
3✔
5113

3✔
5114
                go s.connMgr.Connect(connReq)
3✔
5115

3✔
5116
                return nil
3✔
5117
        }
5118
        s.mu.Unlock()
3✔
5119

3✔
5120
        // If we're not making a persistent connection, then we'll attempt to
3✔
5121
        // connect to the target peer. If the we can't make the connection, or
3✔
5122
        // the crypto negotiation breaks down, then return an error to the
3✔
5123
        // caller.
3✔
5124
        errChan := make(chan error, 1)
3✔
5125
        s.connectToPeer(addr, errChan, timeout)
3✔
5126

3✔
5127
        select {
3✔
5128
        case err := <-errChan:
3✔
5129
                return err
3✔
5130
        case <-s.quit:
×
5131
                return ErrServerShuttingDown
×
5132
        }
5133
}
5134

5135
// connectToPeer establishes a connection to a remote peer. errChan is used to
5136
// notify the caller if the connection attempt has failed. Otherwise, it will be
5137
// closed.
5138
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5139
        errChan chan<- error, timeout time.Duration) {
3✔
5140

3✔
5141
        conn, err := brontide.Dial(
3✔
5142
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5143
        )
3✔
5144
        if err != nil {
6✔
5145
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5146
                select {
3✔
5147
                case errChan <- err:
3✔
5148
                case <-s.quit:
×
5149
                }
5150
                return
3✔
5151
        }
5152

5153
        close(errChan)
3✔
5154

3✔
5155
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5156
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5157

3✔
5158
        s.OutboundPeerConnected(nil, conn)
3✔
5159
}
5160

5161
// DisconnectPeer sends the request to server to close the connection with peer
5162
// identified by public key.
5163
//
5164
// NOTE: This function is safe for concurrent access.
5165
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5166
        pubBytes := pubKey.SerializeCompressed()
3✔
5167
        pubStr := string(pubBytes)
3✔
5168

3✔
5169
        s.mu.Lock()
3✔
5170
        defer s.mu.Unlock()
3✔
5171

3✔
5172
        // Check that were actually connected to this peer. If not, then we'll
3✔
5173
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5174
        // currently connected to.
3✔
5175
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5176
        if err == ErrPeerNotConnected {
6✔
5177
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5178
        }
3✔
5179

5180
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5181

3✔
5182
        s.cancelConnReqs(pubStr, nil)
3✔
5183

3✔
5184
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5185
        // them from this map so we don't attempt to re-connect after we
3✔
5186
        // disconnect.
3✔
5187
        delete(s.persistentPeers, pubStr)
3✔
5188
        delete(s.persistentPeersBackoff, pubStr)
3✔
5189

3✔
5190
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5191
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5192
        //
3✔
5193
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5194
        // goroutine because we might hold the server's mutex.
3✔
5195
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5196

3✔
5197
        return nil
3✔
5198
}
5199

5200
// OpenChannel sends a request to the server to open a channel to the specified
5201
// peer identified by nodeKey with the passed channel funding parameters.
5202
//
5203
// NOTE: This function is safe for concurrent access.
5204
func (s *server) OpenChannel(
5205
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5206

3✔
5207
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5208
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5209
        // not blocked if the caller is not reading the updates.
3✔
5210
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5211
        req.Err = make(chan error, 1)
3✔
5212

3✔
5213
        // First attempt to locate the target peer to open a channel with, if
3✔
5214
        // we're unable to locate the peer then this request will fail.
3✔
5215
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5216
        s.mu.RLock()
3✔
5217
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5218
        if !ok {
3✔
5219
                s.mu.RUnlock()
×
5220

×
5221
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5222
                return req.Updates, req.Err
×
5223
        }
×
5224
        req.Peer = peer
3✔
5225
        s.mu.RUnlock()
3✔
5226

3✔
5227
        // We'll wait until the peer is active before beginning the channel
3✔
5228
        // opening process.
3✔
5229
        select {
3✔
5230
        case <-peer.ActiveSignal():
3✔
5231
        case <-peer.QuitSignal():
×
5232
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5233
                return req.Updates, req.Err
×
5234
        case <-s.quit:
×
5235
                req.Err <- ErrServerShuttingDown
×
5236
                return req.Updates, req.Err
×
5237
        }
5238

5239
        // If the fee rate wasn't specified at this point we fail the funding
5240
        // because of the missing fee rate information. The caller of the
5241
        // `OpenChannel` method needs to make sure that default values for the
5242
        // fee rate are set beforehand.
5243
        if req.FundingFeePerKw == 0 {
3✔
5244
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5245
                        "the channel opening transaction")
×
5246

×
5247
                return req.Updates, req.Err
×
5248
        }
×
5249

5250
        // Spawn a goroutine to send the funding workflow request to the funding
5251
        // manager. This allows the server to continue handling queries instead
5252
        // of blocking on this request which is exported as a synchronous
5253
        // request to the outside world.
5254
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5255

3✔
5256
        return req.Updates, req.Err
3✔
5257
}
5258

5259
// Peers returns a slice of all active peers.
5260
//
5261
// NOTE: This function is safe for concurrent access.
5262
func (s *server) Peers() []*peer.Brontide {
3✔
5263
        s.mu.RLock()
3✔
5264
        defer s.mu.RUnlock()
3✔
5265

3✔
5266
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5267
        for _, peer := range s.peersByPub {
6✔
5268
                peers = append(peers, peer)
3✔
5269
        }
3✔
5270

5271
        return peers
3✔
5272
}
5273

5274
// computeNextBackoff uses a truncated exponential backoff to compute the next
5275
// backoff using the value of the exiting backoff. The returned duration is
5276
// randomized in either direction by 1/20 to prevent tight loops from
5277
// stabilizing.
5278
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5279
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5280
        nextBackoff := 2 * currBackoff
3✔
5281
        if nextBackoff > maxBackoff {
6✔
5282
                nextBackoff = maxBackoff
3✔
5283
        }
3✔
5284

5285
        // Using 1/10 of our duration as a margin, compute a random offset to
5286
        // avoid the nodes entering connection cycles.
5287
        margin := nextBackoff / 10
3✔
5288

3✔
5289
        var wiggle big.Int
3✔
5290
        wiggle.SetUint64(uint64(margin))
3✔
5291
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5292
                // Randomizing is not mission critical, so we'll just return the
×
5293
                // current backoff.
×
5294
                return nextBackoff
×
5295
        }
×
5296

5297
        // Otherwise add in our wiggle, but subtract out half of the margin so
5298
        // that the backoff can tweaked by 1/20 in either direction.
5299
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5300
}
5301

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

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

3✔
5310
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5311
        if err != nil {
3✔
5312
                return nil, err
×
5313
        }
×
5314

5315
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5316
        if err != nil {
6✔
5317
                return nil, err
3✔
5318
        }
3✔
5319

5320
        if len(node.Addresses) == 0 {
6✔
5321
                return nil, errNoAdvertisedAddr
3✔
5322
        }
3✔
5323

5324
        return node.Addresses, nil
3✔
5325
}
5326

5327
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5328
// channel update for a target channel.
5329
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5330
        *lnwire.ChannelUpdate1, error) {
3✔
5331

3✔
5332
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5333
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5334
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5335
                if err != nil {
6✔
5336
                        return nil, err
3✔
5337
                }
3✔
5338

5339
                return netann.ExtractChannelUpdate(
3✔
5340
                        ourPubKey[:], info, edge1, edge2,
3✔
5341
                )
3✔
5342
        }
5343
}
5344

5345
// applyChannelUpdate applies the channel update to the different sub-systems of
5346
// the server. The useAlias boolean denotes whether or not to send an alias in
5347
// place of the real SCID.
5348
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5349
        op *wire.OutPoint, useAlias bool) error {
3✔
5350

3✔
5351
        var (
3✔
5352
                peerAlias    *lnwire.ShortChannelID
3✔
5353
                defaultAlias lnwire.ShortChannelID
3✔
5354
        )
3✔
5355

3✔
5356
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5357

3✔
5358
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5359
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5360
        if useAlias {
6✔
5361
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5362
                if foundAlias != defaultAlias {
6✔
5363
                        peerAlias = &foundAlias
3✔
5364
                }
3✔
5365
        }
5366

5367
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5368
                update, discovery.RemoteAlias(peerAlias),
3✔
5369
        )
3✔
5370
        select {
3✔
5371
        case err := <-errChan:
3✔
5372
                return err
3✔
5373
        case <-s.quit:
×
5374
                return ErrServerShuttingDown
×
5375
        }
5376
}
5377

5378
// SendCustomMessage sends a custom message to the peer with the specified
5379
// pubkey.
5380
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5381
        data []byte) error {
3✔
5382

3✔
5383
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5384
        if err != nil {
3✔
5385
                return err
×
5386
        }
×
5387

5388
        // We'll wait until the peer is active.
5389
        select {
3✔
5390
        case <-peer.ActiveSignal():
3✔
5391
        case <-peer.QuitSignal():
×
5392
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5393
        case <-s.quit:
×
5394
                return ErrServerShuttingDown
×
5395
        }
5396

5397
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5398
        if err != nil {
6✔
5399
                return err
3✔
5400
        }
3✔
5401

5402
        // Send the message as low-priority. For now we assume that all
5403
        // application-defined message are low priority.
5404
        return peer.SendMessageLazy(true, msg)
3✔
5405
}
5406

5407
// newSweepPkScriptGen creates closure that generates a new public key script
5408
// which should be used to sweep any funds into the on-chain wallet.
5409
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5410
// (p2wkh) output.
5411
func newSweepPkScriptGen(
5412
        wallet lnwallet.WalletController,
5413
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5414

3✔
5415
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5416
                sweepAddr, err := wallet.NewAddress(
3✔
5417
                        lnwallet.TaprootPubkey, false,
3✔
5418
                        lnwallet.DefaultAccountName,
3✔
5419
                )
3✔
5420
                if err != nil {
3✔
5421
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5422
                }
×
5423

5424
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5425
                if err != nil {
3✔
5426
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5427
                }
×
5428

5429
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5430
                        wallet, netParams, addr,
3✔
5431
                )
3✔
5432
                if err != nil {
3✔
5433
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5434
                }
×
5435

5436
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5437
                        DeliveryAddress: addr,
3✔
5438
                        InternalKey:     internalKeyDesc,
3✔
5439
                })
3✔
5440
        }
5441
}
5442

5443
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5444
// finished.
5445
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5446
        // Get a list of closed channels.
3✔
5447
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5448
        if err != nil {
3✔
5449
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5450
                return nil
×
5451
        }
×
5452

5453
        // Save the SCIDs in a map.
5454
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5455
        for _, c := range channels {
6✔
5456
                // If the channel is not pending, its FC has been finalized.
3✔
5457
                if !c.IsPending {
6✔
5458
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5459
                }
3✔
5460
        }
5461

5462
        // Double check whether the reported closed channel has indeed finished
5463
        // closing.
5464
        //
5465
        // NOTE: There are misalignments regarding when a channel's FC is
5466
        // marked as finalized. We double check the pending channels to make
5467
        // sure the returned SCIDs are indeed terminated.
5468
        //
5469
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5470
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5471
        if err != nil {
3✔
5472
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5473
                return nil
×
5474
        }
×
5475

5476
        for _, c := range pendings {
6✔
5477
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5478
                        continue
3✔
5479
                }
5480

5481
                // If the channel is still reported as pending, remove it from
5482
                // the map.
5483
                delete(closedSCIDs, c.ShortChannelID)
×
5484

×
5485
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5486
                        c.ShortChannelID)
×
5487
        }
5488

5489
        return closedSCIDs
3✔
5490
}
5491

5492
// getStartingBeat returns the current beat. This is used during the startup to
5493
// initialize blockbeat consumers.
5494
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5495
        // beat is the current blockbeat.
3✔
5496
        var beat *chainio.Beat
3✔
5497

3✔
5498
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5499
        // we will skip fetching the best block.
3✔
5500
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5501
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5502
                        "mode")
×
5503

×
5504
                return &chainio.Beat{}, nil
×
5505
        }
×
5506

5507
        // We should get a notification with the current best block immediately
5508
        // by passing a nil block.
5509
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5510
        if err != nil {
3✔
5511
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5512
        }
×
5513
        defer blockEpochs.Cancel()
3✔
5514

3✔
5515
        // We registered for the block epochs with a nil request. The notifier
3✔
5516
        // should send us the current best block immediately. So we need to
3✔
5517
        // wait for it here because we need to know the current best height.
3✔
5518
        select {
3✔
5519
        case bestBlock := <-blockEpochs.Epochs:
3✔
5520
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5521
                        bestBlock.Hash, bestBlock.Height)
3✔
5522

3✔
5523
                // Update the current blockbeat.
3✔
5524
                beat = chainio.NewBeat(*bestBlock)
3✔
5525

5526
        case <-s.quit:
×
5527
                srvrLog.Debug("LND shutting down")
×
5528
        }
5529

5530
        return beat, nil
3✔
5531
}
5532

5533
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5534
// point has an active RBF chan closer.
5535
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5536
        chanPoint wire.OutPoint) bool {
3✔
5537

3✔
5538
        pubBytes := peerPub.SerializeCompressed()
3✔
5539

3✔
5540
        s.mu.RLock()
3✔
5541
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5542
        s.mu.RUnlock()
3✔
5543
        if !ok {
3✔
5544
                return false
×
5545
        }
×
5546

5547
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5548
}
5549

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

3✔
5558
        // First, we'll attempt to look up the channel based on it's
3✔
5559
        // ChannelPoint.
3✔
5560
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5561
        if err != nil {
3✔
5562
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5563
        }
×
5564

5565
        // From the channel, we can now get the pubkey of the peer, then use
5566
        // that to eventually get the chan closer.
5567
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5568

3✔
5569
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5570
        s.mu.RLock()
3✔
5571
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5572
        s.mu.RUnlock()
3✔
5573
        if !ok {
3✔
5574
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5575
                        "not online", chanPoint)
×
5576
        }
×
5577

5578
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5579
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5580
        )
3✔
5581
        if err != nil {
3✔
5582
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5583
                        "%w", err)
×
5584
        }
×
5585

5586
        return closeUpdates, nil
3✔
5587
}
5588

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

3✔
5597
        // If the channel is present in the switch, then the request should flow
3✔
5598
        // through the switch instead.
3✔
5599
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5600
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5601
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5602
                        "invalid request", chanPoint)
×
5603
        }
×
5604

5605
        // At this point, we know that the channel isn't present in the link, so
5606
        // we'll check to see if we have an entry in the active chan closer map.
5607
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5608
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5609
        )
3✔
5610
        if err != nil {
3✔
5611
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5612
                        "ChannelPoint(%v)", chanPoint)
×
5613
        }
×
5614

5615
        return updates, nil
3✔
5616
}
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