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

lightningnetwork / lnd / 16200890897

10 Jul 2025 04:39PM UTC coverage: 67.437% (+0.02%) from 67.417%
16200890897

Pull #10015

github

web-flow
Merge 46d2623a2 into 04a2be29d
Pull Request #10015: graph/db: add zombie channels cleanup routine

58 of 63 new or added lines in 2 files covered. (92.06%)

86 existing lines in 18 files now uncovered.

135349 of 200705 relevant lines covered (67.44%)

21863.02 hits per line

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

69.48
/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(ctx context.Context,
3✔
1256
                        cb func(*models.ChannelEdgeInfo,
3✔
1257
                                *models.ChannelEdgePolicy) error) error {
6✔
1258

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2053
                chainBackendAttempts = 0
×
2054
        }
×
2055

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2267
        return startErr
3✔
2268
}
2269

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

2282
        var startErr error
3✔
2283

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2872
        return nil
3✔
2873
}
2874

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

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

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

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

2904
        return externalIPs, nil
×
2905
}
2906

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3098
        return bootStrappers, nil
3✔
3099
}
3100

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

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

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

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

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

3131
        return ignore
3✔
3132
}
3133

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

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

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

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

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

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

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

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

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

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

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

×
3195
                                sampleTicker.Stop()
×
3196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3455
        return nil
×
3456
}
3457

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3586
        return nil
3✔
3587
}
3588

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

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

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

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

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

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

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

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

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

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

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

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

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

3691
                nodeAddrsMap[pubStr] = n
3✔
3692
                return nil
3✔
3693
        }
3694
        err = s.graphDB.ForEachSourceNodeChannel(ctx, forEachSrcNodeChan)
3✔
3695
        if err != nil {
3✔
3696
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3697
                        "%v", err)
×
3698

×
3699
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3700
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3701

×
3702
                        return err
×
3703
                }
×
3704
        }
3705

3706
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3707
                len(nodeAddrsMap))
3✔
3708

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

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

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

3✔
3737
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3738
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3739
                }
3✔
3740

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

3✔
3751
                        go s.connectToPersistentPeer(pubStr)
3✔
3752
                } else {
3✔
3753
                        go s.delayInitialReconnect(pubStr)
×
3754
                }
×
3755

3756
                numOutboundConns++
3✔
3757
        }
3758

3759
        return nil
3✔
3760
}
3761

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

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

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

3✔
3789
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3790
                        "peer has no open channels", compressedPubKey)
3✔
3791

3✔
3792
                return
3✔
3793
        }
3✔
3794
        s.mu.Unlock()
3✔
3795
}
3796

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

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

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

3837
                peers = append(peers, sPeer)
3✔
3838
        }
3839
        s.mu.RUnlock()
3✔
3840

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

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

3✔
3855
                        p.SendMessageLazy(false, msgs...)
3✔
3856
                }(sPeer)
3✔
3857
        }
3858

3859
        // Wait for all messages to have been dispatched before returning to
3860
        // caller.
3861
        wg.Wait()
3✔
3862

3✔
3863
        return nil
3✔
3864
}
3865

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

3✔
3873
        s.mu.Lock()
3✔
3874

3✔
3875
        // Compute the target peer's identifier.
3✔
3876
        pubStr := string(peerKey[:])
3✔
3877

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

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

3900
                // Connected, can return early.
3901
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3902

3✔
3903
                select {
3✔
3904
                case peerChan <- peer:
3✔
3905
                case <-s.quit:
×
3906
                }
3907

3908
                return
3✔
3909
        }
3910

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

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

3✔
3926
        c := make(chan struct{})
3✔
3927

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

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

3✔
3944
        return c
3✔
3945
}
3946

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

3✔
3956
        pubStr := string(peerKey.SerializeCompressed())
3✔
3957

3✔
3958
        return s.findPeerByPubStr(pubStr)
3✔
3959
}
3✔
3960

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

3✔
3970
        return s.findPeerByPubStr(pubStr)
3✔
3971
}
3✔
3972

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

3981
        return peer, nil
3✔
3982
}
3983

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

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

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

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

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

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

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

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

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

4056
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4057
        pubSer := nodePub.SerializeCompressed()
3✔
4058
        pubStr := string(pubSer)
3✔
4059

3✔
4060
        var pubBytes [33]byte
3✔
4061
        copy(pubBytes[:], pubSer)
3✔
4062

3✔
4063
        s.mu.Lock()
