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

lightningnetwork / lnd / 17301176272

28 Aug 2025 03:54PM UTC coverage: 66.765% (+9.4%) from 57.321%
17301176272

Pull #9868

github

web-flow
Merge 9549248bd into 0c2f045f5
Pull Request #9868: PoC Onion messaging using `msgmux`

150 of 225 new or added lines in 10 files covered. (66.67%)

9 existing lines in 4 files now uncovered.

136145 of 203917 relevant lines covered (66.76%)

21438.06 hits per line

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

69.51
/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
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
69
        "github.com/lightningnetwork/lnd/peer"
70
        "github.com/lightningnetwork/lnd/peernotifier"
71
        "github.com/lightningnetwork/lnd/pool"
72
        "github.com/lightningnetwork/lnd/queue"
73
        "github.com/lightningnetwork/lnd/routing"
74
        "github.com/lightningnetwork/lnd/routing/localchans"
75
        "github.com/lightningnetwork/lnd/routing/route"
76
        "github.com/lightningnetwork/lnd/subscribe"
77
        "github.com/lightningnetwork/lnd/sweep"
78
        "github.com/lightningnetwork/lnd/ticker"
79
        "github.com/lightningnetwork/lnd/tor"
80
        "github.com/lightningnetwork/lnd/walletunlocker"
81
        "github.com/lightningnetwork/lnd/watchtower/blob"
82
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
83
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
84
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
85
)
86

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

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

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

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

249
        chanStatusMgr *netann.ChanStatusManager
250

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

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

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

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

271
        mu sync.RWMutex
272

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

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

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

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

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

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

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

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

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

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

337
        invoicesDB invoices.InvoiceDB
338

339
        // paymentsDB is the DB that contains all functions for managing
340
        // payments.
341
        paymentsDB paymentsdb.DB
342

343
        aliasMgr *aliasmgr.Manager
344

345
        htlcSwitch *htlcswitch.Switch
346

347
        interceptableSwitch *htlcswitch.InterceptableSwitch
348

349
        invoices *invoices.InvoiceRegistry
350

351
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
352

353
        channelNotifier *channelnotifier.ChannelNotifier
354

355
        peerNotifier *peernotifier.PeerNotifier
356

357
        htlcNotifier *htlcswitch.HtlcNotifier
358

359
        witnessBeacon contractcourt.WitnessBeacon
360

361
        breachArbitrator *contractcourt.BreachArbitrator
362

363
        missionController *routing.MissionController
364
        defaultMC         *routing.MissionControl
365

366
        graphBuilder *graph.Builder
367

368
        chanRouter *routing.ChannelRouter
369

370
        controlTower routing.ControlTower
371

372
        authGossiper *discovery.AuthenticatedGossiper
373

374
        localChanMgr *localchans.Manager
375

376
        utxoNursery *contractcourt.UtxoNursery
377

378
        sweeper *sweep.UtxoSweeper
379

380
        chainArb *contractcourt.ChainArbitrator
381

382
        sphinx *hop.OnionProcessor
383

384
        towerClientMgr *wtclient.Manager
385

386
        connMgr *connmgr.ConnManager
387

388
        sigPool *lnwallet.SigPool
389

390
        writePool *pool.Write
391

392
        readPool *pool.Read
393

394
        tlsManager *TLSManager
395

396
        // featureMgr dispatches feature vectors for various contexts within the
397
        // daemon.
398
        featureMgr *feature.Manager
399

400
        // currentNodeAnn is the node announcement that has been broadcast to
401
        // the network upon startup, if the attributes of the node (us) has
402
        // changed since last start.
403
        currentNodeAnn *lnwire.NodeAnnouncement
404

405
        // chansToRestore is the set of channels that upon starting, the server
406
        // should attempt to restore/recover.
407
        chansToRestore walletunlocker.ChannelsToRecover
408

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

414
        // chanEventStore tracks the behaviour of channels and their remote peers to
415
        // provide insights into their health and performance.
416
        chanEventStore *chanfitness.ChannelEventStore
417

418
        hostAnn *netann.HostAnnouncer
419

420
        // livenessMonitor monitors that lnd has access to critical resources.
421
        livenessMonitor *healthcheck.Monitor
422

423
        customMessageServer *subscribe.Server
424

425
        onionMessageServer *subscribe.Server
426

427
        // txPublisher is a publisher with fee-bumping capability.
428
        txPublisher *sweep.TxPublisher
429

430
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
431
        // of new blocks.
432
        blockbeatDispatcher *chainio.BlockbeatDispatcher
433

434
        // peerAccessMan implements peer access controls.
435
        peerAccessMan *accessMan
436

437
        quit chan struct{}
438

439
        wg sync.WaitGroup
440
}
441

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

450
        s.wg.Add(1)
3✔
451
        go func() {
6✔
452
                defer func() {
6✔
453
                        graphSub.Cancel()
3✔
454
                        s.wg.Done()
3✔
455
                }()
3✔
456

457
                for {
6✔
458
                        select {
3✔
459
                        case <-s.quit:
3✔
460
                                return
3✔
461

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

469
                                for _, update := range topChange.NodeUpdates {
6✔
470
                                        pubKeyStr := string(
3✔
471
                                                update.IdentityKey.
3✔
472
                                                        SerializeCompressed(),
3✔
473
                                        )
3✔
474

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

484
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
485
                                                len(update.Addresses))
3✔
486

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

497
                                        s.mu.Lock()
3✔
498

3✔
499
                                        // Update the stored addresses for this
3✔
500
                                        // to peer to reflect the new set.
3✔
501
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
502

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

513
                                        s.mu.Unlock()
3✔
514

3✔
515
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
516
                                }
517
                        }
518
                }
519
        }()
520

521
        return nil
3✔
522
}
523

524
// CustomMessage is a custom message that is received from a peer.
525
type CustomMessage struct {
526
        // Peer is the peer pubkey
527
        Peer [33]byte
528

529
        // Msg is the custom wire message.
530
        Msg *lnwire.Custom
531
}
532

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

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

557
        if tor.IsOnionHost(host) {
3✔
558
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
559
        }
×
560

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

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

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

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

3✔
593
        var (
3✔
594
                err         error
3✔
595
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
596

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

3✔
604
        netParams := cfg.ActiveNetParams.Params
3✔
605

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

3✔
612
        writeBufferPool := pool.NewWriteBuffer(
3✔
613
                pool.DefaultWriteBufferGCInterval,
3✔
614
                pool.DefaultWriteBufferExpiryInterval,
3✔
615
        )
3✔
616

3✔
617
        writePool := pool.NewWrite(
3✔
618
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
619
        )
3✔
620

3✔
621
        readBufferPool := pool.NewReadBuffer(
3✔
622
                pool.DefaultReadBufferGCInterval,
3✔
623
                pool.DefaultReadBufferExpiryInterval,
3✔
624
        )
3✔
625

3✔
626
        readPool := pool.NewRead(
3✔
627
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
628
        )
3✔
629

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

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

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

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

3✔
676
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
677

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

3✔
693
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
694
                        cc.ChainNotifier,
3✔
695
                ),
3✔
696
                channelNotifier: channelnotifier.New(
3✔
697
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
698
                ),
3✔
699

3✔
700
                identityECDH:   nodeKeyECDH,
3✔
701
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
702
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
703

3✔
704
                listenAddrs: listenAddrs,
3✔
705

3✔
706
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
707
                // schedule
3✔
708
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
709

3✔
710
                torController: torController,
3✔
711

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

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

3✔
728
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
729

3✔
730
                customMessageServer: subscribe.NewServer(),
3✔
731

3✔
732
                onionMessageServer: subscribe.NewServer(),
3✔
733

3✔
734
                tlsManager: tlsManager,
3✔
735

3✔
736
                featureMgr: featureMgr,
3✔
737
                quit:       make(chan struct{}),
3✔
738
        }
3✔
739

3✔
740
        // Start the low-level services once they are initialized.
3✔
741
        //
3✔
742
        // TODO(yy): break the server startup into four steps,
3✔
743
        // 1. init the low-level services.
3✔
744
        // 2. start the low-level services.
3✔
745
        // 3. init the high-level services.
3✔
746
        // 4. start the high-level services.
3✔
747
        if err := s.startLowLevelServices(); err != nil {
3✔
748
                return nil, err
×
749
        }
×
750

751
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
752
        if err != nil {
3✔
753
                return nil, err
×
754
        }
×
755

756
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
757
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
758
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
759
        )
3✔
760
        s.invoices = invoices.NewRegistry(
3✔
761
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
762
        )
3✔
763

3✔
764
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
765

3✔
766
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
767
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
768

3✔
769
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
770
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
771
                if err != nil {
3✔
772
                        return err
×
773
                }
×
774

775
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
776

3✔
777
                return nil
3✔
778
        }
779

780
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
781
        if err != nil {
3✔
782
                return nil, err
×
783
        }
×
784

785
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
786
                DB:                   dbs.ChanStateDB,
3✔
787
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
788
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
789
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
790
                LocalChannelClose: func(pubKey []byte,
3✔
791
                        request *htlcswitch.ChanClose) {
6✔
792

3✔
793
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
794
                        if err != nil {
3✔
795
                                srvrLog.Errorf("unable to close channel, peer"+
×
796
                                        " with %v id can't be found: %v",
×
797
                                        pubKey, err,
×
798
                                )
×
799
                                return
×
800
                        }
×
801

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

837
        s.witnessBeacon = newPreimageBeacon(
3✔
838
                dbs.ChanStateDB.NewWitnessCache(),
3✔
839
                s.interceptableSwitch.ForwardPacket,
3✔
840
        )
3✔
841

3✔
842
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
843
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
844
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
845
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
846
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
847
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
848
                MessageSigner:            s.nodeSigner,
3✔
849
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
850
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
851
                DB:                       s.chanStateDB,
3✔
852
                Graph:                    dbs.GraphDB,
3✔
853
        }
3✔
854

3✔
855
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
856
        if err != nil {
3✔
857
                return nil, err
×
858
        }
×
859
        s.chanStatusMgr = chanStatusMgr
3✔
860

3✔
861
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
862
        // port forwarding for users behind a NAT.
3✔
863
        if cfg.NAT {
3✔
864
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
865

×
866
                discoveryTimeout := time.Duration(10 * time.Second)
×
867

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

×
882
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
883
                                "enabled device")
×
884

×
885
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
886
                        if err != nil {
×
887
                                err := fmt.Errorf("unable to discover a "+
×
888
                                        "NAT-PMP enabled device on the local "+
×
889
                                        "network: %v", err)
×
890
                                srvrLog.Error(err)
×
891
                                return nil, err
×
892
                        }
×
893

894
                        s.natTraversal = pmp
×
895
                }
896
        }
897

898
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
899
        // Set the self node which represents our node in the graph.
3✔
900
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
901
        if err != nil {
3✔
902
                return nil, err
×
903
        }
×
904

905
        // The router will get access to the payment ID sequencer, such that it
906
        // can generate unique payment IDs.
907
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
908
        if err != nil {
3✔
909
                return nil, err
×
910
        }
×
911

912
        // Instantiate mission control with config from the sub server.
913
        //
914
        // TODO(joostjager): When we are further in the process of moving to sub
915
        // servers, the mission control instance itself can be moved there too.
916
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
917

3✔
918
        // We only initialize a probability estimator if there's no custom one.
3✔
919
        var estimator routing.Estimator
3✔
920
        if cfg.Estimator != nil {
3✔
921
                estimator = cfg.Estimator
×
922
        } else {
3✔
923
                switch routingConfig.ProbabilityEstimatorType {
3✔
924
                case routing.AprioriEstimatorName:
3✔
925
                        aCfg := routingConfig.AprioriConfig
3✔
926
                        aprioriConfig := routing.AprioriConfig{
3✔
927
                                AprioriHopProbability: aCfg.HopProbability,
3✔
928
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
929
                                AprioriWeight:         aCfg.Weight,
3✔
930
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
931
                        }
3✔
932

3✔
933
                        estimator, err = routing.NewAprioriEstimator(
3✔
934
                                aprioriConfig,
3✔
935
                        )
3✔
936
                        if err != nil {
3✔
937
                                return nil, err
×
938
                        }
×
939

940
                case routing.BimodalEstimatorName:
×
941
                        bCfg := routingConfig.BimodalConfig
×
942
                        bimodalConfig := routing.BimodalConfig{
×
943
                                BimodalNodeWeight: bCfg.NodeWeight,
×
944
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
945
                                        bCfg.Scale,
×
946
                                ),
×
947
                                BimodalDecayTime: bCfg.DecayTime,
×
948
                        }
×
949

×
950
                        estimator, err = routing.NewBimodalEstimator(
×
951
                                bimodalConfig,
×
952
                        )
×
953
                        if err != nil {
×
954
                                return nil, err
×
955
                        }
×
956

957
                default:
×
958
                        return nil, fmt.Errorf("unknown estimator type %v",
×
959
                                routingConfig.ProbabilityEstimatorType)
×
960
                }
961
        }
962

963
        mcCfg := &routing.MissionControlConfig{
3✔
964
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
965
                Estimator:               estimator,
3✔
966
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
967
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
968
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
969
        }
3✔
970

3✔
971
        s.missionController, err = routing.NewMissionController(
3✔
972
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
973
        )
3✔
974
        if err != nil {
3✔
975
                return nil, fmt.Errorf("can't create mission control "+
×
976
                        "manager: %w", err)
×
977
        }
×
978
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
979
                routing.DefaultMissionControlNamespace,
3✔
980
        )
3✔
981
        if err != nil {
3✔
982
                return nil, fmt.Errorf("can't create mission control in the "+
×
983
                        "default namespace: %w", err)
×
984
        }
×
985

986
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
987
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
988
                int64(routingConfig.AttemptCost),
3✔
989
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
990
                routingConfig.MinRouteProbability)
3✔
991

3✔
992
        pathFindingConfig := routing.PathFindingConfig{
3✔
993
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
994
                        routingConfig.AttemptCost,
3✔
995
                ),
3✔
996
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
997
                MinProbability: routingConfig.MinRouteProbability,
3✔
998
        }
3✔
999

3✔
1000
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1001
        if err != nil {
3✔
1002
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1003
        }
×
1004
        paymentSessionSource := &routing.SessionSource{
3✔
1005
                GraphSessionFactory: dbs.GraphDB,
3✔
1006
                SourceNode:          sourceNode,
3✔
1007
                MissionControl:      s.defaultMC,
3✔
1008
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1009
                PathFindingConfig:   pathFindingConfig,
3✔
1010
        }
3✔
1011

3✔
1012
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1013

3✔
1014
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1015
                cfg.Routing.StrictZombiePruning
3✔
1016

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

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

1054
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1055
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1056
        if err != nil {
3✔
1057
                return nil, err
×
1058
        }
×
1059
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1060
        if err != nil {
3✔
1061
                return nil, err
×
1062
        }
×
1063

1064
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1065

3✔
1066
        s.authGossiper = discovery.New(discovery.Config{
3✔
1067
                Graph:                 s.graphBuilder,
3✔
1068
                ChainIO:               s.cc.ChainIO,
3✔
1069
                Notifier:              s.cc.ChainNotifier,
3✔
1070
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1071
                Broadcast:             s.BroadcastMessage,
3✔
1072
                ChanSeries:            chanSeries,
3✔
1073
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1074
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1075
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1076
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1077
                        error) {
3✔
1078

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

1112
        accessCfg := &accessManConfig{
3✔
1113
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1114
                        error) {
6✔
1115

3✔
1116
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1117
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1118
                                genesisHash[:],
3✔
1119
                        )
3✔
1120
                },
3✔
1121
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1122
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1123
        }
1124

1125
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1126
        if err != nil {
3✔
1127
                return nil, err
×
1128
        }
×
1129

1130
        s.peerAccessMan = peerAccessMan
3✔
1131

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

3✔
1142
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1143
                                func(c *models.ChannelEdgeInfo,
3✔
1144
                                        e *models.ChannelEdgePolicy,
3✔
1145
                                        _ *models.ChannelEdgePolicy) error {
6✔
1146

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

×
1159
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1160
                },
×
1161
        }
1162

1163
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1164
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1165
        )
3✔
1166
        if err != nil {
3✔
1167
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1168
                return nil, err
×
1169
        }
×
1170