3✔
4064
        defer s.mu.Unlock()
3✔
4065

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

3✔
4073
                conn.Close()
3✔
4074
                return
3✔
4075
        }
3✔
4076

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

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

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

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

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

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

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

3✔
4129
                s.cancelConnReqs(pubStr, nil)
3✔
4130

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

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

4152
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4153
        pubSer := nodePub.SerializeCompressed()
3✔
4154
        pubStr := string(pubSer)
3✔
4155

3✔
4156
        var pubBytes [33]byte
3✔
4157
        copy(pubBytes[:], pubSer)
3✔
4158

3✔
4159
        s.mu.Lock()
3✔
4160
        defer s.mu.Unlock()
3✔
4161

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

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

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

×
4188
                if connReq != nil {
×
4189
                        s.connMgr.Remove(connReq.ID())
×
4190
                }
×
4191

4192
                conn.Close()
×
4193
                return
×
4194
        }
4195

4196
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4197
                conn.RemoteAddr())
3✔
4198

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

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

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

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

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

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

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

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

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

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

4292
        for _, connReq := range connReqs {
6✔
4293
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4294

3✔
4295
                // Atomically capture the current request identifier.
3✔
4296
                connID := connReq.ID()
3✔
4297

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

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

4309
                s.connMgr.Remove(connID)
3✔
4310
        }
4311

4312
        delete(s.persistentConnReqs, pubStr)
3✔
4313
}
4314

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

3✔
4321
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4322
                Peer: peer,
3✔
4323
                Msg:  msg,
3✔
4324
        })
3✔
4325
}
3✔
4326

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

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

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

4344
        // Notify subscribers about this open channel event.
4345
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4346
}
4347

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

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

4361
        // Notify subscribers about this event.
4362
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4363
}
4364

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

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

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

4386
        // Notify subscribers about this event.
4387
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4388
}
4389

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

3✔
4397
        brontideConn := conn.(*brontide.Conn)
3✔
4398
        addr := conn.RemoteAddr()
3✔
4399
        pubKey := brontideConn.RemotePub()
3✔
4400

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

×
4411
                // Clean up the persistent peer maps if we're dropping this
×
4412
                // connection.
×
4413
                s.bannedPersistentPeerConnection(string(pubSer))
×
4414

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

×
4419
                conn.Close()
×
4420

×
4421
                return
×
4422
        }
×
4423

4424
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4425
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4426

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

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

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

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

4462
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4463
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4464

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

3✔
4508
                        return s.genNodeAnnouncement(nil)
3✔
4509
                },
3✔
4510

4511
                PongBuf: s.pongBuf,
4512

4513
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4514

4515
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4516

4517
                FundingManager: s.fundingMgr,
4518

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

4549
                        return clock.NewDefaultClock().Now().Before(
3✔
4550
                                EndorsementExperimentEnd,
3✔
4551
                        )
3✔
4552
                },
4553
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4554
        }
4555

4556
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4557
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4558

3✔
4559
        p := peer.NewBrontide(pCfg)
3✔
4560

3✔
4561
        // Update the access manager with the access permission for this peer.
3✔
4562
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4563

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

3✔
4567
        s.addPeer(p)
3✔
4568

3✔
4569
        // Once we have successfully added the peer to the server, we can
3✔
4570
        // delete the previous error buffer from the server's map of error
3✔
4571
        // buffers.
3✔
4572
        delete(s.peerErrors, pkStr)
3✔
4573

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

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

4588
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4589

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

×
4596
                return
×
4597
        }
×
4598

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

4604
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4605
        // be human-readable.
4606
        pubStr := string(pubBytes)
3✔
4607

3✔
4608
        s.peersByPub[pubStr] = p
3✔
4609

3✔
4610
        if p.Inbound() {
6✔
4611
                s.inboundPeers[pubStr] = p
3✔
4612
        } else {
6✔
4613
                s.outboundPeers[pubStr] = p
3✔
4614
        }
3✔
4615

4616
        // Inform the peer notifier of a peer online event so that it can be reported
4617
        // to clients listening for peer events.
4618
        var pubKey [33]byte
3✔
4619
        copy(pubKey[:], pubBytes)
3✔
4620
}
4621

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

3✔
4634
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4635

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

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

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

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

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

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

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

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

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

3✔
4688
        // Since the peer has been fully initialized, now it's time to notify
3✔
4689
        // the RPC about the peer online event.
3✔
4690
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4691
}
4692

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