1171
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1172
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1173
        )
3✔
1174
        if err != nil {
3✔
1175
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1176
                return nil, err
×
1177
        }
×
1178

1179
        aggregator := sweep.NewBudgetAggregator(
3✔
1180
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1181
                s.implCfg.AuxSweeper,
3✔
1182
        )
3✔
1183

3✔
1184
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1185
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1186
                Wallet:     cc.Wallet,
3✔
1187
                Estimator:  cc.FeeEstimator,
3✔
1188
                Notifier:   cc.ChainNotifier,
3✔
1189
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1190
        })
3✔
1191

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

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

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

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

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

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

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

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

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

3✔
1309
                        // processACK will handle the BreachArbitrator ACKing
3✔
1310
                        // the event.
3✔
1311
                        finalErr := make(chan error, 1)
3✔
1312
                        processACK := func(brarErr error) {
6✔
1313
                                if brarErr != nil {
3✔
1314
                                        finalErr <- brarErr
×
1315
                                        return
×
1316
                                }
×
1317

1318
                                // If the BreachArbitrator successfully handled
1319
                                // the event, we can signal that the handoff
1320
                                // was successful.
1321
                                finalErr <- nil
3✔
1322
                        }
1323

1324
                        event := &contractcourt.ContractBreachEvent{
3✔
1325
                                ChanPoint:         chanPoint,
3✔
1326
                                ProcessACK:        processACK,
3✔
1327
                                BreachRetribution: breachRet,
3✔
1328
                        }
3✔
1329

3✔
1330
                        // Send the contract breach event to the
3✔
1331
                        // BreachArbitrator.
3✔
1332
                        select {
3✔
1333
                        case contractBreaches <- event:
3✔
1334
                        case <-s.quit:
×
1335
                                return ErrServerShuttingDown
×
1336
                        }
1337

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

1363
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1364
                QueryIncomingCircuit: func(
1365
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1366

3✔
1367
                        // Get the circuit map.
3✔
1368
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1369

3✔
1370
                        // Lookup the outgoing circuit.
3✔
1371
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1372
                        if pc == nil {
5✔
1373
                                return nil
2✔
1374
                        }
2✔
1375

1376
                        return &pc.Incoming
3✔
1377
                },
1378
                AuxLeafStore: implCfg.AuxLeafStore,
1379
                AuxSigner:    implCfg.AuxSigner,
1380
                AuxResolver:  implCfg.AuxContractResolver,
1381
        }, dbs.ChanStateDB)
1382

1383
        // Select the configuration and funding parameters for Bitcoin.
1384
        chainCfg := cfg.Bitcoin
3✔
1385
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1386
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1387

3✔
1388
        var chanIDSeed [32]byte
3✔
1389
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1390
                return nil, err
×
1391
        }
×
1392

1393
        // Wrap the DeleteChannelEdges method so that the funding manager can
1394
        // use it without depending on several layers of indirection.
1395
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1396
                *models.ChannelEdgePolicy, error) {
6✔
1397

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

1411
                // Grab our key to find our policy.
1412
                var ourKey [33]byte
3✔
1413
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1414

3✔
1415
                var ourPolicy *models.ChannelEdgePolicy
3✔
1416
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1417
                        ourPolicy = e1
3✔
1418
                } else {
6✔
1419
                        ourPolicy = e2
3✔
1420
                }
3✔
1421

1422
                if ourPolicy == nil {
3✔
1423
                        // Something is wrong, so return an error.
×
1424
                        return nil, fmt.Errorf("we don't have an edge")
×
1425
                }
×
1426

1427
                err = s.graphDB.DeleteChannelEdges(
3✔
1428
                        false, false, scid.ToUint64(),
3✔
1429
                )
3✔
1430
                return ourPolicy, err
3✔
1431
        }
1432

1433
        // For the reservationTimeout and the zombieSweeperInterval different
1434
        // values are set in case we are in a dev environment so enhance test
1435
        // capacilities.
1436
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1437
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1438

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

3✔
1449
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1450
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1451

3✔
1452
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1453
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1454
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1455
        }
3✔
1456

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

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

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

1503
                        minConf := uint64(3)
×
1504
                        maxConf := uint64(6)
×
1505

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

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

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

1542
                        // If this is a wumbo channel, then we'll require the
1543
                        // max value.
1544
                        if chanAmt > MaxFundingAmount {
×
1545
                                return maxRemoteDelay
×
1546
                        }
×
1547

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

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

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

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

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

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

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

1661
        // Assemble a peer notifier which will provide clients with subscriptions
1662
        // to peer online and offline events.
1663
        s.peerNotifier = peernotifier.New()
3✔
1664

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

1680
        if cfg.WtClient.Active {
6✔
1681
                policy := wtpolicy.DefaultPolicy()
3✔
1682
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1683

3✔
1684
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1685
                // protocol operations on sat/kw.
3✔
1686
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1687
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1688
                )
3✔
1689

3✔
1690
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1691

3✔
1692
                if err := policy.Validate(); err != nil {
3✔
1693
                        return nil, err
×
1694
                }
×
1695

1696
                // authDial is the wrapper around the btrontide.Dial for the
1697
                // watchtower.
1698
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1699
                        netAddr *lnwire.NetAddress,
3✔
1700
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1701

3✔
1702
                        return brontide.Dial(
3✔
1703
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1704
                        )
3✔
1705
                }
3✔
1706

1707
                // buildBreachRetribution is a call-back that can be used to
1708
                // query the BreachRetribution info and channel type given a
1709
                // channel ID and commitment height.
1710
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1711
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1712
                        channeldb.ChannelType, error) {
6✔
1713

3✔
1714
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1715
                                nil, chanID,
3✔
1716
                        )
3✔
1717
                        if err != nil {
3✔
1718
                                return nil, 0, err
×
1719
                        }
×
1720

1721
                        br, err := lnwallet.NewBreachRetribution(
3✔
1722
                                channel, commitHeight, 0, nil,
3✔
1723
                                implCfg.AuxLeafStore,
3✔
1724
                                implCfg.AuxContractResolver,
3✔
1725
                        )
3✔
1726
                        if err != nil {
3✔
1727
                                return nil, 0, err
×
1728
                        }
×
1729

1730
                        return br, channel.ChanType, nil
3✔
1731
                }
1732

1733
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1734

3✔
1735
                // Copy the policy for legacy channels and set the blob flag
3✔
1736
                // signalling support for anchor channels.
3✔
1737
                anchorPolicy := policy
3✔
1738
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1739

3✔
1740
                // Copy the policy for legacy channels and set the blob flag
3✔
1741
                // signalling support for taproot channels.
3✔
1742
                taprootPolicy := policy
3✔
1743
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1744
                        blob.FlagTaprootChannel,
3✔
1745
                )
3✔
1746

3✔
1747
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1748
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1749
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1750
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1751
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1752
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1753
                                error) {
6✔
1754

3✔
1755
                                return s.channelNotifier.
3✔
1756
                                        SubscribeChannelEvents()
3✔
1757
                        },
3✔
1758
                        Signer: cc.Wallet.Cfg.Signer,
1759
                        NewAddress: func() ([]byte, error) {
3✔
1760
                                addr, err := newSweepPkScriptGen(
3✔
1761
                                        cc.Wallet, netParams,
3✔
1762
                                )().Unpack()
3✔
1763
                                if err != nil {
3✔
1764
                                        return nil, err
×
1765
                                }
×
1766

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

1783
        if len(cfg.ExternalHosts) != 0 {
3✔
1784
                advertisedIPs := make(map[string]struct{})
×
1785
                for _, addr := range s.currentNodeAnn.Addresses {
×
1786
                        advertisedIPs[addr.String()] = struct{}{}
×
1787
                }
×
1788

1789
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1790
                        Hosts:         cfg.ExternalHosts,
×
1791
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1792
                        LookupHost: func(host string) (net.Addr, error) {
×
1793
                                return lncfg.ParseAddressString(
×
1794
                                        host, strconv.Itoa(defaultPeerPort),
×
1795
                                        cfg.net.ResolveTCPAddr,
×
1796
                                )
×
1797
                        },
×
1798
                        AdvertisedIPs: advertisedIPs,
1799
                        AnnounceNewIPs: netann.IPAnnouncer(
1800
                                func(modifier ...netann.NodeAnnModifier) (
1801
                                        lnwire.NodeAnnouncement, error) {
×
1802

×
1803
                                        return s.genNodeAnnouncement(
×
1804
                                                nil, modifier...,
×
1805
                                        )
×
1806
                                }),
×
1807
                })
1808
        }
1809

1810
        // Create liveness monitor.
1811
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1812

3✔
1813
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1814
        for i, listenAddr := range listenAddrs {
6✔
1815
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1816
                // doesn't need to call the general lndResolveTCP function
3✔
1817
                // since we are resolving a local address.
3✔
1818

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

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

3✔
1850
        // Finally, register the subsystems in blockbeat.
3✔
1851
        s.registerBlockConsumers()
3✔
1852

3✔
1853
        return s, nil
3✔
1854
}
1855

1856
// UpdateRoutingConfig is a callback function to update the routing config
1857
// values in the main cfg.
1858
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1859
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1860

3✔
1861
        switch c := cfg.Estimator.Config().(type) {
3✔
1862
        case routing.AprioriConfig:
3✔
1863
                routerCfg.ProbabilityEstimatorType =
3✔
1864
                        routing.AprioriEstimatorName
3✔
1865

3✔
1866
                targetCfg := routerCfg.AprioriConfig
3✔
1867
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1868
                targetCfg.Weight = c.AprioriWeight
3✔
1869
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1870
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1871

1872
        case routing.BimodalConfig:
3✔
1873
                routerCfg.ProbabilityEstimatorType =
3✔
1874
                        routing.BimodalEstimatorName
3✔
1875

3✔
1876
                targetCfg := routerCfg.BimodalConfig
3✔
1877
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1878
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1879
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1880
        }
1881

1882
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1883
}
1884

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

1904
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1905
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1906
// may differ from what is on disk.
1907
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1908
        error) {
3✔
1909

3✔
1910
        data, err := u.DataToSign()
3✔
1911
        if err != nil {
3✔
1912
                return nil, err
×
1913
        }
×
1914

1915
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1916
}
1917

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

3✔
1931
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1932
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1933
                srvrLog.Info("Disabling chain backend checks for " +
×
1934
                        "nochainbackend mode")
×
1935

×
1936
                chainBackendAttempts = 0
×
1937
        }
×
1938

1939
        chainHealthCheck := healthcheck.NewObservation(
3✔
1940
                "chain backend",
3✔
1941
                cc.HealthCheck,
3✔
1942
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1943
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1944
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1945
                chainBackendAttempts,
3✔
1946
        )
3✔
1947

3✔
1948
        diskCheck := healthcheck.NewObservation(
3✔
1949
                "disk space",
3✔
1950
                func() error {
3✔
1951
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1952
                                cfg.LndDir,
×
1953
                        )
×
1954
                        if err != nil {
×
1955
                                return err
×
1956
                        }
×
1957

1958
                        // If we have more free space than we require,
1959
                        // we return a nil error.
1960
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1961
                                return nil
×
1962
                        }
×
1963

1964
                        return fmt.Errorf("require: %v free space, got: %v",
×
1965
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1966
                                free)
×
1967
                },
1968
                cfg.HealthChecks.DiskCheck.Interval,
1969
                cfg.HealthChecks.DiskCheck.Timeout,
1970
                cfg.HealthChecks.DiskCheck.Backoff,
1971
                cfg.HealthChecks.DiskCheck.Attempts,
1972
        )
1973

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

1988
                        // If the certificate is not outdated, no error needs
1989
                        // to be returned
1990
                        return nil
×
1991
                },
1992
                cfg.HealthChecks.TLSCheck.Interval,
1993
                cfg.HealthChecks.TLSCheck.Timeout,
1994
                cfg.HealthChecks.TLSCheck.Backoff,
1995
                cfg.HealthChecks.TLSCheck.Attempts,
1996
        )
1997

1998
        checks := []*healthcheck.Observation{
3✔
1999
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2000
        }
3✔
2001

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

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

3✔
2032
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2033
                        "remote signer connection",
3✔
2034
                        rpcwallet.HealthCheck(
3✔
2035
                                s.cfg.RemoteSigner,
3✔
2036

3✔
2037
                                // For the health check we might to be even
3✔
2038
                                // stricter than the initial/normal connect, so
3✔
2039
                                // we use the health check timeout here.
3✔
2040
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2041
                        ),
3✔
2042
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2043
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2044
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2045
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2046
                )
3✔
2047
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2048
        }
3✔
2049

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

×
2068
                                leader, err := leaderElector.IsLeader(
×
2069
                                        timeoutCtx,
×
2070
                                )
×
2071
                                if err != nil {
×
2072
                                        return fmt.Errorf("unable to check if "+
×
2073
                                                "still leader: %v", err)
×
2074
                                }
×
2075

2076
                                if !leader {
×
2077
                                        srvrLog.Debug("Not the current leader")
×
2078
                                        return fmt.Errorf("not the current " +
×
2079
                                                "leader")
×
2080
                                }
×
2081

2082
                                return nil
×
2083
                        },
2084
                        cfg.HealthChecks.LeaderCheck.Interval,
2085
                        cfg.HealthChecks.LeaderCheck.Timeout,
2086
                        cfg.HealthChecks.LeaderCheck.Backoff,
2087
                        cfg.HealthChecks.LeaderCheck.Attempts,
2088
                )
2089

2090
                checks = append(checks, leaderCheck)
×
2091
        }
2092

2093
        // If we have not disabled all of our health checks, we create a
2094
        // liveness monitor with our configured checks.
2095
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2096
                &healthcheck.Config{
3✔
2097
                        Checks:   checks,
3✔
2098
                        Shutdown: srvrLog.Criticalf,
3✔
2099
                },
3✔
2100
        )
3✔
2101
}
2102

2103
// Started returns true if the server has been started, and false otherwise.
2104
// NOTE: This function is safe for concurrent access.
2105
func (s *server) Started() bool {
3✔
2106
        return atomic.LoadInt32(&s.active) != 0
3✔
2107
}
3✔
2108

2109
// cleaner is used to aggregate "cleanup" functions during an operation that
2110
// starts several subsystems. In case one of the subsystem fails to start
2111
// and a proper resource cleanup is required, the "run" method achieves this
2112
// by running all these added "cleanup" functions.
2113
type cleaner []func() error
2114

2115
// add is used to add a cleanup function to be called when
2116
// the run function is executed.
2117
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2118
        return append(c, cleanup)
3✔
2119
}
3✔
2120

2121
// run is used to run all the previousely added cleanup functions.
2122
func (c cleaner) run() {
×
2123
        for i := len(c) - 1; i >= 0; i-- {
×
2124
                if err := c[i](); err != nil {
×
2125
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2126
                }
×
2127
        }
2128
}
2129

2130
// startLowLevelServices starts the low-level services of the server. These
2131
// services must be started successfully before running the main server. The
2132
// services are,
2133
// 1. the chain notifier.
2134
//
2135
// TODO(yy): identify and add more low-level services here.
2136
func (s *server) startLowLevelServices() error {
3✔
2137
        var startErr error
3✔
2138

3✔
2139
        cleanup := cleaner{}
3✔
2140

3✔
2141
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2142
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2143
                startErr = err
×
2144
        }
×
2145

2146
        if startErr != nil {
3✔
2147
                cleanup.run()
×
2148
        }
×
2149

2150
        return startErr
3✔
2151
}
2152

2153
// Start starts the main daemon server, all requested listeners, and any helper
2154
// goroutines.
2155
// NOTE: This function is safe for concurrent access.
2156
//
2157
//nolint:funlen
2158
func (s *server) Start(ctx context.Context) error {
3✔
2159
        // Get the current blockbeat.
3✔
2160
        beat, err := s.getStartingBeat()
3✔
2161
        if err != nil {
3✔
2162
                return err
×
2163
        }
×
2164

2165
        var startErr error
3✔
2166

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

3✔
2172
        s.start.Do(func() {
6✔
2173
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2174
                if err := s.customMessageServer.Start(); err != nil {
3✔
2175
                        startErr = err
×
2176
                        return
×
2177
                }
×
2178

2179
                cleanup = cleanup.add(s.onionMessageServer.Stop)
3✔
2180
                if err := s.onionMessageServer.Start(); err != nil {
3✔
NEW
2181
                        startErr = err
×
NEW
2182
                        return
×
NEW
2183
                }
×
2184

2185
                if s.hostAnn != nil {
3✔
2186
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2187
                        if err := s.hostAnn.Start(); err != nil {
×
2188
                                startErr = err
×
2189
                                return
×
2190
                        }
×
2191
                }
2192

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

2201
                // Start the notification server. This is used so channel
2202
                // management goroutines can be notified when a funding
2203
                // transaction reaches a sufficient number of confirmations, or
2204
                // when the input for the funding transaction is spent in an
2205
                // attempt at an uncooperative close by the counterparty.
2206
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2207
                if err := s.sigPool.Start(); err != nil {
3✔
2208
                        startErr = err
×
2209
                        return
×
2210
                }
×
2211

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

2218
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2219
                if err := s.readPool.Start(); err != nil {
3✔
2220
                        startErr = err
×
2221
                        return
×
2222
                }
×
2223

2224
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2225
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2226
                        startErr = err
×
2227
                        return
×
2228
                }
×
2229

2230
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2231
                if err := s.channelNotifier.Start(); err != nil {
3✔
2232
                        startErr = err
×
2233
                        return
×
2234
                }
×
2235

2236
                cleanup = cleanup.add(func() error {
3✔
2237
                        return s.peerNotifier.Stop()
×
2238
                })
×
2239
                if err := s.peerNotifier.Start(); err != nil {
3✔
2240
                        startErr = err
×
2241
                        return
×
2242
                }
×
2243

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

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

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

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

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

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

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

2288
                // htlcSwitch must be started before chainArb since the latter
2289
                // relies on htlcSwitch to deliver resolution message upon
2290
                // start.
2291
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2292
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2293
                        startErr = err
×
2294
                        return
×
2295
                }
×
2296

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

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

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

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

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

2327
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2328
                if err := s.chanRouter.Start(); err != nil {
3✔
2329
                        startErr = err
×
2330
                        return
×
2331
                }
×
2332
                // The authGossiper depends on the chanRouter and therefore
2333
                // should be started after it.
2334
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2335
                if err := s.authGossiper.Start(); err != nil {
3✔
2336
                        startErr = err
×
2337
                        return
×
2338
                }
×
2339

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

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

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

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

2364
                cleanup.add(func() error {
3✔
2365
                        s.missionController.StopStoreTickers()
×
2366
                        return nil
×
2367
                })
×
2368
                s.missionController.RunStoreTickers()
3✔
2369

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

2402
                // chanSubSwapper must be started after the `channelNotifier`
2403
                // because it depends on channel events as a synchronization
2404
                // point.
2405
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2406
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2407
                        startErr = err
×
2408
                        return
×
2409
                }
×
2410

2411
                if s.torController != nil {
3✔
2412
                        cleanup = cleanup.add(s.torController.Stop)
×
2413
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2414
                                startErr = err
×
2415
                                return
×
2416
                        }
×
2417
                }
2418

2419
                if s.natTraversal != nil {
3✔
2420
                        s.wg.Add(1)
×
2421
                        go s.watchExternalIP()
×
2422
                }
×
2423

2424
                // Start connmgr last to prevent connections before init.
2425
                cleanup = cleanup.add(func() error {
3✔
2426
                        s.connMgr.Stop()
×
2427
                        return nil
×
2428
                })
×
2429

2430
                // RESOLVE: s.connMgr.Start() is called here, but
2431
                // brontide.NewListener() is called in newServer. This means
2432
                // that we are actually listening and partially accepting
2433
                // inbound connections even before the connMgr starts.
2434
                //
2435
                // TODO(yy): move the log into the connMgr's `Start` method.
2436
                srvrLog.Info("connMgr starting...")
3✔
2437
                s.connMgr.Start()
3✔
2438
                srvrLog.Debug("connMgr started")
3✔
2439

3✔
2440
                // If peers are specified as a config option, we'll add those
3✔
2441
                // peers first.
3✔
2442
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2443
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2444
                                peerAddrCfg,
3✔
2445
                        )
3✔
2446
                        if err != nil {
3✔
2447
                                startErr = fmt.Errorf("unable to parse peer "+
×
2448
                                        "pubkey from config: %v", err)
×
2449
                                return
×
2450
                        }
×
2451
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2452
                        if err != nil {
3✔
2453
                                startErr = fmt.Errorf("unable to parse peer "+
×
2454
                                        "address provided as a config option: "+
×
2455
                                        "%v", err)
×
2456
                                return
×
2457
                        }
×
2458

2459
                        peerAddr := &lnwire.NetAddress{
3✔
2460
                                IdentityKey: parsedPubkey,
3✔
2461
                                Address:     addr,
3✔
2462
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2463
                        }
3✔
2464

3✔
2465
                        err = s.ConnectToPeer(
3✔
2466
                                peerAddr, true,
3✔
2467
                                s.cfg.ConnectionTimeout,
3✔
2468
                        )
3✔
2469
                        if err != nil {
3✔
2470
                                startErr = fmt.Errorf("unable to connect to "+
×
2471
                                        "peer address provided as a config "+
×
2472
                                        "option: %v", err)
×
2473
                                return
×
2474
                        }
×
2475
                }
2476

2477
                // Subscribe to NodeAnnouncements that advertise new addresses
2478
                // our persistent peers.
2479
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2480
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2481
                                "addr: %v", err)
×
2482

×
2483
                        startErr = err
×
2484
                        return
×
2485
                }
×
2486

2487
                // With all the relevant sub-systems started, we'll now attempt
2488
                // to establish persistent connections to our direct channel
2489
                // collaborators within the network. Before doing so however,
2490
                // we'll prune our set of link nodes found within the database
2491
                // to ensure we don't reconnect to any nodes we no longer have
2492
                // open channels with.
2493
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2494
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2495

×
2496
                        startErr = err
×
2497
                        return
×
2498
                }
×
2499

2500
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2501
                        srvrLog.Errorf("Failed to establish persistent "+
×
2502
                                "connections: %v", err)
×
2503
                }
×
2504

2505
                // setSeedList is a helper function that turns multiple DNS seed
2506
                // server tuples from the command line or config file into the
2507
                // data structure we need and does a basic formal sanity check
2508
                // in the process.
2509
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2510
                        if len(tuples) == 0 {
×
2511
                                return
×
2512
                        }
×
2513

2514
                        result := make([][2]string, len(tuples))
×
2515
                        for idx, tuple := range tuples {
×
2516
                                tuple = strings.TrimSpace(tuple)
×
2517
                                if len(tuple) == 0 {
×
2518
                                        return
×
2519
                                }
×
2520

2521
                                servers := strings.Split(tuple, ",")
×
2522
                                if len(servers) > 2 || len(servers) == 0 {
×
2523
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2524
                                                "seed tuple: %v", servers)
×
2525
                                        return
×
2526
                                }
×
2527

2528
                                copy(result[idx][:], servers)
×
2529
                        }
2530

2531
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2532
                }
2533

2534
                // Let users overwrite the DNS seed nodes. We only allow them
2535
                // for bitcoin mainnet/testnet/signet.
2536
                if s.cfg.Bitcoin.MainNet {
3✔
2537
                        setSeedList(
×
2538
                                s.cfg.Bitcoin.DNSSeeds,
×
2539
                                chainreg.BitcoinMainnetGenesis,
×
2540
                        )
×
2541
                }
×
2542
                if s.cfg.Bitcoin.TestNet3 {
3✔
2543
                        setSeedList(
×
2544
                                s.cfg.Bitcoin.DNSSeeds,
×
2545
                                chainreg.BitcoinTestnetGenesis,
×
2546
                        )
×
2547
                }
×
2548
                if s.cfg.Bitcoin.TestNet4 {
3✔
2549
                        setSeedList(
×
2550
                                s.cfg.Bitcoin.DNSSeeds,
×
2551
                                chainreg.BitcoinTestnet4Genesis,
×
2552
                        )
×
2553
                }
×
2554
                if s.cfg.Bitcoin.SigNet {
3✔
2555
                        setSeedList(
×
2556
                                s.cfg.Bitcoin.DNSSeeds,
×
2557
                                chainreg.BitcoinSignetGenesis,
×
2558
                        )
×
2559
                }
×
2560

2561
                // If network bootstrapping hasn't been disabled, then we'll
2562
                // configure the set of active bootstrappers, and launch a
2563
                // dedicated goroutine to maintain a set of persistent
2564
                // connections.
2565
                if !s.cfg.NoNetBootstrap {
6✔
2566
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2567
                        if err != nil {
3✔
2568
                                startErr = err
×
2569
                                return
×
2570
                        }
×
2571

2572
                        s.wg.Add(1)
3✔
2573
                        go s.peerBootstrapper(
3✔
2574
                                ctx, defaultMinPeers, bootstrappers,
3✔
2575
                        )
3✔
2576
                } else {
3✔
2577
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2578
                }
3✔
2579

2580
                // Start the blockbeat after all other subsystems have been
2581
                // started so they are ready to receive new blocks.
2582
                cleanup = cleanup.add(func() error {
3✔
2583
                        s.blockbeatDispatcher.Stop()
×
2584
                        return nil
×
2585
                })
×
2586
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2587
                        startErr = err
×
2588
                        return
×
2589
                }
×
2590

2591
                // Set the active flag now that we've completed the full
2592
                // startup.
2593
                atomic.StoreInt32(&s.active, 1)
3✔
2594
        })
2595

2596
        if startErr != nil {
3✔
2597
                cleanup.run()
×
2598
        }
×
2599
        return startErr
3✔
2600
}
2601

2602
// Stop gracefully shutsdown the main daemon server. This function will signal
2603
// any active goroutines, or helper objects to exit, then blocks until they've
2604
// all successfully exited. Additionally, any/all listeners are closed.
2605
// NOTE: This function is safe for concurrent access.
2606
func (s *server) Stop() error {
3✔
2607
        s.stop.Do(func() {
6✔
2608
                atomic.StoreInt32(&s.stopping, 1)
3✔
2609

3✔
2610
                ctx := context.Background()
3✔
2611

3✔
2612
                close(s.quit)
3✔
2613

3✔
2614
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2615
                s.connMgr.Stop()
3✔
2616

3✔
2617
                // Stop dispatching blocks to other systems immediately.
3✔
2618
                s.blockbeatDispatcher.Stop()
3✔
2619

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

2682
                // Update channel.backup file. Make sure to do it before
2683
                // stopping chanSubSwapper.
2684
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2685
                        ctx, s.chanStateDB, s.addrSource,
3✔
2686
                )
3✔
2687
                if err != nil {
3✔
2688
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2689
                                err)
×
2690
                } else {
3✔
2691
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2692
                        if err != nil {
6✔
2693
                                srvrLog.Warnf("Manual update of channel "+
3✔
2694
                                        "backup failed: %v", err)
3✔
2695
                        }
3✔
2696
                }
2697

2698
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2699
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2700
                }
×
2701
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2702
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2703
                }
×
2704
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2705
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2706
                                err)
×
2707
                }
×
2708
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2709
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2710
                                err)
×
2711
                }
×
2712
                s.missionController.StopStoreTickers()
3✔
2713

3✔
2714
                // Disconnect from each active peers to ensure that
3✔
2715
                // peerTerminationWatchers signal completion to each peer.
3✔
2716
                for _, peer := range s.Peers() {
6✔
2717
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2718
                        if err != nil {
3✔
2719
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2720
                                        "received error: %v", peer.IdentityKey(),
×
2721
                                        err,
×
2722
                                )
×
2723
                        }
×
2724
                }
2725

2726
                // Now that all connections have been torn down, stop the tower
2727
                // client which will reliably flush all queued states to the
2728
                // tower. If this is halted for any reason, the force quit timer
2729
                // will kick in and abort to allow this method to return.
2730
                if s.towerClientMgr != nil {
6✔
2731
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2732
                                srvrLog.Warnf("Unable to shut down tower "+
×
2733
                                        "client manager: %v", err)
×
2734
                        }
×
2735
                }
2736

2737
                if s.hostAnn != nil {
3✔
2738
                        if err := s.hostAnn.Stop(); err != nil {
×
2739
                                srvrLog.Warnf("unable to shut down host "+
×
2740
                                        "annoucner: %v", err)
×
2741
                        }
×
2742
                }
2743

2744
                if s.livenessMonitor != nil {
6✔
2745
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2746
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2747
                                        "monitor: %v", err)
×
2748
                        }
×
2749
                }
2750

2751
                // Wait for all lingering goroutines to quit.
2752
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2753
                s.wg.Wait()
3✔
2754

3✔
2755
                srvrLog.Debug("Stopping buffer pools...")
3✔
2756
                s.sigPool.Stop()
3✔
2757
                s.writePool.Stop()
3✔
2758
                s.readPool.Stop()
3✔
2759
        })
2760

2761
        return nil
3✔
2762
}
2763

2764
// Stopped returns true if the server has been instructed to shutdown.
2765
// NOTE: This function is safe for concurrent access.
2766
func (s *server) Stopped() bool {
3✔
2767
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2768
}
3✔
2769

2770
// configurePortForwarding attempts to set up port forwarding for the different
2771
// ports that the server will be listening on.
2772
//
2773
// NOTE: This should only be used when using some kind of NAT traversal to
2774
// automatically set up forwarding rules.
2775
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2776
        ip, err := s.natTraversal.ExternalIP()
×
2777
        if err != nil {
×
2778
                return nil, err
×
2779
        }
×
2780
        s.lastDetectedIP = ip
×
2781

×
2782
        externalIPs := make([]string, 0, len(ports))
×
2783
        for _, port := range ports {
×
2784
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2785
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2786
                        continue
×
2787
                }
2788

2789
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2790
                externalIPs = append(externalIPs, hostIP)
×
2791
        }
2792

2793
        return externalIPs, nil
×
2794
}
2795

2796
// removePortForwarding attempts to clear the forwarding rules for the different
2797
// ports the server is currently listening on.
2798
//
2799
// NOTE: This should only be used when using some kind of NAT traversal to
2800
// automatically set up forwarding rules.
2801
func (s *server) removePortForwarding() {
×
2802
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2803
        for _, port := range forwardedPorts {
×
2804
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2805
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2806
                                "port %d: %v", port, err)
×
2807
                }
×
2808
        }
2809
}
2810