3✔
4707
        ctx := btclog.WithCtx(
3✔
4708
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4709
        )
3✔
4710

3✔
4711
        p.WaitForDisconnect(ready)
3✔
4712

3✔
4713
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4714

3✔
4715
        // If the server is exiting then we can bail out early ourselves as all
3✔
4716
        // the other sub-systems will already be shutting down.
3✔
4717
        if s.Stopped() {
6✔
4718
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4719
                return
3✔
4720
        }
3✔
4721

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

3✔
4728
        pubKey := p.IdentityKey()
3✔
4729

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

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

4744
        for _, link := range links {
6✔
4745
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4746
        }
3✔
4747

4748
        s.mu.Lock()
3✔
4749
        defer s.mu.Unlock()
3✔
4750

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

3✔
4760
        // If the server has already removed this peer, we can short circuit the
3✔
4761
        // peer termination watcher and skip cleanup.
3✔
4762
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4763
                delete(s.ignorePeerTermination, p)
3✔
4764

3✔
4765
                pubKey := p.PubKey()
3✔
4766
                pubStr := string(pubKey[:])
3✔
4767

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

4781
        // First, cleanup any remaining state the server has regarding the peer
4782
        // in question.
4783
        s.removePeerUnsafe(ctx, p)
3✔
4784

3✔
4785
        // Next, check to see if this is a persistent peer or not.
3✔
4786
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4787
                return
3✔
4788
        }
3✔
4789

4790
        // Get the last address that we used to connect to the peer.
4791
        addrs := []net.Addr{
3✔
4792
                p.NetAddress().Address,
3✔
4793
        }
3✔
4794

3✔
4795
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4796
        // reconnection purposes.
3✔
4797
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4798
        switch {
3✔
4799
        // We found advertised addresses, so use them.
4800
        case err == nil:
3✔
4801
                addrs = advertisedAddrs
3✔
4802

4803
        // The peer doesn't have an advertised address.
4804
        case err == errNoAdvertisedAddr:
3✔
4805
                // If it is an outbound peer then we fall back to the existing
3✔
4806
                // peer address.
3✔
4807
                if !p.Inbound() {
6✔
4808
                        break
3✔
4809
                }
4810

4811
                // Fall back to the existing peer address if
4812
                // we're not accepting connections over Tor.
4813
                if s.torController == nil {
6✔
4814
                        break
3✔
4815
                }
4816

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

4826
        // We came across an error retrieving an advertised
4827
        // address, log it, and fall back to the existing peer
4828
        // address.
4829
        default:
3✔
4830
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4831
                        "address for peer", err)
3✔
4832
        }
4833

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

4841
        // Add any missing addresses for this peer to persistentPeerAddr.
4842
        for _, addr := range addrs {
6✔
4843
                if existingAddrs[addr.String()] {
3✔
4844
                        continue
×
4845
                }
4846

4847
                s.persistentPeerAddrs[pubStr] = append(
3✔
4848
                        s.persistentPeerAddrs[pubStr],
3✔
4849
                        &lnwire.NetAddress{
3✔
4850
                                IdentityKey: p.IdentityKey(),
3✔
4851
                                Address:     addr,
3✔
4852
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4853
                        },
3✔
4854
                )
3✔
4855
        }
4856

4857
        // Record the computed backoff in the backoff map.
4858
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4859
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4860

3✔
4861
        // Initialize a retry canceller for this peer if one does not
3✔
4862
        // exist.
3✔
4863
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4864
        if !ok {
6✔
4865
                cancelChan = make(chan struct{})
3✔
4866
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4867
        }
3✔
4868

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

3✔
4877
                select {
3✔
4878
                case <-time.After(backoff):
3✔
4879
                case <-cancelChan:
3✔
4880
                        return
3✔
4881
                case <-s.quit:
3✔
4882
                        return
3✔
4883
                }
4884

4885
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4886
                        "connection")
3✔
4887

3✔
4888
                s.connectToPersistentPeer(pubStr)
3✔
4889
        }()
4890
}
4891

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

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

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

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

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

4942
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4943

3✔
4944
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4945
        if !ok {
6✔
4946
                cancelChan = make(chan struct{})
3✔
4947
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4948
        }
3✔
4949

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