2811
// watchExternalIP continuously checks for an updated external IP address every
2812
// 15 minutes. Once a new IP address has been detected, it will automatically
2813
// handle port forwarding rules and send updated node announcements to the
2814
// currently connected peers.
2815
//
2816
// NOTE: This MUST be run as a goroutine.
2817
func (s *server) watchExternalIP() {
×
2818
        defer s.wg.Done()
×
2819

×
2820
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2821
        // up by the server.
×
2822
        defer s.removePortForwarding()
×
2823

×
2824
        // Keep track of the external IPs set by the user to avoid replacing
×
2825
        // them when detecting a new IP.
×
2826
        ipsSetByUser := make(map[string]struct{})
×
2827
        for _, ip := range s.cfg.ExternalIPs {
×
2828
                ipsSetByUser[ip.String()] = struct{}{}
×
2829
        }
×
2830

2831
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2832

×
2833
        ticker := time.NewTicker(15 * time.Minute)
×
2834
        defer ticker.Stop()
×
2835
out:
×
2836
        for {
×
2837
                select {
×
2838
                case <-ticker.C:
×
2839
                        // We'll start off by making sure a new IP address has
×
2840
                        // been detected.
×
2841
                        ip, err := s.natTraversal.ExternalIP()
×
2842
                        if err != nil {
×
2843
                                srvrLog.Debugf("Unable to retrieve the "+
×
2844
                                        "external IP address: %v", err)
×
2845
                                continue
×
2846
                        }
2847

2848
                        // Periodically renew the NAT port forwarding.
2849
                        for _, port := range forwardedPorts {
×
2850
                                err := s.natTraversal.AddPortMapping(port)
×
2851
                                if err != nil {
×
2852
                                        srvrLog.Warnf("Unable to automatically "+
×
2853
                                                "re-create port forwarding using %s: %v",
×
2854
                                                s.natTraversal.Name(), err)
×
2855
                                } else {
×
2856
                                        srvrLog.Debugf("Automatically re-created "+
×
2857
                                                "forwarding for port %d using %s to "+
×
2858
                                                "advertise external IP",
×
2859
                                                port, s.natTraversal.Name())
×
2860
                                }
×
2861
                        }
2862

2863
                        if ip.Equal(s.lastDetectedIP) {
×
2864
                                continue
×
2865
                        }
2866

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

×
2869
                        // Next, we'll craft the new addresses that will be
×
2870
                        // included in the new node announcement and advertised
×
2871
                        // to the network. Each address will consist of the new
×
2872
                        // IP detected and one of the currently advertised
×
2873
                        // ports.
×
2874
                        var newAddrs []net.Addr
×
2875
                        for _, port := range forwardedPorts {
×
2876
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2877
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2878
                                if err != nil {
×
2879
                                        srvrLog.Debugf("Unable to resolve "+
×
2880
                                                "host %v: %v", addr, err)
×
2881
                                        continue
×
2882
                                }
2883

2884
                                newAddrs = append(newAddrs, addr)
×
2885
                        }
2886

2887
                        // Skip the update if we weren't able to resolve any of
2888
                        // the new addresses.
2889
                        if len(newAddrs) == 0 {
×
2890
                                srvrLog.Debug("Skipping node announcement " +
×
2891
                                        "update due to not being able to " +
×
2892
                                        "resolve any new addresses")
×
2893
                                continue
×
2894
                        }
2895

2896
                        // Now, we'll need to update the addresses in our node's
2897
                        // announcement in order to propagate the update
2898
                        // throughout the network. We'll only include addresses
2899
                        // that have a different IP from the previous one, as
2900
                        // the previous IP is no longer valid.
2901
                        currentNodeAnn := s.getNodeAnnouncement()
×
2902

×
2903
                        for _, addr := range currentNodeAnn.Addresses {
×
2904
                                host, _, err := net.SplitHostPort(addr.String())
×
2905
                                if err != nil {
×
2906
                                        srvrLog.Debugf("Unable to determine "+
×
2907
                                                "host from address %v: %v",
×
2908
                                                addr, err)
×
2909
                                        continue
×
2910
                                }
2911

2912
                                // We'll also make sure to include external IPs
2913
                                // set manually by the user.
2914
                                _, setByUser := ipsSetByUser[addr.String()]
×
2915
                                if setByUser || host != s.lastDetectedIP.String() {
×
2916
                                        newAddrs = append(newAddrs, addr)
×
2917
                                }
×
2918
                        }
2919

2920
                        // Then, we'll generate a new timestamped node
2921
                        // announcement with the updated addresses and broadcast
2922
                        // it to our peers.
2923
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2924
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2925
                        )
×
2926
                        if err != nil {
×
2927
                                srvrLog.Debugf("Unable to generate new node "+
×
2928
                                        "announcement: %v", err)
×
2929
                                continue
×
2930
                        }
2931

2932
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2933
                        if err != nil {
×
2934
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2935
                                        "announcement to peers: %v", err)
×
2936
                                continue
×
2937
                        }
2938

2939
                        // Finally, update the last IP seen to the current one.
2940
                        s.lastDetectedIP = ip
×
2941
                case <-s.quit:
×
2942
                        break out
×
2943
                }
2944
        }
2945
}
2946

2947
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2948
// based on the server, and currently active bootstrap mechanisms as defined
2949
// within the current configuration.
2950
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2951
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2952

3✔
2953
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2954

3✔
2955
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2956
        // this can be used by default if we've already partially seeded the
3✔
2957
        // network.
3✔
2958
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2959
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2960
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2961
        )
3✔
2962
        if err != nil {
3✔
2963
                return nil, err
×
2964
        }
×
2965
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2966

3✔
2967
        // If this isn't using simnet or regtest mode, then one of our
3✔
2968
        // additional bootstrapping sources will be the set of running DNS
3✔
2969
        // seeds.
3✔
2970
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2971
                //nolint:ll
×
2972
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2973

×
2974
                // If we have a set of DNS seeds for this chain, then we'll add
×
2975
                // it as an additional bootstrapping source.
×
2976
                if ok {
×
2977
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2978
                                "seeds: %v", dnsSeeds)
×
2979

×
2980
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2981
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2982
                        )
×
2983
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2984
                }
×
2985
        }
2986

2987
        return bootStrappers, nil
3✔
2988
}
2989

2990
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2991
// needs to ignore, which is made of three parts,
2992
//   - the node itself needs to be skipped as it doesn't make sense to connect
2993
//     to itself.
2994
//   - the peers that already have connections with, as in s.peersByPub.
2995
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2996
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2997
        s.mu.RLock()
3✔
2998
        defer s.mu.RUnlock()
3✔
2999

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

3✔
3002
        // We should ignore ourselves from bootstrapping.
3✔
3003
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3004
        ignore[selfKey] = struct{}{}
3✔
3005

3✔
3006
        // Ignore all connected peers.
3✔
3007
        for _, peer := range s.peersByPub {
3✔
3008
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3009
                ignore[nID] = struct{}{}
×
3010
        }
×
3011

3012
        // Ignore all persistent peers as they have a dedicated reconnecting
3013
        // process.
3014
        for pubKeyStr := range s.persistentPeers {
3✔
3015
                var nID autopilot.NodeID
×
3016
                copy(nID[:], []byte(pubKeyStr))
×
3017
                ignore[nID] = struct{}{}
×
3018
        }
×
3019

3020
        return ignore
3✔
3021
}
3022

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

3✔
3031
        defer s.wg.Done()
3✔
3032

3✔
3033
        // Before we continue, init the ignore peers map.
3✔
3034
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3035

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

3✔
3040
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3041
        // peers.
3✔
3042
        //
3✔
3043
        // We'll use a 15 second backoff, and double the time every time an
3✔
3044
        // epoch fails up to a ceiling.
3✔
3045
        backOff := time.Second * 15
3✔
3046

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

3✔
3052
        // We'll use the number of attempts and errors to determine if we need
3✔
3053
        // to increase the time between discovery epochs.
3✔
3054
        var epochErrors uint32 // To be used atomically.
3✔
3055
        var epochAttempts uint32
3✔
3056

3✔
3057
        for {
6✔
3058
                select {
3✔
3059
                // The ticker has just woken us up, so we'll need to check if
3060
                // we need to attempt to connect our to any more peers.
3061
                case <-sampleTicker.C:
×
3062
                        // Obtain the current number of peers, so we can gauge
×
3063
                        // if we need to sample more peers or not.
×
3064
                        s.mu.RLock()
×
3065
                        numActivePeers := uint32(len(s.peersByPub))
×
3066
                        s.mu.RUnlock()
×
3067

×
3068
                        // If we have enough peers, then we can loop back
×
3069
                        // around to the next round as we're done here.
×
3070
                        if numActivePeers >= numTargetPeers {
×
3071
                                continue
×
3072
                        }
3073

3074
                        // If all of our attempts failed during this last back
3075
                        // off period, then will increase our backoff to 5
3076
                        // minute ceiling to avoid an excessive number of
3077
                        // queries
3078
                        //
3079
                        // TODO(roasbeef): add reverse policy too?
3080

3081
                        if epochAttempts > 0 &&
×
3082
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3083

×
3084
                                sampleTicker.Stop()
×
3085

×
3086
                                backOff *= 2
×
3087
                                if backOff > bootstrapBackOffCeiling {
×
3088
                                        backOff = bootstrapBackOffCeiling
×
3089
                                }
×
3090

3091
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3092
                                        "%v", backOff)
×
3093
                                sampleTicker = time.NewTicker(backOff)
×
3094
                                continue
×
3095
                        }
3096

3097
                        atomic.StoreUint32(&epochErrors, 0)
×
3098
                        epochAttempts = 0
×
3099

×
3100
                        // Since we know need more peers, we'll compute the
×
3101
                        // exact number we need to reach our threshold.
×
3102
                        numNeeded := numTargetPeers - numActivePeers
×
3103

×
3104
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3105
                                "peers", numNeeded)
×
3106

×
3107
                        // With the number of peers we need calculated, we'll
×
3108
                        // query the network bootstrappers to sample a set of
×
3109
                        // random addrs for us.
×
3110
                        //
×
3111
                        // Before we continue, get a copy of the ignore peers
×
3112
                        // map.
×
3113
                        ignoreList = s.createBootstrapIgnorePeers()
×
3114

×
3115
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3116
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3117
                        )
×
3118
                        if err != nil {
×
3119
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3120
                                        "peers: %v", err)
×
3121
                                continue
×
3122
                        }
3123

3124
                        // Finally, we'll launch a new goroutine for each
3125
                        // prospective peer candidates.
3126
                        for _, addr := range peerAddrs {
×
3127
                                epochAttempts++
×
3128

×
3129
                                go func(a *lnwire.NetAddress) {
×
3130
                                        // TODO(roasbeef): can do AS, subnet,
×
3131
                                        // country diversity, etc
×
3132
                                        errChan := make(chan error, 1)
×
3133
                                        s.connectToPeer(
×
3134
                                                a, errChan,
×
3135
                                                s.cfg.ConnectionTimeout,
×
3136
                                        )
×
3137
                                        select {
×
3138
                                        case err := <-errChan:
×
3139
                                                if err == nil {
×
3140
                                                        return
×
3141
                                                }
×
3142

3143
                                                srvrLog.Errorf("Unable to "+
×
3144
                                                        "connect to %v: %v",
×
3145
                                                        a, err)
×
3146
                                                atomic.AddUint32(&epochErrors, 1)
×
3147
                                        case <-s.quit:
×
3148
                                        }
3149
                                }(addr)
3150
                        }
3151
                case <-s.quit:
3✔
3152
                        return
3✔
3153
                }
3154
        }
3155
}
3156

3157
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3158
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3159
// query back off each time we encounter a failure.
3160
const bootstrapBackOffCeiling = time.Minute * 5
3161

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

3✔
3169
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3170
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3171

3✔
3172
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3173
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3174
        var delaySignal <-chan time.Time
3✔
3175
        delayTime := time.Second * 2
3✔
3176

3✔
3177
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3178
        // then the main peer bootstrap logic.
3✔
3179
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3180

3✔
3181
        for attempts := 0; ; attempts++ {
6✔
3182
                // Check if the server has been requested to shut down in order
3✔
3183
                // to prevent blocking.
3✔
3184
                if s.Stopped() {
3✔
3185
                        return
×
3186
                }
×
3187

3188
                // We can exit our aggressive initial peer bootstrapping stage
3189
                // if we've reached out target number of peers.
3190
                s.mu.RLock()
3✔
3191
                numActivePeers := uint32(len(s.peersByPub))
3✔
3192
                s.mu.RUnlock()
3✔
3193

3✔
3194
                if numActivePeers >= numTargetPeers {
6✔
3195
                        return
3✔
3196
                }
3✔
3197

3198
                if attempts > 0 {
3✔
3199
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3200
                                "bootstrap peers (attempt #%v)", delayTime,
×
3201
                                attempts)
×
3202

×
3203
                        // We've completed at least one iterating and haven't
×
3204
                        // finished, so we'll start to insert a delay period
×
3205
                        // between each attempt.
×
3206
                        delaySignal = time.After(delayTime)
×
3207
                        select {
×
3208
                        case <-delaySignal:
×
3209
                        case <-s.quit:
×
3210
                                return
×
3211
                        }
3212

3213
                        // After our delay, we'll double the time we wait up to
3214
                        // the max back off period.
3215
                        delayTime *= 2
×
3216
                        if delayTime > backOffCeiling {
×
3217
                                delayTime = backOffCeiling
×
3218
                        }
×
3219
                }
3220

3221
                // Otherwise, we'll request for the remaining number of peers
3222
                // in order to reach our target.
3223
                peersNeeded := numTargetPeers - numActivePeers
3✔
3224
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3225
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3226
                )
3✔
3227
                if err != nil {
3✔
3228
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3229
                                "peers: %v", err)
×
3230
                        continue
×
3231
                }
3232

3233
                // Then, we'll attempt to establish a connection to the
3234
                // different peer addresses retrieved by our bootstrappers.
3235
                var wg sync.WaitGroup
3✔
3236
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3237
                        wg.Add(1)
3✔
3238
                        go func(addr *lnwire.NetAddress) {
6✔
3239
                                defer wg.Done()
3✔
3240

3✔
3241
                                errChan := make(chan error, 1)
3✔
3242
                                go s.connectToPeer(
3✔
3243
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3244
                                )
3✔
3245

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

3269
                wg.Wait()
3✔
3270
        }
3271
}
3272

3273
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3274
// order to listen for inbound connections over Tor.
3275
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3276
        // Determine the different ports the server is listening on. The onion
×
3277
        // service's virtual port will map to these ports and one will be picked
×
3278
        // at random when the onion service is being accessed.
×
3279
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3280
        for _, listenAddr := range s.listenAddrs {
×
3281
                port := listenAddr.(*net.TCPAddr).Port
×
3282
                listenPorts = append(listenPorts, port)
×
3283
        }
×
3284

3285
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3286
        if err != nil {
×
3287
                return err
×
3288
        }
×
3289

3290
        // Once the port mapping has been set, we can go ahead and automatically
3291
        // create our onion service. The service's private key will be saved to
3292
        // disk in order to regain access to this service when restarting `lnd`.
3293
        onionCfg := tor.AddOnionConfig{
×
3294
                VirtualPort: defaultPeerPort,
×
3295
                TargetPorts: listenPorts,
×
3296
                Store: tor.NewOnionFile(
×
3297
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3298
                        encrypter,
×
3299
                ),
×
3300
        }
×
3301

×
3302
        switch {
×
3303
        case s.cfg.Tor.V2:
×
3304
                onionCfg.Type = tor.V2
×
3305
        case s.cfg.Tor.V3:
×
3306
                onionCfg.Type = tor.V3
×
3307
        }
3308

3309
        addr, err := s.torController.AddOnion(onionCfg)
×
3310
        if err != nil {
×
3311
                return err
×
3312
        }
×
3313

3314
        // Now that the onion service has been created, we'll add the onion
3315
        // address it can be reached at to our list of advertised addresses.
3316
        newNodeAnn, err := s.genNodeAnnouncement(
×
3317
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3318
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3319
                },
×
3320
        )
3321
        if err != nil {
×
3322
                return fmt.Errorf("unable to generate new node "+
×
3323
                        "announcement: %v", err)
×
3324
        }
×
3325

3326
        // Finally, we'll update the on-disk version of our announcement so it
3327
        // will eventually propagate to nodes in the network.
3328
        selfNode := &models.LightningNode{
×
3329
                HaveNodeAnnouncement: true,
×
3330
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3331
                Addresses:            newNodeAnn.Addresses,
×
3332
                Alias:                newNodeAnn.Alias.String(),
×
3333
                Features: lnwire.NewFeatureVector(
×
3334
                        newNodeAnn.Features, lnwire.Features,
×
3335
                ),
×
3336
                Color:        newNodeAnn.RGBColor,
×
3337
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3338
        }
×
3339
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3340
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3341
                return fmt.Errorf("can't set self node: %w", err)
×
3342
        }
×
3343

3344
        return nil
×
3345
}
3346

3347
// findChannel finds a channel given a public key and ChannelID. It is an
3348
// optimization that is quicker than seeking for a channel given only the
3349
// ChannelID.
3350
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3351
        *channeldb.OpenChannel, error) {
3✔
3352

3✔
3353
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3354
        if err != nil {
3✔
3355
                return nil, err
×
3356
        }
×
3357

3358
        for _, channel := range nodeChans {
6✔
3359
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3360
                        return channel, nil
3✔
3361
                }
3✔
3362
        }
3363

3364
        return nil, fmt.Errorf("unable to find channel")
3✔
3365
}
3366

3367
// getNodeAnnouncement fetches the current, fully signed node announcement.
3368
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3369
        s.mu.Lock()
3✔
3370
        defer s.mu.Unlock()
3✔
3371

3✔
3372
        return *s.currentNodeAnn
3✔
3373
}
3✔
3374

3375
// genNodeAnnouncement generates and returns the current fully signed node
3376
// announcement. The time stamp of the announcement will be updated in order
3377
// to ensure it propagates through the network.
3378
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3379
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3380

3✔
3381
        s.mu.Lock()
3✔
3382
        defer s.mu.Unlock()
3✔
3383

3✔
3384
        // Create a shallow copy of the current node announcement to work on.
3✔
3385
        // This ensures the original announcement remains unchanged
3✔
3386
        // until the new announcement is fully signed and valid.
3✔
3387
        newNodeAnn := *s.currentNodeAnn
3✔
3388

3✔
3389
        // First, try to update our feature manager with the updated set of
3✔
3390
        // features.
3✔
3391
        if features != nil {
6✔
3392
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3393
                        feature.SetNodeAnn: features,
3✔
3394
                }
3✔
3395
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3396
                if err != nil {
6✔
3397
                        return lnwire.NodeAnnouncement{}, err
3✔
3398
                }
3✔
3399

3400
                // If we could successfully update our feature manager, add
3401
                // an update modifier to include these new features to our
3402
                // set.
3403
                modifiers = append(
3✔
3404
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3405
                )
3✔
3406
        }
3407

3408
        // Always update the timestamp when refreshing to ensure the update
3409
        // propagates.
3410
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3411

3✔
3412
        // Apply the requested changes to the node announcement.
3✔
3413
        for _, modifier := range modifiers {
6✔
3414
                modifier(&newNodeAnn)
3✔
3415
        }
3✔
3416

3417
        // Sign a new update after applying all of the passed modifiers.
3418
        err := netann.SignNodeAnnouncement(
3✔
3419
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3420
        )
3✔
3421
        if err != nil {
3✔
3422
                return lnwire.NodeAnnouncement{}, err
×
3423
        }
×
3424

3425
        // If signing succeeds, update the current announcement.
3426
        *s.currentNodeAnn = newNodeAnn
3✔
3427

3✔
3428
        return *s.currentNodeAnn, nil
3✔
3429
}
3430

3431
// updateAndBroadcastSelfNode generates a new node announcement
3432
// applying the giving modifiers and updating the time stamp
3433
// to ensure it propagates through the network. Then it broadcasts
3434
// it to the network.
3435
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3436
        features *lnwire.RawFeatureVector,
3437
        modifiers ...netann.NodeAnnModifier) error {
3✔
3438

3✔
3439
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3440
        if err != nil {
6✔
3441
                return fmt.Errorf("unable to generate new node "+
3✔
3442
                        "announcement: %v", err)
3✔
3443
        }
3✔
3444

3445
        // Update the on-disk version of our announcement.
3446
        // Load and modify self node istead of creating anew instance so we
3447
        // don't risk overwriting any existing values.
3448
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3449
        if err != nil {
3✔
3450
                return fmt.Errorf("unable to get current source node: %w", err)
×
3451
        }
×
3452

3453
        selfNode.HaveNodeAnnouncement = true
3✔
3454
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3455
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3456
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3457
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3458
        selfNode.Color = newNodeAnn.RGBColor
3✔
3459
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3460

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

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

3467
        // Finally, propagate it to the nodes in the network.
3468
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3469
        if err != nil {
3✔
3470
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3471
                        "announcement to peers: %v", err)
×
3472
                return err
×
3473
        }
×
3474

3475
        return nil
3✔
3476
}
3477

3478
type nodeAddresses struct {
3479
        pubKey    *btcec.PublicKey
3480
        addresses []net.Addr
3481
}
3482

3483
// establishPersistentConnections attempts to establish persistent connections
3484
// to all our direct channel collaborators. In order to promote liveness of our
3485
// active channels, we instruct the connection manager to attempt to establish
3486
// and maintain persistent connections to all our direct channel counterparties.
3487
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3488
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3489
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3490
        // since other PubKey forms can't be compared.
3✔
3491
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3492

3✔
3493
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3494
        // attempt to connect to based on our set of previous connections. Set
3✔
3495
        // the reconnection port to the default peer port.
3✔
3496
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3497
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3498
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3499
        }
×
3500

3501
        for _, node := range linkNodes {
6✔
3502
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3503
                nodeAddrs := &nodeAddresses{
3✔
3504
                        pubKey:    node.IdentityPub,
3✔
3505
                        addresses: node.Addresses,
3✔
3506
                }
3✔
3507
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3508
        }
3✔
3509

3510
        // After checking our previous connections for addresses to connect to,
3511
        // iterate through the nodes in our channel graph to find addresses
3512
        // that have been added via NodeAnnouncement messages.
3513
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3514
        // each of the nodes.
3515
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3516
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3517
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3518

3✔
3519
                // If the remote party has announced the channel to us, but we
3✔
3520
                // haven't yet, then we won't have a policy. However, we don't
3✔
3521
                // need this to connect to the peer, so we'll log it and move on.
3✔
3522
                if !havePolicy {
3✔
3523
                        srvrLog.Warnf("No channel policy found for "+
×
3524
                                "ChannelPoint(%v): ", chanPoint)
×
3525
                }
×
3526

3527
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3528

3✔
3529
                // Add all unique addresses from channel
3✔
3530
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3531
                // connect to for this peer.
3✔
3532
                addrSet := make(map[string]net.Addr)
3✔
3533
                for _, addr := range channelPeer.Addresses {
6✔
3534
                        switch addr.(type) {
3✔
3535
                        case *net.TCPAddr:
3✔
3536
                                addrSet[addr.String()] = addr
3✔
3537

3538
                        // We'll only attempt to connect to Tor addresses if Tor
3539
                        // outbound support is enabled.
3540
                        case *tor.OnionAddr:
×
3541
                                if s.cfg.Tor.Active {
×
3542
                                        addrSet[addr.String()] = addr
×
3543
                                }
×
3544
                        }
3545
                }
3546

3547
                // If this peer is also recorded as a link node, we'll add any
3548
                // additional addresses that have not already been selected.
3549
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3550
                if ok {
6✔
3551
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3552
                                switch lnAddress.(type) {
3✔
3553
                                case *net.TCPAddr:
3✔
3554
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3555

3556
                                // We'll only attempt to connect to Tor
3557
                                // addresses if Tor outbound support is enabled.
3558
                                case *tor.OnionAddr:
×
3559
                                        if s.cfg.Tor.Active {
×
3560
                                                //nolint:ll
×
3561
                                                addrSet[lnAddress.String()] = lnAddress
×
3562
                                        }
×
3563
                                }
3564
                        }
3565
                }
3566

3567
                // Construct a slice of the deduped addresses.
3568
                var addrs []net.Addr
3✔
3569
                for _, addr := range addrSet {
6✔
3570
                        addrs = append(addrs, addr)
3✔
3571
                }
3✔
3572

3573
                n := &nodeAddresses{
3✔
3574
                        addresses: addrs,
3✔
3575
                }
3✔
3576
                n.pubKey, err = channelPeer.PubKey()
3✔
3577
                if err != nil {
3✔
3578
                        return err
×
3579
                }
×
3580

3581
                graphAddrs[pubStr] = n
3✔
3582
                return nil
3✔
3583
        }
3584
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3585
                ctx, forEachSrcNodeChan, func() {
6✔
3586
                        clear(graphAddrs)
3✔
3587
                },
3✔
3588
        )
3589
        if err != nil {
3✔
3590
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3591
                        "%v", err)
×
3592

×
3593
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3594
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3595

×
3596
                        return err
×
3597
                }
×
3598
        }
3599

3600
        // Combine the addresses from the link nodes and the channel graph.
3601
        for pubStr, nodeAddr := range graphAddrs {
6✔
3602
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3603
        }
3✔
3604

3605
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3606
                len(nodeAddrsMap))
3✔
3607

3✔
3608
        // Acquire and hold server lock until all persistent connection requests
3✔
3609
        // have been recorded and sent to the connection manager.
3✔
3610
        s.mu.Lock()
3✔
3611
        defer s.mu.Unlock()
3✔
3612

3✔
3613
        // Iterate through the combined list of addresses from prior links and
3✔
3614
        // node announcements and attempt to reconnect to each node.
3✔
3615
        var numOutboundConns int
3✔
3616
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3617
                // Add this peer to the set of peers we should maintain a
3✔
3618
                // persistent connection with. We set the value to false to
3✔
3619
                // indicate that we should not continue to reconnect if the
3✔
3620
                // number of channels returns to zero, since this peer has not
3✔
3621
                // been requested as perm by the user.
3✔
3622
                s.persistentPeers[pubStr] = false
3✔
3623
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3624
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3625
                }
3✔
3626

3627
                for _, address := range nodeAddr.addresses {
6✔
3628
                        // Create a wrapper address which couples the IP and
3✔
3629
                        // the pubkey so the brontide authenticated connection
3✔
3630
                        // can be established.
3✔
3631
                        lnAddr := &lnwire.NetAddress{
3✔
3632
                                IdentityKey: nodeAddr.pubKey,
3✔
3633
                                Address:     address,
3✔
3634
                        }
3✔
3635

3✔
3636
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3637
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3638
                }
3✔
3639

3640
                // We'll connect to the first 10 peers immediately, then
3641
                // randomly stagger any remaining connections if the
3642
                // stagger initial reconnect flag is set. This ensures
3643
                // that mobile nodes or nodes with a small number of
3644
                // channels obtain connectivity quickly, but larger
3645
                // nodes are able to disperse the costs of connecting to
3646
                // all peers at once.
3647
                if numOutboundConns < numInstantInitReconnect ||
3✔
3648
                        !s.cfg.StaggerInitialReconnect {
6✔
3649

3✔
3650
                        go s.connectToPersistentPeer(pubStr)
3✔
3651
                } else {
3✔
3652
                        go s.delayInitialReconnect(pubStr)
×
3653
                }
×
3654

3655
                numOutboundConns++
3✔
3656
        }
3657

3658
        return nil
3✔
3659
}
3660

3661
// delayInitialReconnect will attempt a reconnection to the given peer after
3662
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3663
//
3664
// NOTE: This method MUST be run as a goroutine.
3665
func (s *server) delayInitialReconnect(pubStr string) {
×
3666
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3667
        select {
×
3668
        case <-time.After(delay):
×
3669
                s.connectToPersistentPeer(pubStr)
×
3670
        case <-s.quit:
×
3671
        }
3672
}
3673

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

3✔
3680
        s.mu.Lock()
3✔
3681
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3682
                delete(s.persistentPeers, pubKeyStr)
3✔
3683
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3684
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3685
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3686
                s.mu.Unlock()
3✔
3687

3✔
3688
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3689
                        "peer has no open channels", compressedPubKey)
3✔
3690

3✔
3691
                return
3✔
3692
        }
3✔
3693
        s.mu.Unlock()
3✔
3694
}
3695

3696
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3697
// is instead used to remove persistent peer state for a peer that has been
3698
// disconnected for good cause by the server. Currently, a gossip ban from
3699
// sending garbage and the server running out of restricted-access
3700
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3701
// future, this function may expand when more ban criteria is added.
3702
//
3703
// NOTE: The server's write lock MUST be held when this is called.
3704
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3705
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3706
                delete(s.persistentPeers, remotePub)
×
3707
                delete(s.persistentPeersBackoff, remotePub)
×
3708
                delete(s.persistentPeerAddrs, remotePub)
×
3709
                s.cancelConnReqs(remotePub, nil)
×
3710
        }
×
3711
}
3712

3713
// BroadcastMessage sends a request to the server to broadcast a set of
3714
// messages to all peers other than the one specified by the `skips` parameter.
3715
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3716
// the target peers.
3717
//
3718
// NOTE: This function is safe for concurrent access.
3719
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3720
        msgs ...lnwire.Message) error {
3✔
3721

3✔
3722
        // Filter out peers found in the skips map. We synchronize access to
3✔
3723
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3724
        // exact set of peers present at the time of invocation.
3✔
3725
        s.mu.RLock()
3✔
3726
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3727
        for pubStr, sPeer := range s.peersByPub {
6✔
3728
                if skips != nil {
6✔
3729
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3730
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3731
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3732
                                continue
3✔
3733
                        }
3734
                }
3735

3736
                peers = append(peers, sPeer)
3✔
3737
        }
3738
        s.mu.RUnlock()
3✔
3739

3✔
3740
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3741
        // all messages to each of peers.
3✔
3742
        var wg sync.WaitGroup
3✔
3743
        for _, sPeer := range peers {
6✔
3744
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3745
                        sPeer.PubKey())
3✔
3746

3✔
3747
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3748
                wg.Add(1)
3✔
3749
                s.wg.Add(1)
3✔
3750
                go func(p lnpeer.Peer) {
6✔
3751
                        defer s.wg.Done()
3✔
3752
                        defer wg.Done()
3✔
3753

3✔
3754
                        p.SendMessageLazy(false, msgs...)
3✔
3755
                }(sPeer)
3✔
3756
        }
3757

3758
        // Wait for all messages to have been dispatched before returning to
3759
        // caller.
3760
        wg.Wait()
3✔
3761

3✔
3762
        return nil
3✔
3763
}
3764

3765
// NotifyWhenOnline can be called by other subsystems to get notified when a
3766
// particular peer comes online. The peer itself is sent across the peerChan.
3767
//
3768
// NOTE: This function is safe for concurrent access.
3769
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3770
        peerChan chan<- lnpeer.Peer) {
3✔
3771

3✔
3772
        s.mu.Lock()
3✔
3773

3✔
3774
        // Compute the target peer's identifier.
3✔
3775
        pubStr := string(peerKey[:])
3✔
3776

3✔
3777
        // Check if peer is connected.
3✔
3778
        peer, ok := s.peersByPub[pubStr]
3✔
3779
        if ok {
6✔
3780
                // Unlock here so that the mutex isn't held while we are
3✔
3781
                // waiting for the peer to become active.
3✔
3782
                s.mu.Unlock()
3✔
3783

3✔
3784
                // Wait until the peer signals that it is actually active
3✔
3785
                // rather than only in the server's maps.
3✔
3786
                select {
3✔
3787
                case <-peer.ActiveSignal():
3✔
3788
                case <-peer.QuitSignal():
×
3789
                        // The peer quit, so we'll add the channel to the slice
×
3790
                        // and return.
×
3791
                        s.mu.Lock()
×
3792
                        s.peerConnectedListeners[pubStr] = append(
×
3793
                                s.peerConnectedListeners[pubStr], peerChan,
×
3794
                        )
×
3795
                        s.mu.Unlock()
×
3796
                        return
×
3797
                }
3798

3799
                // Connected, can return early.
3800
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3801

3✔
3802
                select {
3✔
3803
                case peerChan <- peer:
3✔
3804
                case <-s.quit:
1✔
3805
                }
3806

3807
                return
3✔
3808
        }
3809

3810
        // Not connected, store this listener such that it can be notified when
3811
        // the peer comes online.
3812
        s.peerConnectedListeners[pubStr] = append(
3✔
3813
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3814
        )
3✔
3815
        s.mu.Unlock()
3✔
3816
}
3817

3818
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3819
// the given public key has been disconnected. The notification is signaled by
3820
// closing the channel returned.
3821
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3822
        s.mu.Lock()
3✔
3823
        defer s.mu.Unlock()
3✔
3824

3✔
3825
        c := make(chan struct{})
3✔
3826

3✔
3827
        // If the peer is already offline, we can immediately trigger the
3✔
3828
        // notification.
3✔
3829
        peerPubKeyStr := string(peerPubKey[:])
3✔
3830
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3831
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3832
                close(c)
×
3833
                return c
×
3834
        }
×
3835

3836
        // Otherwise, the peer is online, so we'll keep track of the channel to
3837
        // trigger the notification once the server detects the peer
3838
        // disconnects.
3839
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3840
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3841
        )
3✔
3842

3✔
3843
        return c
3✔
3844
}
3845

3846
// FindPeer will return the peer that corresponds to the passed in public key.
3847
// This function is used by the funding manager, allowing it to update the
3848
// daemon's local representation of the remote peer.
3849
//
3850
// NOTE: This function is safe for concurrent access.
3851
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3852
        s.mu.RLock()
3✔
3853
        defer s.mu.RUnlock()
3✔
3854

3✔
3855
        pubStr := string(peerKey.SerializeCompressed())
3✔
3856

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

3860
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3861
// which should be a string representation of the peer's serialized, compressed
3862
// public key.
3863
//
3864
// NOTE: This function is safe for concurrent access.
3865
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3866
        s.mu.RLock()
3✔
3867
        defer s.mu.RUnlock()
3✔
3868