3✔
4958
                for _, addr := range addrMap {
6✔
4959
                        // Send the persistent connection request to the
3✔
4960
                        // connection manager, saving the request itself so we
3✔
4961
                        // can cancel/restart the process as needed.
3✔
4962
                        connReq := &connmgr.ConnReq{
3✔
4963
                                Addr:      addr,
3✔
4964
                                Permanent: true,
3✔
4965
                        }
3✔
4966

3✔
4967
                        s.mu.Lock()
3✔
4968
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4969
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4970
                        )
3✔
4971
                        s.mu.Unlock()
3✔
4972

3✔
4973
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4974
                                "channel peer %v", addr)
3✔
4975

3✔
4976
                        go s.connMgr.Connect(connReq)
3✔
4977

3✔
4978
                        select {
3✔
4979
                        case <-s.quit:
3✔
4980
                                return
3✔
4981
                        case <-cancelChan:
3✔
4982
                                return
3✔
4983
                        case <-ticker.C:
3✔
4984
                        }
4985
                }
4986
        }()
4987
}
4988

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

4998
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4999

3✔
5000
        // Exit early if we have already been instructed to shutdown, the peers
3✔
5001
        // will be disconnected in the server shutdown process.
3✔
5002
        if s.Stopped() {
3✔
5003
                return
×
5004
        }
×
5005

5006
        // Capture the peer's public key and string representation.
5007
        pKey := p.PubKey()
3✔
5008
        pubSer := pKey[:]
3✔
5009
        pubStr := string(pubSer)
3✔
5010

3✔
5011
        delete(s.peersByPub, pubStr)
3✔
5012

3✔
5013
        if p.Inbound() {
6✔
5014
                delete(s.inboundPeers, pubStr)
3✔
5015
        } else {
6✔
5016
                delete(s.outboundPeers, pubStr)
3✔
5017
        }
3✔
5018

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

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

3✔
5030
                // If this peer had an active persistent connection request,
3✔
5031
                // remove it.
3✔
5032
                if p.ConnReq() != nil {
6✔
5033
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5034
                }
3✔
5035

5036
                // Remove the peer's access permission from the access manager.
5037
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5038
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5039

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

3✔
5051
                // Inform the peer notifier of a peer offline event so that it
3✔
5052
                // can be reported to clients listening for peer events.
3✔
5053
                var pubKey [33]byte
3✔
5054
                copy(pubKey[:], pubSer)
3✔
5055

3✔
5056
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5057
        }()
5058
}
5059

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

3✔
5068
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5069

3✔
5070
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5071
        // better granularity.  In certain conditions, this method requires
3✔
5072
        // making an outbound connection to a remote peer, which requires the
3✔
5073
        // lock to be released, and subsequently reacquired.
3✔
5074
        s.mu.Lock()
3✔
5075

3✔
5076
        // Ensure we're not already connected to this peer.
3✔
5077
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5078

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

5087
        // Peer was not found, continue to pursue connection with peer.
5088

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

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

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

3✔
5120
                go s.connMgr.Connect(connReq)
3✔
5121

3✔
5122
                return nil
3✔
5123
        }
5124
        s.mu.Unlock()
3✔
5125

3✔
5126
        // If we're not making a persistent connection, then we'll attempt to
3✔
5127
        // connect to the target peer. If the we can't make the connection, or
3✔
5128
        // the crypto negotiation breaks down, then return an error to the
3✔
5129
        // caller.
3✔
5130
        errChan := make(chan error, 1)
3✔
5131
        s.connectToPeer(addr, errChan, timeout)
3✔
5132

3✔
5133
        select {
3✔
5134
        case err := <-errChan:
3✔
5135
                return err
3✔
5136
        case <-s.quit:
×
5137
                return ErrServerShuttingDown
×
5138
        }
5139
}
5140

5141
// connectToPeer establishes a connection to a remote peer. errChan is used to
5142
// notify the caller if the connection attempt has failed. Otherwise, it will be
5143
// closed.
5144
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5145
        errChan chan<- error, timeout time.Duration) {
3✔
5146

3✔
5147
        conn, err := brontide.Dial(
3✔
5148
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5149
        )
3✔
5150
        if err != nil {
6✔
5151
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5152
                select {
3✔
5153
                case errChan <- err:
3✔
5154
                case <-s.quit:
×
5155
                }
5156
                return
3✔
5157
        }
5158

5159
        close(errChan)
3✔
5160

3✔
5161
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5162
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5163

3✔
5164
        s.OutboundPeerConnected(nil, conn)
3✔
5165
}
5166

5167
// DisconnectPeer sends the request to server to close the connection with peer
5168
// identified by public key.
5169
//
5170
// NOTE: This function is safe for concurrent access.
5171
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5172
        pubBytes := pubKey.SerializeCompressed()