3✔
3869
        return s.findPeerByPubStr(pubStr)
3✔
3870
}
3✔
3871

3872
// findPeerByPubStr is an internal method that retrieves the specified peer from
3873
// the server's internal state using.
3874
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3875
        peer, ok := s.peersByPub[pubStr]
3✔
3876
        if !ok {
6✔
3877
                return nil, ErrPeerNotConnected
3✔
3878
        }
3✔
3879

3880
        return peer, nil
3✔
3881
}
3882

3883
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3884
// exponential backoff. If no previous backoff was known, the default is
3885
// returned.
3886
func (s *server) nextPeerBackoff(pubStr string,
3887
        startTime time.Time) time.Duration {
3✔
3888

3✔
3889
        // Now, determine the appropriate backoff to use for the retry.
3✔
3890
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3891
        if !ok {
6✔
3892
                // If an existing backoff was unknown, use the default.
3✔
3893
                return s.cfg.MinBackoff
3✔
3894
        }
3✔
3895

3896
        // If the peer failed to start properly, we'll just use the previous
3897
        // backoff to compute the subsequent randomized exponential backoff
3898
        // duration. This will roughly double on average.
3899
        if startTime.IsZero() {
3✔
3900
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3901
        }
×
3902

3903
        // The peer succeeded in starting. If the connection didn't last long
3904
        // enough to be considered stable, we'll continue to back off retries
3905
        // with this peer.
3906
        connDuration := time.Since(startTime)
3✔
3907
        if connDuration < defaultStableConnDuration {
6✔
3908
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3909
        }
3✔
3910

3911
        // The peer succeed in starting and this was stable peer, so we'll
3912
        // reduce the timeout duration by the length of the connection after
3913
        // applying randomized exponential backoff. We'll only apply this in the
3914
        // case that:
3915
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3916
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3917
        if relaxedBackoff > s.cfg.MinBackoff {
×
3918
                return relaxedBackoff
×
3919
        }
×
3920

3921
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3922
        // the stable connection lasted much longer than our previous backoff.
3923
        // To reward such good behavior, we'll reconnect after the default
3924
        // timeout.
3925
        return s.cfg.MinBackoff
×
3926
}
3927

3928
// shouldDropLocalConnection determines if our local connection to a remote peer
3929
// should be dropped in the case of concurrent connection establishment. In
3930
// order to deterministically decide which connection should be dropped, we'll
3931
// utilize the ordering of the local and remote public key. If we didn't use
3932
// such a tie breaker, then we risk _both_ connections erroneously being
3933
// dropped.
3934
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3935
        localPubBytes := local.SerializeCompressed()
×
3936
        remotePubPbytes := remote.SerializeCompressed()
×
3937

×
3938
        // The connection that comes from the node with a "smaller" pubkey
×
3939
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3940
        // should drop our established connection.
×
3941
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3942
}
×
3943

3944
// InboundPeerConnected initializes a new peer in response to a new inbound
3945
// connection.
3946
//
3947
// NOTE: This function is safe for concurrent access.
3948
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3949
        // Exit early if we have already been instructed to shutdown, this
3✔
3950
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3951
        if s.Stopped() {
3✔
3952
                return
×
3953
        }
×
3954

3955
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3956
        pubSer := nodePub.SerializeCompressed()
3✔
3957
        pubStr := string(pubSer)
3✔
3958

3✔
3959
        var pubBytes [33]byte
3✔
3960
        copy(pubBytes[:], pubSer)
3✔
3961

3✔
3962
        s.mu.Lock()
3✔
3963
        defer s.mu.Unlock()
3✔
3964

3✔
3965
        // If we already have an outbound connection to this peer, then ignore
3✔
3966
        // this new connection.
3✔
3967
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3968
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3969
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3970
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3971

3✔
3972
                conn.Close()
3✔
3973
                return
3✔
3974
        }
3✔
3975

3976
        // If we already have a valid connection that is scheduled to take
3977
        // precedence once the prior peer has finished disconnecting, we'll
3978
        // ignore this connection.
3979
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3980
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3981
                        "scheduled", conn.RemoteAddr(), p)
×
3982
                conn.Close()
×
3983
                return
×
3984
        }
×
3985

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

3✔
3988
        // Check to see if we already have a connection with this peer. If so,
3✔
3989
        // we may need to drop our existing connection. This prevents us from
3✔
3990
        // having duplicate connections to the same peer. We forgo adding a
3✔
3991
        // default case as we expect these to be the only error values returned
3✔
3992
        // from findPeerByPubStr.
3✔
3993
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3994
        switch err {
3✔
3995
        case ErrPeerNotConnected:
3✔
3996
                // We were unable to locate an existing connection with the
3✔
3997
                // target peer, proceed to connect.
3✔
3998
                s.cancelConnReqs(pubStr, nil)
3✔
3999
                s.peerConnected(conn, nil, true)
3✔
4000

4001
        case nil:
3✔
4002
                ctx := btclog.WithCtx(
3✔
4003
                        context.TODO(),
3✔
4004
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4005
                )
3✔
4006

3✔
4007
                // We already have a connection with the incoming peer. If the
3✔
4008
                // connection we've already established should be kept and is
3✔
4009
                // not of the same type of the new connection (inbound), then
3✔
4010
                // we'll close out the new connection s.t there's only a single
3✔
4011
                // connection between us.
3✔
4012
                localPub := s.identityECDH.PubKey()
3✔
4013
                if !connectedPeer.Inbound() &&
3✔
4014
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4015

×
4016
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4017
                                "peer, but already have outbound "+
×
4018
                                "connection, dropping conn",
×
4019
                                fmt.Errorf("already have outbound conn"))
×
4020
                        conn.Close()
×
4021
                        return
×
4022
                }
×
4023

4024
                // Otherwise, if we should drop the connection, then we'll
4025
                // disconnect our already connected peer.
4026
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4027

3✔
4028
                s.cancelConnReqs(pubStr, nil)
3✔
4029

3✔
4030
                // Remove the current peer from the server's internal state and
3✔
4031
                // signal that the peer termination watcher does not need to
3✔
4032
                // execute for this peer.
3✔
4033
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4034
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4035
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4036
                        s.peerConnected(conn, nil, true)
3✔
4037
                }
3✔
4038
        }
4039
}
4040

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

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

3✔
4055
        var pubBytes [33]byte
3✔
4056
        copy(pubBytes[:], pubSer)
3✔
4057

3✔
4058
        s.mu.Lock()
3✔
4059
        defer s.mu.Unlock()
3✔
4060

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

3✔
4068
                if connReq != nil {
6✔
4069
                        s.connMgr.Remove(connReq.ID())
3✔
4070
                }
3✔
4071
                conn.Close()
3✔
4072
                return
3✔
4073
        }
4074
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4075
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4076
                s.connMgr.Remove(connReq.ID())
×
4077
                conn.Close()
×
4078
                return
×
4079
        }
×
4080

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

×
4087
                if connReq != nil {
×
4088
                        s.connMgr.Remove(connReq.ID())
×
4089
                }
×
4090

4091
                conn.Close()
×
4092
                return
×
4093
        }
4094

4095
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4096
                conn.RemoteAddr())
3✔
4097

3✔
4098
        if connReq != nil {
6✔
4099
                // A successful connection was returned by the connmgr.
3✔
4100
                // Immediately cancel all pending requests, excluding the
3✔
4101
                // outbound connection we just established.
3✔
4102
                ignore := connReq.ID()
3✔
4103
                s.cancelConnReqs(pubStr, &ignore)
3✔
4104
        } else {
6✔
4105
                // This was a successful connection made by some other
3✔
4106
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4107
                s.cancelConnReqs(pubStr, nil)
3✔
4108
        }
3✔
4109

4110
        // If we already have a connection with this peer, decide whether or not
4111
        // we need to drop the stale connection. We forgo adding a default case
4112
        // as we expect these to be the only error values returned from
4113
        // findPeerByPubStr.
4114
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4115
        switch err {
3✔
4116
        case ErrPeerNotConnected:
3✔
4117
                // We were unable to locate an existing connection with the
3✔
4118
                // target peer, proceed to connect.
3✔
4119
                s.peerConnected(conn, connReq, false)
3✔
4120

4121
        case nil:
3✔
4122
                ctx := btclog.WithCtx(
3✔
4123
                        context.TODO(),
3✔
4124
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4125
                )
3✔
4126

3✔
4127
                // We already have a connection with the incoming peer. If the
3✔
4128
                // connection we've already established should be kept and is
3✔
4129
                // not of the same type of the new connection (outbound), then
3✔
4130
                // we'll close out the new connection s.t there's only a single
3✔
4131
                // connection between us.
3✔
4132
                localPub := s.identityECDH.PubKey()
3✔
4133
                if connectedPeer.Inbound() &&
3✔
4134
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4135

×
4136
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4137
                                "to peer, but already have inbound "+
×
4138
                                "connection, dropping conn",
×
4139
                                fmt.Errorf("already have inbound conn"))
×
4140
                        if connReq != nil {
×
4141
                                s.connMgr.Remove(connReq.ID())
×
4142
                        }
×
4143
                        conn.Close()
×
4144
                        return
×
4145
                }
4146

4147
                // Otherwise, _their_ connection should be dropped. So we'll
4148
                // disconnect the peer and send the now obsolete peer to the
4149
                // server for garbage collection.
4150
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4151

3✔
4152
                // Remove the current peer from the server's internal state and
3✔
4153
                // signal that the peer termination watcher does not need to
3✔
4154
                // execute for this peer.
3✔
4155
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4156
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4157
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4158
                        s.peerConnected(conn, connReq, false)
3✔
4159
                }
3✔
4160
        }
4161
}
4162

4163
// UnassignedConnID is the default connection ID that a request can have before
4164
// it actually is submitted to the connmgr.
4165
// TODO(conner): move into connmgr package, or better, add connmgr method for
4166
// generating atomic IDs
4167
const UnassignedConnID uint64 = 0
4168

4169
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4170
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4171
// Afterwards, each connection request removed from the connmgr. The caller can
4172
// optionally specify a connection ID to ignore, which prevents us from
4173
// canceling a successful request. All persistent connreqs for the provided
4174
// pubkey are discarded after the operationjw.
4175
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4176
        // First, cancel any lingering persistent retry attempts, which will
3✔
4177
        // prevent retries for any with backoffs that are still maturing.
3✔
4178
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4179
                close(cancelChan)
3✔
4180
                delete(s.persistentRetryCancels, pubStr)
3✔
4181
        }
3✔
4182

4183
        // Next, check to see if we have any outstanding persistent connection
4184
        // requests to this peer. If so, then we'll remove all of these
4185
        // connection requests, and also delete the entry from the map.
4186
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4187
        if !ok {
6✔
4188
                return
3✔
4189
        }
3✔
4190

4191
        for _, connReq := range connReqs {
6✔
4192
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4193

3✔
4194
                // Atomically capture the current request identifier.
3✔
4195
                connID := connReq.ID()
3✔
4196

3✔
4197
                // Skip any zero IDs, this indicates the request has not
3✔
4198
                // yet been schedule.
3✔
4199
                if connID == UnassignedConnID {
3✔
4200
                        continue
×
4201
                }
4202

4203
                // Skip a particular connection ID if instructed.
4204
                if skip != nil && connID == *skip {
6✔
4205
                        continue
3✔
4206
                }
4207

4208
                s.connMgr.Remove(connID)
3✔
4209
        }
4210

4211
        delete(s.persistentConnReqs, pubStr)
3✔
4212
}
4213

4214
// handleCustomMessage dispatches an incoming custom peers message to
4215
// subscribers.
4216
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4217
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4218
                peer, msg.Type)
3✔
4219

3✔
4220
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4221
                Peer: peer,
3✔
4222
                Msg:  msg,
3✔
4223
        })
3✔
4224
}
3✔
4225

4226
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4227
// messages.
4228
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4229
        return s.customMessageServer.Subscribe()
3✔
4230
}
3✔
4231

4232
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4233
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4234
        return s.onionMessageServer.Subscribe()
3✔
4235
}
3✔
4236

4237
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4238
// the channelNotifier's NotifyOpenChannelEvent.
4239
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4240
        remotePub *btcec.PublicKey) {
3✔
4241

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

4248
        // Notify subscribers about this open channel event.
4249
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4250
}
4251

4252
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4253
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4254
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4255
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4256

3✔
4257
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4258
        // peer.
3✔
4259
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4260
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4261
                        "channel[%v] pending open",
×
4262
                        remotePub.SerializeCompressed(), op)
×
4263
        }
×
4264

4265
        // Notify subscribers about this event.
4266
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4267
}
4268

4269
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4270
// calls the channelNotifier's NotifyFundingTimeout.
4271
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4272
        remotePub *btcec.PublicKey) {
3✔
4273

3✔
4274
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4275
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4276
        if err != nil {
3✔
4277
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4278
                        "channel[%v] pending close",
×
4279
                        remotePub.SerializeCompressed(), op)
×
4280
        }
×
4281

4282
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4283
                // If we encounter an error while attempting to disconnect the
×
4284
                // peer, log the error.
×
4285
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4286
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4287
                }
×
4288
        }
4289

4290
        // Notify subscribers about this event.
4291
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4292
}
4293

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

3✔
4301
        brontideConn := conn.(*brontide.Conn)
3✔
4302
        addr := conn.RemoteAddr()
3✔
4303
        pubKey := brontideConn.RemotePub()
3✔
4304

3✔
4305
        // Only restrict access for inbound connections, which means if the
3✔
4306
        // remote node's public key is banned or the restricted slots are used
3✔
4307
        // up, we will drop the connection.
3✔
4308
        //
3✔
4309
        // TODO(yy): Consider perform this check in
3✔
4310
        // `peerAccessMan.addPeerAccess`.
3✔
4311
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4312
        if inbound && err != nil {
3✔
4313
                pubSer := pubKey.SerializeCompressed()
×
4314

×
4315
                // Clean up the persistent peer maps if we're dropping this
×
4316
                // connection.
×
4317
                s.bannedPersistentPeerConnection(string(pubSer))
×
4318

×
4319
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4320
                        "of restricted-access connection slots: %v.", pubSer,
×
4321
                        err)
×
4322

×
4323
                conn.Close()
×
4324

×
4325
                return
×
4326
        }
×
4327

4328
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4329
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4330

3✔
4331
        peerAddr := &lnwire.NetAddress{
3✔
4332
                IdentityKey: pubKey,
3✔
4333
                Address:     addr,
3✔
4334
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4335
        }
3✔
4336

3✔
4337
        // With the brontide connection established, we'll now craft the feature
3✔
4338
        // vectors to advertise to the remote node.
3✔
4339
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4340
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4341

3✔
4342
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4343
        // found, create a fresh buffer.
3✔
4344
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4345
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4346
        if !ok {
6✔
4347
                var err error
3✔
4348
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4349
                if err != nil {
3✔
4350
                        srvrLog.Errorf("unable to create peer %v", err)
×
4351
                        return
×
4352
                }
×
4353
        }
4354

4355
        // If we directly set the peer.Config TowerClient member to the
4356
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4357
        // the peer.Config's TowerClient member will not evaluate to nil even
4358
        // though the underlying value is nil. To avoid this gotcha which can
4359
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4360
        // TowerClient if needed.
4361
        var towerClient wtclient.ClientManager
3✔
4362
        if s.towerClientMgr != nil {
6✔
4363
                towerClient = s.towerClientMgr
3✔
4364
        }
3✔
4365

4366
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4367
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4368

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

3✔
4413
                        return s.genNodeAnnouncement(nil)
3✔
4414
                },
3✔
4415

4416
                PongBuf: s.pongBuf,
4417

4418
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4419

4420
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4421

4422
                FundingManager: s.fundingMgr,
4423

4424
                Hodl:                    s.cfg.Hodl,
4425
                UnsafeReplay:            s.cfg.UnsafeReplay,
4426
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4427
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4428
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4429
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4430
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4431
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4432
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4433
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4434
                HandleCustomMessage:    s.handleCustomMessage,
4435
                GetAliases:             s.aliasMgr.GetAliases,
4436
                RequestAlias:           s.aliasMgr.RequestAlias,
4437
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4438
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4439
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4440
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4441
                MaxFeeExposure:         thresholdMSats,
4442
                Quit:                   s.quit,