3✔
5173
        pubStr := string(pubBytes)
3✔
5174

3✔
5175
        s.mu.Lock()
3✔
5176
        defer s.mu.Unlock()
3✔
5177

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

5186
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5187

3✔
5188
        s.cancelConnReqs(pubStr, nil)
3✔
5189

3✔
5190
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5191
        // them from this map so we don't attempt to re-connect after we
3✔
5192
        // disconnect.
3✔
5193
        delete(s.persistentPeers, pubStr)
3✔
5194
        delete(s.persistentPeersBackoff, pubStr)
3✔
5195

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

3✔
5203
        return nil
3✔
5204
}
5205

5206
// OpenChannel sends a request to the server to open a channel to the specified
5207
// peer identified by nodeKey with the passed channel funding parameters.
5208
//
5209
// NOTE: This function is safe for concurrent access.
5210
func (s *server) OpenChannel(
5211
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5212

3✔
5213
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5214
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5215
        // not blocked if the caller is not reading the updates.
3✔
5216
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5217
        req.Err = make(chan error, 1)
3✔
5218

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

×
5227
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5228
                return req.Updates, req.Err
×
5229
        }
×
5230
        req.Peer = peer
3✔
5231
        s.mu.RUnlock()
3✔
5232

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

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

×
5253
                return req.Updates, req.Err
×
5254
        }
×
5255

5256
        // Spawn a goroutine to send the funding workflow request to the funding
5257
        // manager. This allows the server to continue handling queries instead
5258
        // of blocking on this request which is exported as a synchronous
5259
        // request to the outside world.
5260
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5261

3✔
5262
        return req.Updates, req.Err
3✔
5263
}
5264

5265
// Peers returns a slice of all active peers.
5266
//
5267
// NOTE: This function is safe for concurrent access.
5268
func (s *server) Peers() []*peer.Brontide {
3✔
5269
        s.mu.RLock()
3✔
5270
        defer s.mu.RUnlock()
3✔
5271

3✔
5272
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5273
        for _, peer := range s.peersByPub {
6✔
5274
                peers = append(peers, peer)
3✔
5275
        }
3✔
5276

5277
        return peers
3✔
5278
}
5279

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

5291
        // Using 1/10 of our duration as a margin, compute a random offset to
5292
        // avoid the nodes entering connection cycles.
5293
        margin := nextBackoff / 10
3✔
5294

3✔
5295
        var wiggle big.Int
3✔
5296
        wiggle.SetUint64(uint64(margin))
3✔
5297
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5298
                // Randomizing is not mission critical, so we'll just return the
×
5299
                // current backoff.
×
5300
                return nextBackoff
×
5301
        }
×
5302

5303
        // Otherwise add in our wiggle, but subtract out half of the margin so
5304
        // that the backoff can tweaked by 1/20 in either direction.
5305
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5306
}
5307

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

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

3✔
5316
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5317
        if err != nil {
3✔
5318
                return nil, err
×
5319
        }
×
5320

5321
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5322
        if err != nil {
6✔
5323
                return nil, err
3✔
5324
        }
3✔
5325

5326
        if len(node.Addresses) == 0 {
6✔
5327
                return nil, errNoAdvertisedAddr
3✔
5328
        }
3✔
5329

5330
        return node.Addresses, nil
3✔
5331
}
5332

5333
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5334
// channel update for a target channel.
5335
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5336
        *lnwire.ChannelUpdate1, error) {
3✔
5337

3✔
5338
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5339
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5340
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5341
                if err != nil {
6✔
5342
                        return nil, err
3✔
5343
                }
3✔
5344

5345
                return netann.ExtractChannelUpdate(
3✔
5346
                        ourPubKey[:], info, edge1, edge2,
3✔
5347
                )
3✔
5348
        }
5349
}
5350

5351
// applyChannelUpdate applies the channel update to the different sub-systems of
5352
// the server. The useAlias boolean denotes whether or not to send an alias in
5353
// place of the real SCID.
5354
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5355
        op *wire.OutPoint, useAlias bool) error {
3✔
5356

3✔
5357
        var (
3✔
5358
                peerAlias    *lnwire.ShortChannelID
3✔
5359
                defaultAlias lnwire.ShortChannelID
3✔
5360
        )
3✔
5361

3✔
5362
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5363

3✔
5364
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5365
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5366
        if useAlias {
6✔
5367
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5368
                if foundAlias != defaultAlias {
6✔
5369
                        peerAlias = &foundAlias
3✔
5370
                }
3✔
5371
        }
5372

5373
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5374
                update, discovery.RemoteAlias(peerAlias),
3✔
5375
        )