4443
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4444
                AuxSigner:              s.implCfg.AuxSigner,
4445
                MsgRouter:              s.implCfg.MsgRouter,
4446
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4447
                AuxResolver:            s.implCfg.AuxContractResolver,
4448
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4449
                ShouldFwdExpEndorsement: func() bool {
3✔
4450
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4451
                                return false
3✔
4452
                        }
3✔
4453

4454
                        return clock.NewDefaultClock().Now().Before(
3✔
4455
                                EndorsementExperimentEnd,
3✔
4456
                        )
3✔
4457
                },
4458
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4459
        }
4460

4461
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4462
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4463

3✔
4464
        p := peer.NewBrontide(pCfg)
3✔
4465

3✔
4466
        // Update the access manager with the access permission for this peer.
3✔
4467
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4468

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

3✔
4472
        s.addPeer(p)
3✔
4473

3✔
4474
        // Once we have successfully added the peer to the server, we can
3✔
4475
        // delete the previous error buffer from the server's map of error
3✔
4476
        // buffers.
3✔
4477
        delete(s.peerErrors, pkStr)
3✔
4478

3✔
4479
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4480
        // includes sending and receiving Init messages, which would be a DOS
3✔
4481
        // vector if we held the server's mutex throughout the procedure.
3✔
4482
        s.wg.Add(1)
3✔
4483
        go s.peerInitializer(p)
3✔
4484
}
4485

4486
// addPeer adds the passed peer to the server's global state of all active
4487
// peers.
4488
func (s *server) addPeer(p *peer.Brontide) {
3✔
4489
        if p == nil {
3✔
4490
                return
×
4491
        }
×
4492

4493
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4494

3✔
4495
        // Ignore new peers if we're shutting down.
3✔
4496
        if s.Stopped() {
3✔
4497
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4498
                        pubBytes)
×
4499
                p.Disconnect(ErrServerShuttingDown)
×
4500

×
4501
                return
×
4502
        }
×
4503

4504
        // Track the new peer in our indexes so we can quickly look it up either
4505
        // according to its public key, or its peer ID.
4506
        // TODO(roasbeef): pipe all requests through to the
4507
        // queryHandler/peerManager
4508

4509
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4510
        // be human-readable.
4511
        pubStr := string(pubBytes)
3✔
4512

3✔
4513
        s.peersByPub[pubStr] = p
3✔
4514

3✔
4515
        if p.Inbound() {
6✔
4516
                s.inboundPeers[pubStr] = p
3✔
4517
        } else {
6✔
4518
                s.outboundPeers[pubStr] = p
3✔
4519
        }
3✔
4520

4521
        // Inform the peer notifier of a peer online event so that it can be reported
4522
        // to clients listening for peer events.
4523
        var pubKey [33]byte
3✔
4524
        copy(pubKey[:], pubBytes)
3✔
4525
}
4526

4527
// peerInitializer asynchronously starts a newly connected peer after it has
4528
// been added to the server's peer map. This method sets up a
4529
// peerTerminationWatcher for the given peer, and ensures that it executes even
4530
// if the peer failed to start. In the event of a successful connection, this
4531
// method reads the negotiated, local feature-bits and spawns the appropriate
4532
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4533
// be signaled of the new peer once the method returns.
4534
//
4535
// NOTE: This MUST be launched as a goroutine.
4536
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4537
        defer s.wg.Done()
3✔
4538

3✔
4539
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4540

3✔
4541
        // Avoid initializing peers while the server is exiting.
3✔
4542
        if s.Stopped() {
3✔
4543
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4544
                        pubBytes)
×
4545
                return
×
4546
        }
×
4547

4548
        // Create a channel that will be used to signal a successful start of
4549
        // the link. This prevents the peer termination watcher from beginning
4550
        // its duty too early.
4551
        ready := make(chan struct{})
3✔
4552

3✔
4553
        // Before starting the peer, launch a goroutine to watch for the
3✔
4554
        // unexpected termination of this peer, which will ensure all resources
3✔
4555
        // are properly cleaned up, and re-establish persistent connections when
3✔
4556
        // necessary. The peer termination watcher will be short circuited if
3✔
4557
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4558
        // that the server has already handled the removal of this peer.
3✔
4559
        s.wg.Add(1)
3✔
4560
        go s.peerTerminationWatcher(p, ready)
3✔
4561

3✔
4562
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4563
        // will unblock the peerTerminationWatcher.
3✔
4564
        if err := p.Start(); err != nil {
6✔
4565
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4566

3✔
4567
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4568
                return
3✔
4569
        }
3✔
4570

4571
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4572
        // was successful, and to begin watching the peer's wait group.
4573
        close(ready)
3✔
4574

3✔
4575
        s.mu.Lock()
3✔
4576
        defer s.mu.Unlock()
3✔
4577

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

3✔
4581
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4582
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4583
        pubStr := string(pubBytes)
3✔
4584
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4585
                select {
3✔
4586
                case peerChan <- p:
3✔
4587
                case <-s.quit:
×
4588
                        return
×
4589
                }
4590
        }
4591
        delete(s.peerConnectedListeners, pubStr)
3✔
4592

3✔
4593
        // Since the peer has been fully initialized, now it's time to notify
3✔
4594
        // the RPC about the peer online event.
3✔
4595
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4596
}
4597

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

3✔
4612
        ctx := btclog.WithCtx(
3✔
4613
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4614
        )
3✔
4615

3✔
4616
        p.WaitForDisconnect(ready)
3✔
4617

3✔
4618
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4619

3✔
4620
        // If the server is exiting then we can bail out early ourselves as all
3✔
4621
        // the other sub-systems will already be shutting down.
3✔
4622
        if s.Stopped() {
6✔
4623
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4624
                return
3✔
4625
        }
3✔
4626

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

3✔
4633
        pubKey := p.IdentityKey()
3✔
4634

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

3✔
4639
        // Tell the switch to remove all links associated with this peer.
3✔
4640
        // Passing nil as the target link indicates that all links associated
3✔
4641
        // with this interface should be closed.
3✔
4642
        //
3✔
4643
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4644
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4645
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4646
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4647
        }
×
4648

4649
        for _, link := range links {
6✔
4650
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4651
        }
3✔
4652

4653
        s.mu.Lock()
3✔
4654
        defer s.mu.Unlock()
3✔
4655

3✔
4656
        // If there were any notification requests for when this peer
3✔
4657
        // disconnected, we can trigger them now.
3✔
4658
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4659
        pubStr := string(pubKey.SerializeCompressed())
3✔
4660
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4661
                close(offlineChan)
3✔
4662
        }
3✔
4663
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4664

3✔
4665
        // If the server has already removed this peer, we can short circuit the
3✔
4666
        // peer termination watcher and skip cleanup.
3✔
4667
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4668
                delete(s.ignorePeerTermination, p)
3✔
4669

3✔
4670
                pubKey := p.PubKey()
3✔
4671
                pubStr := string(pubKey[:])
3✔
4672

3✔
4673
                // If a connection callback is present, we'll go ahead and
3✔
4674
                // execute it now that previous peer has fully disconnected. If
3✔
4675
                // the callback is not present, this likely implies the peer was
3✔
4676
                // purposefully disconnected via RPC, and that no reconnect
3✔
4677
                // should be attempted.
3✔
4678
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4679
                if ok {
6✔
4680
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4681
                        connCallback()
3✔
4682
                }
3✔
4683
                return
3✔
4684
        }
4685

4686
        // First, cleanup any remaining state the server has regarding the peer
4687
        // in question.
4688
        s.removePeerUnsafe(ctx, p)
3✔
4689

3✔
4690
        // Next, check to see if this is a persistent peer or not.
3✔
4691
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4692
                return
3✔
4693
        }
3✔
4694

4695
        // Get the last address that we used to connect to the peer.
4696
        addrs := []net.Addr{
3✔
4697
                p.NetAddress().Address,
3✔
4698
        }
3✔
4699

3✔
4700
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4701
        // reconnection purposes.
3✔
4702
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4703
        switch {
3✔
4704
        // We found advertised addresses, so use them.
4705
        case err == nil:
3✔
4706
                addrs = advertisedAddrs
3✔
4707

4708
        // The peer doesn't have an advertised address.
4709
        case err == errNoAdvertisedAddr:
3✔
4710
                // If it is an outbound peer then we fall back to the existing
3✔
4711
                // peer address.
3✔
4712
                if !p.Inbound() {
6✔
4713
                        break
3✔
4714
                }
4715

4716
                // Fall back to the existing peer address if
4717
                // we're not accepting connections over Tor.
4718
                if s.torController == nil {
6✔
4719
                        break
3✔
4720
                }
4721

4722
                // If we are, the peer's address won't be known
4723
                // to us (we'll see a private address, which is
4724
                // the address used by our onion service to dial
4725
                // to lnd), so we don't have enough information
4726
                // to attempt a reconnect.
4727
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4728
                        "to inbound peer without advertised address")
×
4729
                return
×
4730

4731
        // We came across an error retrieving an advertised
4732
        // address, log it, and fall back to the existing peer
4733
        // address.
4734
        default:
3✔
4735
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4736
                        "address for peer", err)
3✔
4737
        }
4738

4739
        // Make an easy lookup map so that we can check if an address
4740
        // is already in the address list that we have stored for this peer.
4741
        existingAddrs := make(map[string]bool)
3✔
4742
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4743
                existingAddrs[addr.String()] = true
3✔
4744
        }
3✔
4745

4746
        // Add any missing addresses for this peer to persistentPeerAddr.
4747
        for _, addr := range addrs {
6✔
4748
                if existingAddrs[addr.String()] {
3✔
4749
                        continue
×
4750
                }
4751

4752
                s.persistentPeerAddrs[pubStr] = append(
3✔
4753
                        s.persistentPeerAddrs[pubStr],
3✔
4754
                        &lnwire.NetAddress{
3✔
4755
                                IdentityKey: p.IdentityKey(),
3✔
4756
                                Address:     addr,
3✔
4757
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4758
                        },
3✔
4759
                )
3✔
4760
        }
4761

4762
        // Record the computed backoff in the backoff map.
4763
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4764
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4765

3✔
4766
        // Initialize a retry canceller for this peer if one does not
3✔
4767
        // exist.
3✔
4768
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4769
        if !ok {
6✔
4770
                cancelChan = make(chan struct{})
3✔
4771
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4772
        }
3✔
4773

4774
        // We choose not to wait group this go routine since the Connect
4775
        // call can stall for arbitrarily long if we shutdown while an
4776
        // outbound connection attempt is being made.
4777
        go func() {
6✔
4778
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4779
                        "re-establishment to persistent peer",
3✔
4780
                        "reconnecting_in", backoff)
3✔
4781

3✔
4782
                select {
3✔
4783
                case <-time.After(backoff):
3✔
4784
                case <-cancelChan:
3✔
4785
                        return
3✔
4786
                case <-s.quit:
3✔
4787
                        return
3✔
4788
                }
4789

4790
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4791
                        "connection")
3✔
4792

3✔
4793
                s.connectToPersistentPeer(pubStr)
3✔
4794
        }()
4795
}
4796

4797
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4798
// to connect to the peer. It creates connection requests if there are
4799
// currently none for a given address and it removes old connection requests
4800
// if the associated address is no longer in the latest address list for the
4801
// peer.
4802
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4803
        s.mu.Lock()
3✔
4804
        defer s.mu.Unlock()
3✔
4805

3✔
4806
        // Create an easy lookup map of the addresses we have stored for the
3✔
4807
        // peer. We will remove entries from this map if we have existing
3✔
4808
        // connection requests for the associated address and then any leftover
3✔
4809
        // entries will indicate which addresses we should create new
3✔
4810
        // connection requests for.
3✔
4811
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4812
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4813
                addrMap[addr.String()] = addr
3✔
4814
        }
3✔
4815

4816
        // Go through each of the existing connection requests and
4817
        // check if they correspond to the latest set of addresses. If
4818
        // there is a connection requests that does not use one of the latest
4819
        // advertised addresses then remove that connection request.
4820
        var updatedConnReqs []*connmgr.ConnReq
3✔
4821
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4822
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4823

3✔
4824
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4825
                // If the existing connection request is using one of the
4826
                // latest advertised addresses for the peer then we add it to
4827
                // updatedConnReqs and remove the associated address from
4828
                // addrMap so that we don't recreate this connReq later on.
4829
                case true:
×
4830
                        updatedConnReqs = append(
×
4831
                                updatedConnReqs, connReq,
×
4832
                        )
×
4833
                        delete(addrMap, lnAddr)
×
4834

4835
                // If the existing connection request is using an address that
4836
                // is not one of the latest advertised addresses for the peer
4837
                // then we remove the connecting request from the connection
4838
                // manager.
4839
                case false:
3✔
4840
                        srvrLog.Info(
3✔
4841
                                "Removing conn req:", connReq.Addr.String(),
3✔
4842
                        )
3✔
4843
                        s.connMgr.Remove(connReq.ID())
3✔
4844
                }
4845
        }
4846

4847
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4848

3✔
4849
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4850
        if !ok {
6✔
4851
                cancelChan = make(chan struct{})
3✔
4852
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4853
        }
3✔
4854

4855
        // Any addresses left in addrMap are new ones that we have not made
4856
        // connection requests for. So create new connection requests for those.
4857
        // If there is more than one address in the address map, stagger the
4858
        // creation of the connection requests for those.
4859
        go func() {
6✔
4860
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4861
                defer ticker.Stop()
3✔
4862

3✔
4863
                for _, addr := range addrMap {
6✔
4864
                        // Send the persistent connection request to the
3✔
4865
                        // connection manager, saving the request itself so we
3✔
4866
                        // can cancel/restart the process as needed.
3✔
4867
                        connReq := &connmgr.ConnReq{
3✔
4868
                                Addr:      addr,
3✔
4869
                                Permanent: true,
3✔
4870
                        }
3✔
4871

3✔
4872
                        s.mu.Lock()
3✔
4873
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4874
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4875
                        )
3✔
4876
                        s.mu.Unlock()
3✔
4877

3✔
4878
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4879
                                "channel peer %v", addr)
3✔
4880

3✔
4881
                        go s.connMgr.Connect(connReq)
3✔
4882

3✔
4883
                        select {
3✔
4884
                        case <-s.quit:
3✔
4885
                                return
3✔
4886
                        case <-cancelChan:
3✔
4887
                                return
3✔
4888
                        case <-ticker.C:
3✔
4889
                        }
4890
                }
4891
        }()
4892
}
4893

4894
// removePeerUnsafe removes the passed peer from the server's state of all
4895
// active peers.
4896
//
4897
// NOTE: Server mutex must be held when calling this function.
4898
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4899
        if p == nil {
3✔
4900
                return
×
4901
        }
×
4902

4903
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4904

3✔
4905
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4906
        // will be disconnected in the server shutdown process.
3✔
4907
        if s.Stopped() {
3✔
4908
                return
×
4909
        }
×
4910

4911
        // Capture the peer's public key and string representation.
4912
        pKey := p.PubKey()
3✔
4913
        pubSer := pKey[:]
3✔
4914
        pubStr := string(pubSer)
3✔
4915

3✔
4916
        delete(s.peersByPub, pubStr)
3✔
4917

3✔
4918
        if p.Inbound() {
6✔
4919
                delete(s.inboundPeers, pubStr)
3✔
4920
        } else {
6✔
4921
                delete(s.outboundPeers, pubStr)
3✔
4922
        }
3✔
4923

4924
        // When removing the peer we make sure to disconnect it asynchronously
4925
        // to avoid blocking the main server goroutine because it is holding the
4926
        // server's mutex. Disconnecting the peer might block and wait until the
4927
        // peer has fully started up. This can happen if an inbound and outbound
4928
        // race condition occurs.
4929
        s.wg.Add(1)