3✔
5376
        select {
3✔
5377
        case err := <-errChan:
3✔
5378
                return err
3✔
5379
        case <-s.quit:
×
5380
                return ErrServerShuttingDown
×
5381
        }
5382
}
5383

5384
// SendCustomMessage sends a custom message to the peer with the specified
5385
// pubkey.
5386
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5387
        data []byte) error {
3✔
5388

3✔
5389
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5390
        if err != nil {
3✔
5391
                return err
×
5392
        }
×
5393

5394
        // We'll wait until the peer is active.
5395
        select {
3✔
5396
        case <-peer.ActiveSignal():
3✔
5397
        case <-peer.QuitSignal():
×
5398
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5399
        case <-s.quit:
×
5400
                return ErrServerShuttingDown
×
5401
        }
5402

5403
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5404
        if err != nil {
6✔
5405
                return err
3✔
5406
        }
3✔
5407

5408
        // Send the message as low-priority. For now we assume that all
5409
        // application-defined message are low priority.
5410
        return peer.SendMessageLazy(true, msg)
3✔
5411
}
5412

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

3✔
5421
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5422
                sweepAddr, err := wallet.NewAddress(
3✔
5423
                        lnwallet.TaprootPubkey, false,
3✔
5424
                        lnwallet.DefaultAccountName,
3✔
5425
                )
3✔
5426
                if err != nil {
3✔
5427
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5428
                }
×
5429

5430
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5431
                if err != nil {
3✔
5432
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5433
                }
×
5434

5435
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5436
                        wallet, netParams, addr,
3✔
5437
                )
3✔
5438
                if err != nil {
3✔
5439
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5440
                }
×
5441

5442
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5443
                        DeliveryAddress: addr,
3✔
5444
                        InternalKey:     internalKeyDesc,
3✔
5445
                })
3✔
5446
        }
5447
}
5448

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

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

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

5482
        for _, c := range pendings {
6✔
5483
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5484
                        continue
3✔
5485
                }
5486

5487
                // If the channel is still reported as pending, remove it from
5488
                // the map.
5489
                delete(closedSCIDs, c.ShortChannelID)
×
5490

×
5491
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5492
                        c.ShortChannelID)
×
5493
        }
5494

5495
        return closedSCIDs
3✔
5496
}
5497

5498
// getStartingBeat returns the current beat. This is used during the startup to
5499
// initialize blockbeat consumers.
5500
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5501
        // beat is the current blockbeat.
3✔
5502
        var beat *chainio.Beat
3✔
5503

3✔
5504
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5505
        // we will skip fetching the best block.
3✔
5506
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5507
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5508
                        "mode")
×
5509

×
5510
                return &chainio.Beat{}, nil
×
5511
        }
×
5512

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

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

3✔
5529
                // Update the current blockbeat.
3✔
5530
                beat = chainio.NewBeat(*bestBlock)
3✔
5531

5532
        case <-s.quit:
×
5533
                srvrLog.Debug("LND shutting down")
×
5534
        }
5535

5536
        return beat, nil
3✔
5537
}
5538

5539
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5540
// point has an active RBF chan closer.
5541
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5542
        chanPoint wire.OutPoint) bool {
3✔
5543

3✔
5544
        pubBytes := peerPub.SerializeCompressed()
3✔
5545

3✔
5546
        s.mu.RLock()
3✔
5547
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5548
        s.mu.RUnlock()
3✔
5549
        if !ok {
3✔
5550
                return false
×
5551
        }
×
5552

5553
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5554
}
5555

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

3✔
5564
        // First, we'll attempt to look up the channel based on it's
3✔
5565
        // ChannelPoint.
3✔
5566
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5567
        if err != nil {
3✔
5568
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5569
        }
×
5570

5571
        // From the channel, we can now get the pubkey of the peer, then use
5572
        // that to eventually get the chan closer.
5573
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5574

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

5584
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5585
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5586
        )
3✔
5587
        if err != nil {
3✔
5588
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5589
                        "%w", err)
×
5590
        }
×
5591

5592
        return closeUpdates, nil
3✔
5593
}
5594

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

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

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

5621
        return updates, nil
3✔
5622
}
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