3✔
4930
        go func() {
6✔
4931
                defer s.wg.Done()
3✔
4932

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

3✔
4935
                // If this peer had an active persistent connection request,
3✔
4936
                // remove it.
3✔
4937
                if p.ConnReq() != nil {
6✔
4938
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4939
                }
3✔
4940

4941
                // Remove the peer's access permission from the access manager.
4942
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4943
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4944

3✔
4945
                // Copy the peer's error buffer across to the server if it has
3✔
4946
                // any items in it so that we can restore peer errors across
3✔
4947
                // connections. We need to look up the error after the peer has
3✔
4948
                // been disconnected because we write the error in the
3✔
4949
                // `Disconnect` method.
3✔
4950
                s.mu.Lock()
3✔
4951
                if p.ErrorBuffer().Total() > 0 {
6✔
4952
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4953
                }
3✔
4954
                s.mu.Unlock()
3✔
4955

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

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

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

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

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

3✔
4981
        // Ensure we're not already connected to this peer.
3✔
4982
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4983

3✔
4984
        // When there's no error it means we already have a connection with this
3✔
4985
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4986
        // set, we will ignore the existing connection and continue.
3✔
4987
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4988
                s.mu.Unlock()
3✔
4989
                return &errPeerAlreadyConnected{peer: peer}
3✔
4990
        }
3✔
4991

4992
        // Peer was not found, continue to pursue connection with peer.
4993

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

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

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

3✔
5025
                go s.connMgr.Connect(connReq)
3✔
5026

3✔
5027
                return nil
3✔
5028
        }
5029
        s.mu.Unlock()
3✔
5030

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

3✔
5038
        select {
3✔
5039
        case err := <-errChan:
3✔
5040
                return err
3✔
5041
        case <-s.quit:
×
5042
                return ErrServerShuttingDown
×
5043
        }
5044
}
5045

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

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

5064
        close(errChan)
3✔
5065

3✔
5066
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5067
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5068

3✔
5069
        s.OutboundPeerConnected(nil, conn)
3✔
5070
}
5071

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

3✔
5080
        s.mu.Lock()
3✔
5081
        defer s.mu.Unlock()
3✔
5082

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

5091
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5092

3✔
5093
        s.cancelConnReqs(pubStr, nil)
3✔
5094

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

3✔
5101
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5102
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5103
        //
3✔
5104
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5105
        // goroutine because we might hold the server's mutex.
3✔
5106
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5107

3✔
5108
        return nil
3✔
5109
}
5110

5111
// OpenChannel sends a request to the server to open a channel to the specified
5112
// peer identified by nodeKey with the passed channel funding parameters.
5113
//
5114
// NOTE: This function is safe for concurrent access.
5115
func (s *server) OpenChannel(
5116
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5117

3✔
5118
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5119
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5120
        // not blocked if the caller is not reading the updates.
3✔
5121
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5122
        req.Err = make(chan error, 1)
3✔
5123

3✔
5124
        // First attempt to locate the target peer to open a channel with, if
3✔
5125
        // we're unable to locate the peer then this request will fail.
3✔
5126
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5127
        s.mu.RLock()
3✔
5128
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5129
        if !ok {
3✔
5130
                s.mu.RUnlock()
×
5131

×
5132
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5133
                return req.Updates, req.Err
×
5134
        }
×
5135
        req.Peer = peer
3✔
5136
        s.mu.RUnlock()
3✔
5137

3✔
5138
        // We'll wait until the peer is active before beginning the channel
3✔
5139
        // opening process.
3✔
5140
        select {
3✔
5141
        case <-peer.ActiveSignal():
3✔
5142
        case <-peer.QuitSignal():
×
5143
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5144
                return req.Updates, req.Err
×
5145
        case <-s.quit:
×
5146
                req.Err <- ErrServerShuttingDown
×
5147
                return req.Updates, req.Err
×
5148
        }
5149

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

×
5158
                return req.Updates, req.Err
×
5159
        }
×
5160

5161
        // Spawn a goroutine to send the funding workflow request to the funding
5162
        // manager. This allows the server to continue handling queries instead
5163
        // of blocking on this request which is exported as a synchronous
5164
        // request to the outside world.
5165
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5166

3✔
5167
        return req.Updates, req.Err
3✔
5168
}
5169

5170
// Peers returns a slice of all active peers.
5171
//
5172
// NOTE: This function is safe for concurrent access.
5173
func (s *server) Peers() []*peer.Brontide {
3✔
5174
        s.mu.RLock()
3✔
5175
        defer s.mu.RUnlock()
3✔
5176

3✔
5177
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5178
        for _, peer := range s.peersByPub {
6✔
5179
                peers = append(peers, peer)
3✔
5180
        }
3✔
5181

5182
        return peers
3✔
5183
}
5184

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

5196
        // Using 1/10 of our duration as a margin, compute a random offset to
5197
        // avoid the nodes entering connection cycles.
5198
        margin := nextBackoff / 10
3✔
5199

3✔
5200
        var wiggle big.Int
3✔
5201
        wiggle.SetUint64(uint64(margin))
3✔
5202
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5203
                // Randomizing is not mission critical, so we'll just return the
×
5204
                // current backoff.
×
5205
                return nextBackoff
×
5206
        }
×
5207

5208
        // Otherwise add in our wiggle, but subtract out half of the margin so
5209
        // that the backoff can tweaked by 1/20 in either direction.
5210
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5211
}
5212

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

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

3✔
5221
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5222
        if err != nil {
3✔
5223
                return nil, err
×
5224
        }
×
5225

5226
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5227
        if err != nil {
6✔
5228
                return nil, err
3✔
5229
        }
3✔
5230

5231
        if len(node.Addresses) == 0 {
6✔
5232
                return nil, errNoAdvertisedAddr
3✔
5233
        }
3✔
5234

5235
        return node.Addresses, nil
3✔
5236
}
5237

5238
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5239
// channel update for a target channel.
5240
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5241
        *lnwire.ChannelUpdate1, error) {
3✔
5242

3✔
5243
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5244
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5245
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5246
                if err != nil {
6✔
5247
                        return nil, err
3✔
5248
                }
3✔
5249

5250
                return netann.ExtractChannelUpdate(
3✔
5251
                        ourPubKey[:], info, edge1, edge2,
3✔
5252
                )
3✔
5253
        }
5254
}
5255

5256
// applyChannelUpdate applies the channel update to the different sub-systems of
5257
// the server. The useAlias boolean denotes whether or not to send an alias in
5258
// place of the real SCID.
5259
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5260
        op *wire.OutPoint, useAlias bool) error {
3✔
5261

3✔
5262
        var (
3✔
5263
                peerAlias    *lnwire.ShortChannelID
3✔
5264
                defaultAlias lnwire.ShortChannelID
3✔
5265
        )
3✔
5266

3✔
5267
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5268

3✔
5269
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5270
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5271
        if useAlias {
6✔
5272
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5273
                if foundAlias != defaultAlias {
6✔
5274
                        peerAlias = &foundAlias
3✔
5275
                }
3✔
5276
        }
5277

5278
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5279
                update, discovery.RemoteAlias(peerAlias),
3✔
5280
        )
3✔
5281
        select {
3✔
5282
        case err := <-errChan:
3✔
5283
                return err
3✔
5284
        case <-s.quit:
×
5285
                return ErrServerShuttingDown
×
5286
        }
5287
}
5288

5289
// SendCustomMessage sends a custom message to the peer with the specified
5290
// pubkey.
5291
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5292
        data []byte) error {
3✔
5293

3✔
5294
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5295
        if err != nil {
6✔
5296
                return err
3✔
5297
        }
3✔
5298

5299
        // We'll wait until the peer is active.
5300
        select {
3✔
5301
        case <-peer.ActiveSignal():
3✔
5302
        case <-peer.QuitSignal():
×
5303
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5304
        case <-s.quit:
×
5305
                return ErrServerShuttingDown
×
5306
        }
5307

5308
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5309
        if err != nil {
6✔
5310
                return err
3✔
5311
        }
3✔
5312

5313
        // Send the message as low-priority. For now we assume that all
5314
        // application-defined message are low priority.
5315
        return peer.SendMessageLazy(true, msg)
3✔
5316
}
5317

5318
// SendOnionMessage sends a custom message to the peer with the specified
5319
// pubkey.
5320
// TODO(gijs): change this message to include path finding.
5321
func (s *server) SendOnionMessage(peerPub [33]byte,
5322
        blindingPoint *btcec.PublicKey, onion []byte) error {
3✔
5323

3✔
5324
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5325
        if err != nil {
3✔
NEW
5326
                return err
×
NEW
5327
        }
×
5328

5329
        // We'll wait until the peer is active.
5330
        select {
3✔
5331
        case <-peer.ActiveSignal():
3✔
NEW
5332
        case <-peer.QuitSignal():
×
NEW
5333
                return fmt.Errorf("peer %x disconnected", peerPub)
×
NEW
5334
        case <-s.quit:
×
NEW
5335
                return ErrServerShuttingDown
×
5336
        }
5337

5338
        msg := lnwire.NewOnionMessage(blindingPoint, onion)
3✔
5339

3✔
5340
        // Send the message as low-priority. For now we assume that all
3✔
5341
        // application-defined message are low priority.
3✔
5342
        return peer.SendMessageLazy(true, msg)
3✔
5343
}
5344

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

3✔
5353
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5354
                sweepAddr, err := wallet.NewAddress(
3✔
5355
                        lnwallet.TaprootPubkey, false,
3✔
5356
                        lnwallet.DefaultAccountName,
3✔
5357
                )
3✔
5358
                if err != nil {
3✔
5359
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5360
                }
×
5361

5362
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5363
                if err != nil {
3✔
5364
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5365
                }
×
5366

5367
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5368
                        wallet, netParams, addr,
3✔
5369
                )
3✔
5370
                if err != nil {
3✔
5371
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5372
                }
×
5373

5374
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5375
                        DeliveryAddress: addr,
3✔
5376
                        InternalKey:     internalKeyDesc,
3✔
5377
                })
3✔
5378
        }
5379
}
5380

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

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

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

5414
        for _, c := range pendings {
6✔
5415
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5416
                        continue
3✔
5417
                }
5418

5419
                // If the channel is still reported as pending, remove it from
5420
                // the map.
5421
                delete(closedSCIDs, c.ShortChannelID)
×
5422

×
5423
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5424
                        c.ShortChannelID)
×
5425
        }
5426

5427
        return closedSCIDs
3✔
5428
}
5429

5430
// getStartingBeat returns the current beat. This is used during the startup to
5431
// initialize blockbeat consumers.
5432
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5433
        // beat is the current blockbeat.
3✔
5434
        var beat *chainio.Beat
3✔
5435

3✔
5436
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5437
        // we will skip fetching the best block.
3✔
5438
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5439
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5440
                        "mode")
×
5441

×
5442
                return &chainio.Beat{}, nil
×
5443
        }
×
5444

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

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

3✔
5461
                // Update the current blockbeat.
3✔
5462
                beat = chainio.NewBeat(*bestBlock)
3✔
5463

5464
        case <-s.quit:
×
5465
                srvrLog.Debug("LND shutting down")
×
5466
        }
5467

5468
        return beat, nil
3✔
5469
}
5470

5471
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5472
// point has an active RBF chan closer.
5473
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5474
        chanPoint wire.OutPoint) bool {
3✔
5475

3✔
5476
        pubBytes := peerPub.SerializeCompressed()
3✔
5477

3✔
5478
        s.mu.RLock()
3✔
5479
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5480
        s.mu.RUnlock()
3✔
5481
        if !ok {
3✔
5482
                return false
×
5483
        }
×
5484

5485
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5486
}
5487

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

3✔
5496
        // First, we'll attempt to look up the channel based on it's
3✔
5497
        // ChannelPoint.
3✔
5498
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5499
        if err != nil {
3✔
5500
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5501
        }
×
5502

5503
        // From the channel, we can now get the pubkey of the peer, then use
5504
        // that to eventually get the chan closer.
5505
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5506

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

5516
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5517
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5518
        )
3✔
5519
        if err != nil {
3✔
5520
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5521
                        "%w", err)
×
5522
        }
×
5523

5524
        return closeUpdates, nil
3✔
5525
}
5526

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

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

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

5553
        return updates, nil
3✔
5554
}
5555

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

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

×
5579
                        listenPorts = append(listenPorts, uint16(port))
×
5580
                }
×
5581

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

5595
        // Normalize the external IP strings to net.Addr.
5596
        addrs, err := lncfg.NormalizeAddresses(
3✔
5597
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5598
                s.cfg.net.ResolveTCPAddr,
3✔
5599
        )
3✔
5600
        if err != nil {
3✔
5601
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5602
        }
×
5603

5604
        // To avoid having duplicate addresses, we'll only add addresses from
5605
        // the source node that are not already in our address list yet. We
5606
        // create this map for quick lookup.
5607
        addressMap := make(map[string]struct{}, len(addrs))
3✔
5608
        // Populate the map with the existing addresses.
3✔
5609
        for _, existingAddr := range addrs {
6✔
5610
                addressMap[existingAddr.String()] = struct{}{}
3✔
5611
        }
3✔
5612

5613
        // Parse the color from config. We will update this later if the config
5614
        // color is not changed from default (#3399FF) and we have a value in
5615
        // the source node.
5616
        color, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5617
        if err != nil {
3✔
5618
                return fmt.Errorf("unable to parse color: %w", err)
×
5619
        }
×
5620

5621
        var (
3✔
5622
                alias          = s.cfg.Alias
3✔
5623
                nodeLastUpdate = time.Now()
3✔
5624
        )
3✔
5625

3✔
5626
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5627
        switch {
3✔
5628
        case err == nil:
3✔
5629
                // If we have a source node persisted in the DB already, then we
3✔
5630
                // just need to make sure that the new LastUpdate time is at
3✔
5631
                // least one second after the last update time.
3✔
5632
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5633
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5634
                }
3✔
5635

5636
                // If the color is not changed from default, it means that we
5637
                // didn't specify a different color in the config. We'll use the
5638
                // source node's color.
5639
                if s.cfg.Color == defaultColor {
6✔
5640
                        color = srcNode.Color
3✔
5641
                }
3✔
5642

5643
                // If an alias is not specified in the config, we'll use the
5644
                // source node's alias.
5645
                if alias == "" {
6✔
5646
                        alias = srcNode.Alias
3✔
5647
                }
3✔
5648

5649
                // Append unique addresses from the source node to the address
5650
                // list.
5651
                for _, addr := range srcNode.Addresses {
6✔
5652
                        if _, found := addressMap[addr.String()]; !found {
6✔
5653
                                addrs = append(addrs, addr)
3✔
5654
                                addressMap[addr.String()] = struct{}{}
3✔
5655
                        }
3✔
5656
                }
5657

5658
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5659
                // If an alias is not specified in the config, we'll use the
3✔
5660
                // default, which is the first 10 bytes of the serialized
3✔
5661
                // pubkey.
3✔
5662
                if alias == "" {
6✔
5663
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5664
                }
3✔
5665

5666
        // If the above cases are not matched, then we have an unhandled non
5667
        // nil error.
5668
        default:
×
5669
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5670
        }
5671

5672
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5673
        if err != nil {
3✔
5674
                return err
×
5675
        }
×
5676

5677
        // TODO(abdulkbk): potentially find a way to use the source node's
5678
        // features in the self node.
5679
        selfNode := &models.LightningNode{
3✔
5680
                HaveNodeAnnouncement: true,
3✔
5681
                LastUpdate:           nodeLastUpdate,
3✔
5682
                Addresses:            addrs,
3✔
5683
                Alias:                nodeAlias.String(),
3✔
5684
                Color:                color,
3✔
5685
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
5686
        }
3✔
5687

3✔
5688
        copy(selfNode.PubKeyBytes[:], nodePub[:])
3✔
5689

3✔
5690
        // Based on the disk representation of the node announcement generated
3✔
5691
        // above, we'll generate a node announcement that can go out on the
3✔
5692
        // network so we can properly sign it.
3✔
5693
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5694
        if err != nil {
3✔
5695
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5696
        }
×
5697

5698
        // With the announcement generated, we'll sign it to properly
5699
        // authenticate the message on the network.
5700
        authSig, err := netann.SignAnnouncement(
3✔
5701
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5702
        )
3✔
5703
        if err != nil {
3✔
5704
                return fmt.Errorf("unable to generate signature for self node "+
×
5705
                        "announcement: %v", err)
×
5706
        }
×
5707

5708
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5709
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5710
                selfNode.AuthSigBytes,
3✔
5711
        )
3✔
5712
        if err != nil {
3✔
5713
                return err
×
5714
        }
×
5715

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

5722
        s.currentNodeAnn = nodeAnn
3✔
5723

3✔
5724
        return nil
3✔
5725
}
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