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

lightningnetwork / lnd / 19154714928

07 Nov 2025 12:59AM UTC coverage: 66.688% (-0.02%) from 66.712%
19154714928

Pull #10352

github

web-flow
Merge c165baeef into 096ab65b1
Pull Request #10352: [WIP] chainrpc: return Unavailable while notifier starts

137353 of 205965 relevant lines covered (66.69%)

21282.76 hits per line

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

69.34
/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.NodeAnnouncement1
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
        // txPublisher is a publisher with fee-bumping capability.
426
        txPublisher *sweep.TxPublisher
427

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

432
        // peerAccessMan implements peer access controls.
433
        peerAccessMan *accessMan
434

435
        quit chan struct{}
436

437
        wg sync.WaitGroup
438
}
439

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

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

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

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

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

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

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

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

495
                                        s.mu.Lock()
3✔
496

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

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

511
                                        s.mu.Unlock()
3✔
512

3✔
513
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
514
                                }
515
                        }
516
                }
517
        }()
518

519
        return nil
3✔
520
}
521

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

527
        // Msg is the custom wire message.
528
        Msg *lnwire.Custom
529
}
530

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

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

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

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

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

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

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

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

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

3✔
602
        netParams := cfg.ActiveNetParams.Params
3✔
603

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

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

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

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

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

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

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

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

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

3✔
674
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
675

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

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

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

3✔
702
                listenAddrs: listenAddrs,
3✔
703

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

3✔
708
                torController: torController,
3✔
709

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

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

3✔
726
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
727

3✔
728
                customMessageServer: subscribe.NewServer(),
3✔
729

3✔
730
                tlsManager: tlsManager,
3✔
731

3✔
732
                featureMgr: featureMgr,
3✔
733
                quit:       make(chan struct{}),
3✔
734
        }
3✔
735

3✔
736
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
737
        if err != nil {
3✔
738
                return nil, err
×
739
        }
×
740

741
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
742
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
743
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
744
        )
3✔
745
        s.invoices = invoices.NewRegistry(
3✔
746
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
747
        )
3✔
748

3✔
749
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
750

3✔
751
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
752
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
753

3✔
754
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
755
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
756
                if err != nil {
3✔
757
                        return err
×
758
                }
×
759

760
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
761

3✔
762
                return nil
3✔
763
        }
764

765
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
766
        if err != nil {
3✔
767
                return nil, err
×
768
        }
×
769

770
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
771
                DB:                   dbs.ChanStateDB,
3✔
772
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
773
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
774
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
775
                LocalChannelClose: func(pubKey []byte,
3✔
776
                        request *htlcswitch.ChanClose) {
6✔
777

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

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

822
        s.witnessBeacon = newPreimageBeacon(
3✔
823
                dbs.ChanStateDB.NewWitnessCache(),
3✔
824
                s.interceptableSwitch.ForwardPacket,
3✔
825
        )
3✔
826

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

3✔
840
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
841
        if err != nil {
3✔
842
                return nil, err
×
843
        }
×
844
        s.chanStatusMgr = chanStatusMgr
3✔
845

3✔
846
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
847
        // port forwarding for users behind a NAT.
3✔
848
        if cfg.NAT {
3✔
849
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
850

×
851
                discoveryTimeout := time.Duration(10 * time.Second)
×
852

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

×
867
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
868
                                "enabled device")
×
869

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

879
                        s.natTraversal = pmp
×
880
                }
881
        }
882

883
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
884
        // Set the self node which represents our node in the graph.
3✔
885
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
886
        if err != nil {
3✔
887
                return nil, err
×
888
        }
×
889

890
        // The router will get access to the payment ID sequencer, such that it
891
        // can generate unique payment IDs.
892
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
893
        if err != nil {
3✔
894
                return nil, err
×
895
        }
×
896

897
        // Instantiate mission control with config from the sub server.
898
        //
899
        // TODO(joostjager): When we are further in the process of moving to sub
900
        // servers, the mission control instance itself can be moved there too.
901
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
902

3✔
903
        // We only initialize a probability estimator if there's no custom one.
3✔
904
        var estimator routing.Estimator
3✔
905
        if cfg.Estimator != nil {
3✔
906
                estimator = cfg.Estimator
×
907
        } else {
3✔
908
                switch routingConfig.ProbabilityEstimatorType {
3✔
909
                case routing.AprioriEstimatorName:
3✔
910
                        aCfg := routingConfig.AprioriConfig
3✔
911
                        aprioriConfig := routing.AprioriConfig{
3✔
912
                                AprioriHopProbability: aCfg.HopProbability,
3✔
913
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
914
                                AprioriWeight:         aCfg.Weight,
3✔
915
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
916
                        }
3✔
917

3✔
918
                        estimator, err = routing.NewAprioriEstimator(
3✔
919
                                aprioriConfig,
3✔
920
                        )
3✔
921
                        if err != nil {
3✔
922
                                return nil, err
×
923
                        }
×
924

925
                case routing.BimodalEstimatorName:
×
926
                        bCfg := routingConfig.BimodalConfig
×
927
                        bimodalConfig := routing.BimodalConfig{
×
928
                                BimodalNodeWeight: bCfg.NodeWeight,
×
929
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
930
                                        bCfg.Scale,
×
931
                                ),
×
932
                                BimodalDecayTime: bCfg.DecayTime,
×
933
                        }
×
934

×
935
                        estimator, err = routing.NewBimodalEstimator(
×
936
                                bimodalConfig,
×
937
                        )
×
938
                        if err != nil {
×
939
                                return nil, err
×
940
                        }
×
941

942
                default:
×
943
                        return nil, fmt.Errorf("unknown estimator type %v",
×
944
                                routingConfig.ProbabilityEstimatorType)
×
945
                }
946
        }
947

948
        mcCfg := &routing.MissionControlConfig{
3✔
949
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
950
                Estimator:               estimator,
3✔
951
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
952
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
953
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
954
        }
3✔
955

3✔
956
        s.missionController, err = routing.NewMissionController(
3✔
957
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
958
        )
3✔
959
        if err != nil {
3✔
960
                return nil, fmt.Errorf("can't create mission control "+
×
961
                        "manager: %w", err)
×
962
        }
×
963
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
964
                routing.DefaultMissionControlNamespace,
3✔
965
        )
3✔
966
        if err != nil {
3✔
967
                return nil, fmt.Errorf("can't create mission control in the "+
×
968
                        "default namespace: %w", err)
×
969
        }
×
970

971
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
972
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
973
                int64(routingConfig.AttemptCost),
3✔
974
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
975
                routingConfig.MinRouteProbability)
3✔
976

3✔
977
        pathFindingConfig := routing.PathFindingConfig{
3✔
978
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
979
                        routingConfig.AttemptCost,
3✔
980
                ),
3✔
981
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
982
                MinProbability: routingConfig.MinRouteProbability,
3✔
983
        }
3✔
984

3✔
985
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
986
        if err != nil {
3✔
987
                return nil, fmt.Errorf("error getting source node: %w", err)
×
988
        }
×
989
        paymentSessionSource := &routing.SessionSource{
3✔
990
                GraphSessionFactory: dbs.GraphDB,
3✔
991
                SourceNode:          sourceNode,
3✔
992
                MissionControl:      s.defaultMC,
3✔
993
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
994
                PathFindingConfig:   pathFindingConfig,
3✔
995
        }
3✔
996

3✔
997
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
998

3✔
999
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1000
                cfg.Routing.StrictZombiePruning
3✔
1001

3✔
1002
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1003
                SelfNode:            nodePubKey,
3✔
1004
                Graph:               dbs.GraphDB,
3✔
1005
                Chain:               cc.ChainIO,
3✔
1006
                ChainView:           cc.ChainView,
3✔
1007
                Notifier:            cc.ChainNotifier,
3✔
1008
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1009
                GraphPruneInterval:  time.Hour,
3✔
1010
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1011
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1012
                StrictZombiePruning: strictPruning,
3✔
1013
                IsAlias:             aliasmgr.IsAlias,
3✔
1014
        })
3✔
1015
        if err != nil {
3✔
1016
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1017
        }
×
1018

1019
        s.chanRouter, err = routing.New(routing.Config{
3✔
1020
                SelfNode:           nodePubKey,
3✔
1021
                RoutingGraph:       dbs.GraphDB,
3✔
1022
                Chain:              cc.ChainIO,
3✔
1023
                Payer:              s.htlcSwitch,
3✔
1024
                Control:            s.controlTower,
3✔
1025
                MissionControl:     s.defaultMC,
3✔
1026
                SessionSource:      paymentSessionSource,
3✔
1027
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1028
                NextPaymentID:      sequencer.NextID,
3✔
1029
                PathFindingConfig:  pathFindingConfig,
3✔
1030
                Clock:              clock.NewDefaultClock(),
3✔
1031
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1032
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1033
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1034
        })
3✔
1035
        if err != nil {
3✔
1036
                return nil, fmt.Errorf("can't create router: %w", err)
×
1037
        }
×
1038

1039
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1040
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1041
        if err != nil {
3✔
1042
                return nil, err
×
1043
        }
×
1044
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1045
        if err != nil {
3✔
1046
                return nil, err
×
1047
        }
×
1048

1049
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1050

3✔
1051
        s.authGossiper = discovery.New(discovery.Config{
3✔
1052
                Graph:                 s.graphBuilder,
3✔
1053
                ChainIO:               s.cc.ChainIO,
3✔
1054
                Notifier:              s.cc.ChainNotifier,
3✔
1055
                ChainParams:           s.cfg.ActiveNetParams.Params,
3✔
1056
                Broadcast:             s.BroadcastMessage,
3✔
1057
                ChanSeries:            chanSeries,
3✔
1058
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1059
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1060
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1061
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
3✔
1062
                        error) {
3✔
1063

×
1064
                        return s.genNodeAnnouncement(nil)
×
1065
                },
×
1066
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1067
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1068
                RetransmitTicker:        ticker.New(time.Minute * 30),
1069
                RebroadcastInterval:     time.Hour * 24,
1070
                WaitingProofStore:       waitingProofStore,
1071
                MessageStore:            gossipMessageStore,
1072
                AnnSigner:               s.nodeSigner,
1073
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1074
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1075
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1076
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1077
                MinimumBatchSize:        10,
1078
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1079
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1080
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1081
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1082
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1083
                IsAlias:                 aliasmgr.IsAlias,
1084
                SignAliasUpdate:         s.signAliasUpdate,
1085
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1086
                GetAlias:                s.aliasMgr.GetPeerAlias,
1087
                FindChannel:             s.findChannel,
1088
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1089
                ScidCloser:              scidCloserMan,
1090
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1091
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1092
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1093
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1094
                BanThreshold:            cfg.Gossip.BanThreshold,
1095
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1096
        }, nodeKeyDesc)
1097

1098
        accessCfg := &accessManConfig{
3✔
1099
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1100
                        error) {
6✔
1101

3✔
1102
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1103
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1104
                                genesisHash[:],
3✔
1105
                        )
3✔
1106
                },
3✔
1107
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1108
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1109
        }
1110

1111
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1112
        if err != nil {
3✔
1113
                return nil, err
×
1114
        }
×
1115

1116
        s.peerAccessMan = peerAccessMan
3✔
1117

3✔
1118
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1119
        //nolint:ll
3✔
1120
        s.localChanMgr = &localchans.Manager{
3✔
1121
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1122
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1123
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1124
                        cb func(*models.ChannelEdgeInfo,
3✔
1125
                                *models.ChannelEdgePolicy) error,
3✔
1126
                        reset func()) error {
6✔
1127

3✔
1128
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1129
                                func(c *models.ChannelEdgeInfo,
3✔
1130
                                        e *models.ChannelEdgePolicy,
3✔
1131
                                        _ *models.ChannelEdgePolicy) error {
6✔
1132

3✔
1133
                                        // NOTE: The invoked callback here may
3✔
1134
                                        // receive a nil channel policy.
3✔
1135
                                        return cb(c, e)
3✔
1136
                                }, reset,
3✔
1137
                        )
1138
                },
1139
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1140
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1141
                FetchChannel:              s.chanStateDB.FetchChannel,
1142
                AddEdge: func(ctx context.Context,
1143
                        edge *models.ChannelEdgeInfo) error {
×
1144

×
1145
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1146
                },
×
1147
        }
1148

1149
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1150
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1151
        )
3✔
1152
        if err != nil {
3✔
1153
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1154
                return nil, err
×
1155
        }
×
1156

1157
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1158
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1159
        )
3✔
1160
        if err != nil {
3✔
1161
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1162
                return nil, err
×
1163
        }
×
1164

1165
        aggregator := sweep.NewBudgetAggregator(
3✔
1166
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1167
                s.implCfg.AuxSweeper,
3✔
1168
        )
3✔
1169

3✔
1170
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1171
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1172
                Wallet:     cc.Wallet,
3✔
1173
                Estimator:  cc.FeeEstimator,
3✔
1174
                Notifier:   cc.ChainNotifier,
3✔
1175
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1176
        })
3✔
1177

3✔
1178
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1179
                FeeEstimator: cc.FeeEstimator,
3✔
1180
                GenSweepScript: newSweepPkScriptGen(
3✔
1181
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1182
                ),
3✔
1183
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1184
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1185
                Mempool:              cc.MempoolNotifier,
3✔
1186
                Notifier:             cc.ChainNotifier,
3✔
1187
                Store:                sweeperStore,
3✔
1188
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1189
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1190
                Aggregator:           aggregator,
3✔
1191
                Publisher:            s.txPublisher,
3✔
1192
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1193
        })
3✔
1194

3✔
1195
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1196
                ChainIO:             cc.ChainIO,
3✔
1197
                ConfDepth:           1,
3✔
1198
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1199
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1200
                Notifier:            cc.ChainNotifier,
3✔
1201
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1202
                Store:               utxnStore,
3✔
1203
                SweepInput:          s.sweeper.SweepInput,
3✔
1204
                Budget:              s.cfg.Sweeper.Budget,
3✔
1205
        })
3✔
1206

3✔
1207
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1208
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1209
                closureType contractcourt.ChannelCloseType) {
6✔
1210
                // TODO(conner): Properly respect the update and error channels
3✔
1211
                // returned by CloseLink.
3✔
1212

3✔
1213
                // Instruct the switch to close the channel.  Provide no close out
3✔
1214
                // delivery script or target fee per kw because user input is not
3✔
1215
                // available when the remote peer closes the channel.
3✔
1216
                s.htlcSwitch.CloseLink(
3✔
1217
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1218
                )
3✔
1219
        }
3✔
1220

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

3✔
1225
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1226
                &contractcourt.BreachConfig{
3✔
1227
                        CloseLink: closeLink,
3✔
1228
                        DB:        s.chanStateDB,
3✔
1229
                        Estimator: s.cc.FeeEstimator,
3✔
1230
                        GenSweepScript: newSweepPkScriptGen(
3✔
1231
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1232
                        ),
3✔
1233
                        Notifier:           cc.ChainNotifier,
3✔
1234
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1235
                        ContractBreaches:   contractBreaches,
3✔
1236
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1237
                        Store: contractcourt.NewRetributionStore(
3✔
1238
                                dbs.ChanStateDB,
3✔
1239
                        ),
3✔
1240
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1241
                },
3✔
1242
        )
3✔
1243

3✔
1244
        //nolint:ll
3✔
1245
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1246
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1247
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1248
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1249
                NewSweepAddr: func() ([]byte, error) {
3✔
1250
                        addr, err := newSweepPkScriptGen(
×
1251
                                cc.Wallet, netParams,
×
1252
                        )().Unpack()
×
1253
                        if err != nil {
×
1254
                                return nil, err
×
1255
                        }
×
1256

1257
                        return addr.DeliveryAddress, nil
×
1258
                },
1259
                PublishTx: cc.Wallet.PublishTransaction,
1260
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1261
                        for _, msg := range msgs {
6✔
1262
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1263
                                if err != nil {
3✔
1264
                                        return err
×
1265
                                }
×
1266
                        }
1267
                        return nil
3✔
1268
                },
1269
                IncubateOutputs: func(chanPoint wire.OutPoint,
1270
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1271
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1272
                        broadcastHeight uint32,
1273
                        deadlineHeight fn.Option[int32]) error {
3✔
1274

3✔
1275
                        return s.utxoNursery.IncubateOutputs(
3✔
1276
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1277
                                broadcastHeight, deadlineHeight,
3✔
1278
                        )
3✔
1279
                },
3✔
1280
                PreimageDB:   s.witnessBeacon,
1281
                Notifier:     cc.ChainNotifier,
1282
                Mempool:      cc.MempoolNotifier,
1283
                Signer:       cc.Wallet.Cfg.Signer,
1284
                FeeEstimator: cc.FeeEstimator,
1285
                ChainIO:      cc.ChainIO,
1286
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1287
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1288
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1289
                        return nil
3✔
1290
                },
3✔
1291
                IsOurAddress: cc.Wallet.IsOurAddress,
1292
                ContractBreach: func(chanPoint wire.OutPoint,
1293
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1294

3✔
1295
                        // processACK will handle the BreachArbitrator ACKing
3✔
1296
                        // the event.
3✔
1297
                        finalErr := make(chan error, 1)
3✔
1298
                        processACK := func(brarErr error) {
6✔
1299
                                if brarErr != nil {
3✔
1300
                                        finalErr <- brarErr
×
1301
                                        return
×
1302
                                }
×
1303

1304
                                // If the BreachArbitrator successfully handled
1305
                                // the event, we can signal that the handoff
1306
                                // was successful.
1307
                                finalErr <- nil
3✔
1308
                        }
1309

1310
                        event := &contractcourt.ContractBreachEvent{
3✔
1311
                                ChanPoint:         chanPoint,
3✔
1312
                                ProcessACK:        processACK,
3✔
1313
                                BreachRetribution: breachRet,
3✔
1314
                        }
3✔
1315

3✔
1316
                        // Send the contract breach event to the
3✔
1317
                        // BreachArbitrator.
3✔
1318
                        select {
3✔
1319
                        case contractBreaches <- event:
3✔
1320
                        case <-s.quit:
×
1321
                                return ErrServerShuttingDown
×
1322
                        }
1323

1324
                        // We'll wait for a final error to be available from
1325
                        // the BreachArbitrator.
1326
                        select {
3✔
1327
                        case err := <-finalErr:
3✔
1328
                                return err
3✔
1329
                        case <-s.quit:
×
1330
                                return ErrServerShuttingDown
×
1331
                        }
1332
                },
1333
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1334
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1335
                },
3✔
1336
                Sweeper:                       s.sweeper,
1337
                Registry:                      s.invoices,
1338
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1339
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1340
                OnionProcessor:                s.sphinx,
1341
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1342
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1343
                Clock:                         clock.NewDefaultClock(),
1344
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1345
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1346
                HtlcNotifier:                  s.htlcNotifier,
1347
                Budget:                        *s.cfg.Sweeper.Budget,
1348

1349
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1350
                QueryIncomingCircuit: func(
1351
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1352

3✔
1353
                        // Get the circuit map.
3✔
1354
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1355

3✔
1356
                        // Lookup the outgoing circuit.
3✔
1357
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1358
                        if pc == nil {
5✔
1359
                                return nil
2✔
1360
                        }
2✔
1361

1362
                        return &pc.Incoming
3✔
1363
                },
1364
                AuxLeafStore: implCfg.AuxLeafStore,
1365
                AuxSigner:    implCfg.AuxSigner,
1366
                AuxResolver:  implCfg.AuxContractResolver,
1367
        }, dbs.ChanStateDB)
1368

1369
        // Select the configuration and funding parameters for Bitcoin.
1370
        chainCfg := cfg.Bitcoin
3✔
1371
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1372
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1373

3✔
1374
        var chanIDSeed [32]byte
3✔
1375
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1376
                return nil, err
×
1377
        }
×
1378

1379
        // Wrap the DeleteChannelEdges method so that the funding manager can
1380
        // use it without depending on several layers of indirection.
1381
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1382
                *models.ChannelEdgePolicy, error) {
6✔
1383

3✔
1384
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1385
                        scid.ToUint64(),
3✔
1386
                )
3✔
1387
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1388
                        // This is unlikely but there is a slim chance of this
×
1389
                        // being hit if lnd was killed via SIGKILL and the
×
1390
                        // funding manager was stepping through the delete
×
1391
                        // alias edge logic.
×
1392
                        return nil, nil
×
1393
                } else if err != nil {
3✔
1394
                        return nil, err
×
1395
                }
×
1396

1397
                // Grab our key to find our policy.
1398
                var ourKey [33]byte
3✔
1399
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1400

3✔
1401
                var ourPolicy *models.ChannelEdgePolicy
3✔
1402
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1403
                        ourPolicy = e1
3✔
1404
                } else {
6✔
1405
                        ourPolicy = e2
3✔
1406
                }
3✔
1407

1408
                if ourPolicy == nil {
3✔
1409
                        // Something is wrong, so return an error.
×
1410
                        return nil, fmt.Errorf("we don't have an edge")
×
1411
                }
×
1412

1413
                err = s.graphDB.DeleteChannelEdges(
3✔
1414
                        false, false, scid.ToUint64(),
3✔
1415
                )
3✔
1416
                return ourPolicy, err
3✔
1417
        }
1418

1419
        // For the reservationTimeout and the zombieSweeperInterval different
1420
        // values are set in case we are in a dev environment so enhance test
1421
        // capacilities.
1422
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1423
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1424

3✔
1425
        // Get the development config for funding manager. If we are not in
3✔
1426
        // development mode, this would be nil.
3✔
1427
        var devCfg *funding.DevConfig
3✔
1428
        if lncfg.IsDevBuild() {
6✔
1429
                devCfg = &funding.DevConfig{
3✔
1430
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1431
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1432
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1433
                }
3✔
1434

3✔
1435
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1436
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1437

3✔
1438
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1439
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1440
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1441
        }
3✔
1442

1443
        //nolint:ll
1444
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1445
                Dev:                devCfg,
3✔
1446
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1447
                IDKey:              nodeKeyDesc.PubKey,
3✔
1448
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1449
                Wallet:             cc.Wallet,
3✔
1450
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1451
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1452
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1453
                },
3✔
1454
                Notifier:     cc.ChainNotifier,
1455
                ChannelDB:    s.chanStateDB,
1456
                FeeEstimator: cc.FeeEstimator,
1457
                SignMessage:  cc.MsgSigner.SignMessage,
1458
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1459
                        error) {
3✔
1460

3✔
1461
                        return s.genNodeAnnouncement(nil)
3✔
1462
                },
3✔
1463
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1464
                NotifyWhenOnline:     s.NotifyWhenOnline,
1465
                TempChanIDSeed:       chanIDSeed,
1466
                FindChannel:          s.findChannel,
1467
                DefaultRoutingPolicy: cc.RoutingPolicy,
1468
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1469
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1470
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1471
                        // For large channels we increase the number
3✔
1472
                        // of confirmations we require for the
3✔
1473
                        // channel to be considered open. As it is
3✔
1474
                        // always the responder that gets to choose
3✔
1475
                        // value, the pushAmt is value being pushed
3✔
1476
                        // to us. This means we have more to lose
3✔
1477
                        // in the case this gets re-orged out, and
3✔
1478
                        // we will require more confirmations before
3✔
1479
                        // we consider it open.
3✔
1480

3✔
1481
                        // In case the user has explicitly specified
3✔
1482
                        // a default value for the number of
3✔
1483
                        // confirmations, we use it.
3✔
1484
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1485
                        if defaultConf != 0 {
6✔
1486
                                return defaultConf
3✔
1487
                        }
3✔
1488

1489
                        minConf := uint64(3)
×
1490
                        maxConf := uint64(6)
×
1491

×
1492
                        // If this is a wumbo channel, then we'll require the
×
1493
                        // max amount of confirmations.
×
1494
                        if chanAmt > MaxFundingAmount {
×
1495
                                return uint16(maxConf)
×
1496
                        }
×
1497

1498
                        // If not we return a value scaled linearly
1499
                        // between 3 and 6, depending on channel size.
1500
                        // TODO(halseth): Use 1 as minimum?
1501
                        maxChannelSize := uint64(
×
1502
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1503
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1504
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1505
                        if conf < minConf {
×
1506
                                conf = minConf
×
1507
                        }
×
1508
                        if conf > maxConf {
×
1509
                                conf = maxConf
×
1510
                        }
×
1511
                        return uint16(conf)
×
1512
                },
1513
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1514
                        // We scale the remote CSV delay (the time the
3✔
1515
                        // remote have to claim funds in case of a unilateral
3✔
1516
                        // close) linearly from minRemoteDelay blocks
3✔
1517
                        // for small channels, to maxRemoteDelay blocks
3✔
1518
                        // for channels of size MaxFundingAmount.
3✔
1519

3✔
1520
                        // In case the user has explicitly specified
3✔
1521
                        // a default value for the remote delay, we
3✔
1522
                        // use it.
3✔
1523
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1524
                        if defaultDelay > 0 {
6✔
1525
                                return defaultDelay
3✔
1526
                        }
3✔
1527

1528
                        // If this is a wumbo channel, then we'll require the
1529
                        // max value.
1530
                        if chanAmt > MaxFundingAmount {
×
1531
                                return maxRemoteDelay
×
1532
                        }
×
1533

1534
                        // If not we scale according to channel size.
1535
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1536
                                chanAmt / MaxFundingAmount)
×
1537
                        if delay < minRemoteDelay {
×
1538
                                delay = minRemoteDelay
×
1539
                        }
×
1540
                        if delay > maxRemoteDelay {
×
1541
                                delay = maxRemoteDelay
×
1542
                        }
×
1543
                        return delay
×
1544
                },
1545
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1546
                        peerKey *btcec.PublicKey) error {
3✔
1547

3✔
1548
                        // First, we'll mark this new peer as a persistent peer
3✔
1549
                        // for re-connection purposes. If the peer is not yet
3✔
1550
                        // tracked or the user hasn't requested it to be perm,
3✔
1551
                        // we'll set false to prevent the server from continuing
3✔
1552
                        // to connect to this peer even if the number of
3✔
1553
                        // channels with this peer is zero.
3✔
1554
                        s.mu.Lock()
3✔
1555
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1556
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1557
                                s.persistentPeers[pubStr] = false
3✔
1558
                        }
3✔
1559
                        s.mu.Unlock()
3✔
1560

3✔
1561
                        // With that taken care of, we'll send this channel to
3✔
1562
                        // the chain arb so it can react to on-chain events.
3✔
1563
                        return s.chainArb.WatchNewChannel(channel)
3✔
1564
                },
1565
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1566
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1567
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1568
                },
3✔
1569
                RequiredRemoteChanReserve: func(chanAmt,
1570
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1571

3✔
1572
                        // By default, we'll require the remote peer to maintain
3✔
1573
                        // at least 1% of the total channel capacity at all
3✔
1574
                        // times. If this value ends up dipping below the dust
3✔
1575
                        // limit, then we'll use the dust limit itself as the
3✔
1576
                        // reserve as required by BOLT #2.
3✔
1577
                        reserve := chanAmt / 100
3✔
1578
                        if reserve < dustLimit {
6✔
1579
                                reserve = dustLimit
3✔
1580
                        }
3✔
1581

1582
                        return reserve
3✔
1583
                },
1584
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1585
                        // By default, we'll allow the remote peer to fully
3✔
1586
                        // utilize the full bandwidth of the channel, minus our
3✔
1587
                        // required reserve.
3✔
1588
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1589
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1590
                },
3✔
1591
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1592
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1593
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1594
                        }
3✔
1595

1596
                        // By default, we'll permit them to utilize the full
1597
                        // channel bandwidth.
1598
                        return uint16(input.MaxHTLCNumber / 2)
×
1599
                },
1600
                ZombieSweeperInterval:         zombieSweeperInterval,
1601
                ReservationTimeout:            reservationTimeout,
1602
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1603
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1604
                MaxPendingChannels:            cfg.MaxPendingChannels,
1605
                RejectPush:                    cfg.RejectPush,
1606
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1607
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1608
                OpenChannelPredicate:          chanPredicate,
1609
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1610
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1611
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1612
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1613
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1614
                DeleteAliasEdge:      deleteAliasEdge,
1615
                AliasManager:         s.aliasMgr,
1616
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1617
                AuxFundingController: implCfg.AuxFundingController,
1618
                AuxSigner:            implCfg.AuxSigner,
1619
                AuxResolver:          implCfg.AuxContractResolver,
1620
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1621
        })
1622
        if err != nil {
3✔
1623
                return nil, err
×
1624
        }
×
1625

1626
        // Next, we'll assemble the sub-system that will maintain an on-disk
1627
        // static backup of the latest channel state.
1628
        chanNotifier := &channelNotifier{
3✔
1629
                chanNotifier: s.channelNotifier,
3✔
1630
                addrs:        s.addrSource,
3✔
1631
        }
3✔
1632
        backupFile := chanbackup.NewMultiFile(
3✔
1633
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1634
        )
3✔
1635
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1636
                ctx, s.chanStateDB, s.addrSource,
3✔
1637
        )
3✔
1638
        if err != nil {
3✔
1639
                return nil, err
×
1640
        }
×
1641
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1642
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1643
        )
3✔
1644
        if err != nil {
3✔
1645
                return nil, err
×
1646
        }
×
1647

1648
        // Assemble a peer notifier which will provide clients with subscriptions
1649
        // to peer online and offline events.
1650
        s.peerNotifier = peernotifier.New()
3✔
1651

3✔
1652
        // Create a channel event store which monitors all open channels.
3✔
1653
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1654
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1655
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1656
                },
3✔
1657
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1658
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1659
                },
3✔
1660
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1661
                Clock:           clock.NewDefaultClock(),
1662
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1663
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1664
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1665
        })
1666

1667
        if cfg.WtClient.Active {
6✔
1668
                policy := wtpolicy.DefaultPolicy()
3✔
1669
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1670

3✔
1671
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1672
                // protocol operations on sat/kw.
3✔
1673
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1674
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1675
                )
3✔
1676

3✔
1677
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1678

3✔
1679
                if err := policy.Validate(); err != nil {
3✔
1680
                        return nil, err
×
1681
                }
×
1682

1683
                // authDial is the wrapper around the btrontide.Dial for the
1684
                // watchtower.
1685
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1686
                        netAddr *lnwire.NetAddress,
3✔
1687
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1688

3✔
1689
                        return brontide.Dial(
3✔
1690
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1691
                        )
3✔
1692
                }
3✔
1693

1694
                // buildBreachRetribution is a call-back that can be used to
1695
                // query the BreachRetribution info and channel type given a
1696
                // channel ID and commitment height.
1697
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1698
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1699
                        channeldb.ChannelType, error) {
6✔
1700

3✔
1701
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1702
                                nil, chanID,
3✔
1703
                        )
3✔
1704
                        if err != nil {
3✔
1705
                                return nil, 0, err
×
1706
                        }
×
1707

1708
                        br, err := lnwallet.NewBreachRetribution(
3✔
1709
                                channel, commitHeight, 0, nil,
3✔
1710
                                implCfg.AuxLeafStore,
3✔
1711
                                implCfg.AuxContractResolver,
3✔
1712
                        )
3✔
1713
                        if err != nil {
3✔
1714
                                return nil, 0, err
×
1715
                        }
×
1716

1717
                        return br, channel.ChanType, nil
3✔
1718
                }
1719

1720
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1721

3✔
1722
                // Copy the policy for legacy channels and set the blob flag
3✔
1723
                // signalling support for anchor channels.
3✔
1724
                anchorPolicy := policy
3✔
1725
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1726

3✔
1727
                // Copy the policy for legacy channels and set the blob flag
3✔
1728
                // signalling support for taproot channels.
3✔
1729
                taprootPolicy := policy
3✔
1730
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1731
                        blob.FlagTaprootChannel,
3✔
1732
                )
3✔
1733

3✔
1734
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1735
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1736
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1737
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1738
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1739
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1740
                                error) {
6✔
1741

3✔
1742
                                return s.channelNotifier.
3✔
1743
                                        SubscribeChannelEvents()
3✔
1744
                        },
3✔
1745
                        Signer: cc.Wallet.Cfg.Signer,
1746
                        NewAddress: func() ([]byte, error) {
3✔
1747
                                addr, err := newSweepPkScriptGen(
3✔
1748
                                        cc.Wallet, netParams,
3✔
1749
                                )().Unpack()
3✔
1750
                                if err != nil {
3✔
1751
                                        return nil, err
×
1752
                                }
×
1753

1754
                                return addr.DeliveryAddress, nil
3✔
1755
                        },
1756
                        SecretKeyRing:      s.cc.KeyRing,
1757
                        Dial:               cfg.net.Dial,
1758
                        AuthDial:           authDial,
1759
                        DB:                 dbs.TowerClientDB,
1760
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1761
                        MinBackoff:         10 * time.Second,
1762
                        MaxBackoff:         5 * time.Minute,
1763
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1764
                }, policy, anchorPolicy, taprootPolicy)
1765
                if err != nil {
3✔
1766
                        return nil, err
×
1767
                }
×
1768
        }
1769

1770
        if len(cfg.ExternalHosts) != 0 {
3✔
1771
                advertisedIPs := make(map[string]struct{})
×
1772
                for _, addr := range s.currentNodeAnn.Addresses {
×
1773
                        advertisedIPs[addr.String()] = struct{}{}
×
1774
                }
×
1775

1776
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1777
                        Hosts:         cfg.ExternalHosts,
×
1778
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1779
                        LookupHost: func(host string) (net.Addr, error) {
×
1780
                                return lncfg.ParseAddressString(
×
1781
                                        host, strconv.Itoa(defaultPeerPort),
×
1782
                                        cfg.net.ResolveTCPAddr,
×
1783
                                )
×
1784
                        },
×
1785
                        AdvertisedIPs: advertisedIPs,
1786
                        AnnounceNewIPs: netann.IPAnnouncer(
1787
                                func(modifier ...netann.NodeAnnModifier) (
1788
                                        lnwire.NodeAnnouncement1, error) {
×
1789

×
1790
                                        return s.genNodeAnnouncement(
×
1791
                                                nil, modifier...,
×
1792
                                        )
×
1793
                                }),
×
1794
                })
1795
        }
1796

1797
        // Create liveness monitor.
1798
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1799

3✔
1800
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1801
        for i, listenAddr := range listenAddrs {
6✔
1802
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1803
                // doesn't need to call the general lndResolveTCP function
3✔
1804
                // since we are resolving a local address.
3✔
1805

3✔
1806
                // RESOLVE: We are actually partially accepting inbound
3✔
1807
                // connection requests when we call NewListener.
3✔
1808
                listeners[i], err = brontide.NewListener(
3✔
1809
                        nodeKeyECDH, listenAddr.String(),
3✔
1810
                        // TODO(yy): remove this check and unify the inbound
3✔
1811
                        // connection check inside `InboundPeerConnected`.
3✔
1812
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1813
                )
3✔
1814
                if err != nil {
3✔
1815
                        return nil, err
×
1816
                }
×
1817
        }
1818

1819
        // Create the connection manager which will be responsible for
1820
        // maintaining persistent outbound connections and also accepting new
1821
        // incoming connections
1822
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1823
                Listeners:      listeners,
3✔
1824
                OnAccept:       s.InboundPeerConnected,
3✔
1825
                RetryDuration:  time.Second * 5,
3✔
1826
                TargetOutbound: 100,
3✔
1827
                Dial: noiseDial(
3✔
1828
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1829
                ),
3✔
1830
                OnConnection: s.OutboundPeerConnected,
3✔
1831
        })
3✔
1832
        if err != nil {
3✔
1833
                return nil, err
×
1834
        }
×
1835
        s.connMgr = cmgr
3✔
1836

3✔
1837
        // Finally, register the subsystems in blockbeat.
3✔
1838
        s.registerBlockConsumers()
3✔
1839

3✔
1840
        return s, nil
3✔
1841
}
1842

1843
// UpdateRoutingConfig is a callback function to update the routing config
1844
// values in the main cfg.
1845
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1846
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1847

3✔
1848
        switch c := cfg.Estimator.Config().(type) {
3✔
1849
        case routing.AprioriConfig:
3✔
1850
                routerCfg.ProbabilityEstimatorType =
3✔
1851
                        routing.AprioriEstimatorName
3✔
1852

3✔
1853
                targetCfg := routerCfg.AprioriConfig
3✔
1854
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1855
                targetCfg.Weight = c.AprioriWeight
3✔
1856
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1857
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1858

1859
        case routing.BimodalConfig:
3✔
1860
                routerCfg.ProbabilityEstimatorType =
3✔
1861
                        routing.BimodalEstimatorName
3✔
1862

3✔
1863
                targetCfg := routerCfg.BimodalConfig
3✔
1864
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1865
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1866
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1867
        }
1868

1869
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1870
}
1871

1872
// registerBlockConsumers registers the subsystems that consume block events.
1873
// By calling `RegisterQueue`, a list of subsystems are registered in the
1874
// blockbeat for block notifications. When a new block arrives, the subsystems
1875
// in the same queue are notified sequentially, and different queues are
1876
// notified concurrently.
1877
//
1878
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1879
// a new `RegisterQueue` call.
1880
func (s *server) registerBlockConsumers() {
3✔
1881
        // In this queue, when a new block arrives, it will be received and
3✔
1882
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1883
        consumers := []chainio.Consumer{
3✔
1884
                s.chainArb,
3✔
1885
                s.sweeper,
3✔
1886
                s.txPublisher,
3✔
1887
        }
3✔
1888
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1889
}
3✔
1890

1891
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1892
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1893
// may differ from what is on disk.
1894
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1895
        error) {
3✔
1896

3✔
1897
        data, err := u.DataToSign()
3✔
1898
        if err != nil {
3✔
1899
                return nil, err
×
1900
        }
×
1901

1902
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1903
}
1904

1905
// createLivenessMonitor creates a set of health checks using our configured
1906
// values and uses these checks to create a liveness monitor. Available
1907
// health checks,
1908
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1909
//   - diskCheck
1910
//   - tlsHealthCheck
1911
//   - torController, only created when tor is enabled.
1912
//
1913
// If a health check has been disabled by setting attempts to 0, our monitor
1914
// will not run it.
1915
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1916
        leaderElector cluster.LeaderElector) {
3✔
1917

3✔
1918
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1919
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1920
                srvrLog.Info("Disabling chain backend checks for " +
×
1921
                        "nochainbackend mode")
×
1922

×
1923
                chainBackendAttempts = 0
×
1924
        }
×
1925

1926
        chainHealthCheck := healthcheck.NewObservation(
3✔
1927
                "chain backend",
3✔
1928
                cc.HealthCheck,
3✔
1929
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1930
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1931
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1932
                chainBackendAttempts,
3✔
1933
        )
3✔
1934

3✔
1935
        diskCheck := healthcheck.NewObservation(
3✔
1936
                "disk space",
3✔
1937
                func() error {
3✔
1938
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1939
                                cfg.LndDir,
×
1940
                        )
×
1941
                        if err != nil {
×
1942
                                return err
×
1943
                        }
×
1944

1945
                        // If we have more free space than we require,
1946
                        // we return a nil error.
1947
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1948
                                return nil
×
1949
                        }
×
1950

1951
                        return fmt.Errorf("require: %v free space, got: %v",
×
1952
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1953
                                free)
×
1954
                },
1955
                cfg.HealthChecks.DiskCheck.Interval,
1956
                cfg.HealthChecks.DiskCheck.Timeout,
1957
                cfg.HealthChecks.DiskCheck.Backoff,
1958
                cfg.HealthChecks.DiskCheck.Attempts,
1959
        )
1960

1961
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1962
                "tls",
3✔
1963
                func() error {
3✔
1964
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1965
                                s.cc.KeyRing,
×
1966
                        )
×
1967
                        if err != nil {
×
1968
                                return err
×
1969
                        }
×
1970
                        if expired {
×
1971
                                return fmt.Errorf("TLS certificate is "+
×
1972
                                        "expired as of %v", expTime)
×
1973
                        }
×
1974

1975
                        // If the certificate is not outdated, no error needs
1976
                        // to be returned
1977
                        return nil
×
1978
                },
1979
                cfg.HealthChecks.TLSCheck.Interval,
1980
                cfg.HealthChecks.TLSCheck.Timeout,
1981
                cfg.HealthChecks.TLSCheck.Backoff,
1982
                cfg.HealthChecks.TLSCheck.Attempts,
1983
        )
1984

1985
        checks := []*healthcheck.Observation{
3✔
1986
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1987
        }
3✔
1988

3✔
1989
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1990
        if s.torController != nil {
3✔
1991
                torConnectionCheck := healthcheck.NewObservation(
×
1992
                        "tor connection",
×
1993
                        func() error {
×
1994
                                return healthcheck.CheckTorServiceStatus(
×
1995
                                        s.torController,
×
1996
                                        func() error {
×
1997
                                                return s.createNewHiddenService(
×
1998
                                                        context.TODO(),
×
1999
                                                )
×
2000
                                        },
×
2001
                                )
2002
                        },
2003
                        cfg.HealthChecks.TorConnection.Interval,
2004
                        cfg.HealthChecks.TorConnection.Timeout,
2005
                        cfg.HealthChecks.TorConnection.Backoff,
2006
                        cfg.HealthChecks.TorConnection.Attempts,
2007
                )
2008
                checks = append(checks, torConnectionCheck)
×
2009
        }
2010

2011
        // If remote signing is enabled, add the healthcheck for the remote
2012
        // signing RPC interface.
2013
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2014
                // Because we have two cascading timeouts here, we need to add
3✔
2015
                // some slack to the "outer" one of them in case the "inner"
3✔
2016
                // returns exactly on time.
3✔
2017
                overhead := time.Millisecond * 10
3✔
2018

3✔
2019
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2020
                        "remote signer connection",
3✔
2021
                        rpcwallet.HealthCheck(
3✔
2022
                                s.cfg.RemoteSigner,
3✔
2023

3✔
2024
                                // For the health check we might to be even
3✔
2025
                                // stricter than the initial/normal connect, so
3✔
2026
                                // we use the health check timeout here.
3✔
2027
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2028
                        ),
3✔
2029
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2030
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2031
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2032
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2033
                )
3✔
2034
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2035
        }
3✔
2036

2037
        // If we have a leader elector, we add a health check to ensure we are
2038
        // still the leader. During normal operation, we should always be the
2039
        // leader, but there are circumstances where this may change, such as
2040
        // when we lose network connectivity for long enough expiring out lease.
2041
        if leaderElector != nil {
3✔
2042
                leaderCheck := healthcheck.NewObservation(
×
2043
                        "leader status",
×
2044
                        func() error {
×
2045
                                // Check if we are still the leader. Note that
×
2046
                                // we don't need to use a timeout context here
×
2047
                                // as the healthcheck observer will handle the
×
2048
                                // timeout case for us.
×
2049
                                timeoutCtx, cancel := context.WithTimeout(
×
2050
                                        context.Background(),
×
2051
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2052
                                )
×
2053
                                defer cancel()
×
2054

×
2055
                                leader, err := leaderElector.IsLeader(
×
2056
                                        timeoutCtx,
×
2057
                                )
×
2058
                                if err != nil {
×
2059
                                        return fmt.Errorf("unable to check if "+
×
2060
                                                "still leader: %v", err)
×
2061
                                }
×
2062

2063
                                if !leader {
×
2064
                                        srvrLog.Debug("Not the current leader")
×
2065
                                        return fmt.Errorf("not the current " +
×
2066
                                                "leader")
×
2067
                                }
×
2068

2069
                                return nil
×
2070
                        },
2071
                        cfg.HealthChecks.LeaderCheck.Interval,
2072
                        cfg.HealthChecks.LeaderCheck.Timeout,
2073
                        cfg.HealthChecks.LeaderCheck.Backoff,
2074
                        cfg.HealthChecks.LeaderCheck.Attempts,
2075
                )
2076

2077
                checks = append(checks, leaderCheck)
×
2078
        }
2079

2080
        // If we have not disabled all of our health checks, we create a
2081
        // liveness monitor with our configured checks.
2082
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2083
                &healthcheck.Config{
3✔
2084
                        Checks:   checks,
3✔
2085
                        Shutdown: srvrLog.Criticalf,
3✔
2086
                },
3✔
2087
        )
3✔
2088
}
2089

2090
// Started returns true if the server has been started, and false otherwise.
2091
// NOTE: This function is safe for concurrent access.
2092
func (s *server) Started() bool {
3✔
2093
        return atomic.LoadInt32(&s.active) != 0
3✔
2094
}
3✔
2095

2096
// cleaner is used to aggregate "cleanup" functions during an operation that
2097
// starts several subsystems. In case one of the subsystem fails to start
2098
// and a proper resource cleanup is required, the "run" method achieves this
2099
// by running all these added "cleanup" functions.
2100
type cleaner []func() error
2101

2102
// add is used to add a cleanup function to be called when
2103
// the run function is executed.
2104
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2105
        return append(c, cleanup)
3✔
2106
}
3✔
2107

2108
// run is used to run all the previousely added cleanup functions.
2109
func (c cleaner) run() {
×
2110
        for i := len(c) - 1; i >= 0; i-- {
×
2111
                if err := c[i](); err != nil {
×
2112
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2113
                }
×
2114
        }
2115
}
2116

2117
// Start starts the main daemon server, all requested listeners, and any helper
2118
// goroutines.
2119
// NOTE: This function is safe for concurrent access.
2120
//
2121
//nolint:funlen
2122
func (s *server) Start(ctx context.Context) error {
3✔
2123
        var startErr error
3✔
2124

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

3✔
2130
        s.start.Do(func() {
6✔
2131
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2132
                if err := s.customMessageServer.Start(); err != nil {
3✔
2133
                        startErr = err
×
2134
                        return
×
2135
                }
×
2136

2137
                if s.hostAnn != nil {
3✔
2138
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2139
                        if err := s.hostAnn.Start(); err != nil {
×
2140
                                startErr = err
×
2141
                                return
×
2142
                        }
×
2143
                }
2144

2145
                if s.livenessMonitor != nil {
6✔
2146
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2147
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2148
                                startErr = err
×
2149
                                return
×
2150
                        }
×
2151
                }
2152

2153
                // Start the notification server. This is used so channel
2154
                // management goroutines can be notified when a funding
2155
                // transaction reaches a sufficient number of confirmations, or
2156
                // when the input for the funding transaction is spent in an
2157
                // attempt at an uncooperative close by the counterparty.
2158
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2159
                if err := s.sigPool.Start(); err != nil {
3✔
2160
                        startErr = err
×
2161
                        return
×
2162
                }
×
2163

2164
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2165
                if err := s.writePool.Start(); err != nil {
3✔
2166
                        startErr = err
×
2167
                        return
×
2168
                }
×
2169

2170
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2171
                if err := s.readPool.Start(); err != nil {
3✔
2172
                        startErr = err
×
2173
                        return
×
2174
                }
×
2175

2176
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2177
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2178
                        startErr = err
×
2179
                        return
×
2180
                }
×
2181

2182
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2183
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2184
                        startErr = err
×
2185
                        return
×
2186
                }
×
2187

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

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

2202
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2203
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2204
                        startErr = err
×
2205
                        return
×
2206
                }
×
2207

2208
                if s.towerClientMgr != nil {
6✔
2209
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2210
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2211
                                startErr = err
×
2212
                                return
×
2213
                        }
×
2214
                }
2215

2216
                beat, err := s.getStartingBeat()
3✔
2217
                if err != nil {
3✔
2218
                        startErr = err
×
2219
                        return
×
2220
                }
×
2221

2222
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2223
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2224
                        startErr = err
×
2225
                        return
×
2226
                }
×
2227

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

2234
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2235
                if err := s.utxoNursery.Start(); err != nil {
3✔
2236
                        startErr = err
×
2237
                        return
×
2238
                }
×
2239

2240
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2241
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2242
                        startErr = err
×
2243
                        return
×
2244
                }
×
2245

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

2252
                // htlcSwitch must be started before chainArb since the latter
2253
                // relies on htlcSwitch to deliver resolution message upon
2254
                // start.
2255
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2256
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

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

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

2273
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2274
                if err := s.chainArb.Start(beat); err != nil {
3✔
2275
                        startErr = err
×
2276
                        return
×
2277
                }
×
2278

2279
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2280
                if err := s.graphDB.Start(); err != nil {
3✔
2281
                        startErr = err
×
2282
                        return
×
2283
                }
×
2284

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

2291
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2292
                if err := s.chanRouter.Start(); err != nil {
3✔
2293
                        startErr = err
×
2294
                        return
×
2295
                }
×
2296
                // The authGossiper depends on the chanRouter and therefore
2297
                // should be started after it.
2298
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2299
                if err := s.authGossiper.Start(); err != nil {
3✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

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

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

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

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

2328
                cleanup.add(func() error {
3✔
2329
                        s.missionController.StopStoreTickers()
×
2330
                        return nil
×
2331
                })
×
2332
                s.missionController.RunStoreTickers()
3✔
2333

3✔
2334
                // Before we start the connMgr, we'll check to see if we have
3✔
2335
                // any backups to recover. We do this now as we want to ensure
3✔
2336
                // that have all the information we need to handle channel
3✔
2337
                // recovery _before_ we even accept connections from any peers.
3✔
2338
                chanRestorer := &chanDBRestorer{
3✔
2339
                        db:         s.chanStateDB,
3✔
2340
                        secretKeys: s.cc.KeyRing,
3✔
2341
                        chainArb:   s.chainArb,
3✔
2342
                }
3✔
2343
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2344
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2345
                                s.chansToRestore.PackedSingleChanBackups,
×
2346
                                s.cc.KeyRing, chanRestorer, s,
×
2347
                        )
×
2348
                        if err != nil {
×
2349
                                startErr = fmt.Errorf("unable to unpack single "+
×
2350
                                        "backups: %v", err)
×
2351
                                return
×
2352
                        }
×
2353
                }
2354
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2355
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2356
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2357
                                s.cc.KeyRing, chanRestorer, s,
3✔
2358
                        )
3✔
2359
                        if err != nil {
3✔
2360
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2361
                                        "backup: %v", err)
×
2362
                                return
×
2363
                        }
×
2364
                }
2365

2366
                // chanSubSwapper must be started after the `channelNotifier`
2367
                // because it depends on channel events as a synchronization
2368
                // point.
2369
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2370
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2371
                        startErr = err
×
2372
                        return
×
2373
                }
×
2374

2375
                if s.torController != nil {
3✔
2376
                        cleanup = cleanup.add(s.torController.Stop)
×
2377
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2378
                                startErr = err
×
2379
                                return
×
2380
                        }
×
2381
                }
2382

2383
                if s.natTraversal != nil {
3✔
2384
                        s.wg.Add(1)
×
2385
                        go s.watchExternalIP()
×
2386
                }
×
2387

2388
                // Start connmgr last to prevent connections before init.
2389
                cleanup = cleanup.add(func() error {
3✔
2390
                        s.connMgr.Stop()
×
2391
                        return nil
×
2392
                })
×
2393

2394
                // RESOLVE: s.connMgr.Start() is called here, but
2395
                // brontide.NewListener() is called in newServer. This means
2396
                // that we are actually listening and partially accepting
2397
                // inbound connections even before the connMgr starts.
2398
                //
2399
                // TODO(yy): move the log into the connMgr's `Start` method.
2400
                srvrLog.Info("connMgr starting...")
3✔
2401
                s.connMgr.Start()
3✔
2402
                srvrLog.Debug("connMgr started")
3✔
2403

3✔
2404
                // If peers are specified as a config option, we'll add those
3✔
2405
                // peers first.
3✔
2406
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2407
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2408
                                peerAddrCfg,
3✔
2409
                        )
3✔
2410
                        if err != nil {
3✔
2411
                                startErr = fmt.Errorf("unable to parse peer "+
×
2412
                                        "pubkey from config: %v", err)
×
2413
                                return
×
2414
                        }
×
2415
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2416
                        if err != nil {
3✔
2417
                                startErr = fmt.Errorf("unable to parse peer "+
×
2418
                                        "address provided as a config option: "+
×
2419
                                        "%v", err)
×
2420
                                return
×
2421
                        }
×
2422

2423
                        peerAddr := &lnwire.NetAddress{
3✔
2424
                                IdentityKey: parsedPubkey,
3✔
2425
                                Address:     addr,
3✔
2426
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2427
                        }
3✔
2428

3✔
2429
                        err = s.ConnectToPeer(
3✔
2430
                                peerAddr, true,
3✔
2431
                                s.cfg.ConnectionTimeout,
3✔
2432
                        )
3✔
2433
                        if err != nil {
3✔
2434
                                startErr = fmt.Errorf("unable to connect to "+
×
2435
                                        "peer address provided as a config "+
×
2436
                                        "option: %v", err)
×
2437
                                return
×
2438
                        }
×
2439
                }
2440

2441
                // Subscribe to NodeAnnouncements that advertise new addresses
2442
                // our persistent peers.
2443
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2444
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2445
                                "addr: %v", err)
×
2446

×
2447
                        startErr = err
×
2448
                        return
×
2449
                }
×
2450

2451
                // With all the relevant sub-systems started, we'll now attempt
2452
                // to establish persistent connections to our direct channel
2453
                // collaborators within the network. Before doing so however,
2454
                // we'll prune our set of link nodes found within the database
2455
                // to ensure we don't reconnect to any nodes we no longer have
2456
                // open channels with.
2457
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2458
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2459

×
2460
                        startErr = err
×
2461
                        return
×
2462
                }
×
2463

2464
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2465
                        srvrLog.Errorf("Failed to establish persistent "+
×
2466
                                "connections: %v", err)
×
2467
                }
×
2468

2469
                // setSeedList is a helper function that turns multiple DNS seed
2470
                // server tuples from the command line or config file into the
2471
                // data structure we need and does a basic formal sanity check
2472
                // in the process.
2473
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2474
                        if len(tuples) == 0 {
×
2475
                                return
×
2476
                        }
×
2477

2478
                        result := make([][2]string, len(tuples))
×
2479
                        for idx, tuple := range tuples {
×
2480
                                tuple = strings.TrimSpace(tuple)
×
2481
                                if len(tuple) == 0 {
×
2482
                                        return
×
2483
                                }
×
2484

2485
                                servers := strings.Split(tuple, ",")
×
2486
                                if len(servers) > 2 || len(servers) == 0 {
×
2487
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2488
                                                "seed tuple: %v", servers)
×
2489
                                        return
×
2490
                                }
×
2491

2492
                                copy(result[idx][:], servers)
×
2493
                        }
2494

2495
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2496
                }
2497

2498
                // Let users overwrite the DNS seed nodes. We only allow them
2499
                // for bitcoin mainnet/testnet/signet.
2500
                if s.cfg.Bitcoin.MainNet {
3✔
2501
                        setSeedList(
×
2502
                                s.cfg.Bitcoin.DNSSeeds,
×
2503
                                chainreg.BitcoinMainnetGenesis,
×
2504
                        )
×
2505
                }
×
2506
                if s.cfg.Bitcoin.TestNet3 {
3✔
2507
                        setSeedList(
×
2508
                                s.cfg.Bitcoin.DNSSeeds,
×
2509
                                chainreg.BitcoinTestnetGenesis,
×
2510
                        )
×
2511
                }
×
2512
                if s.cfg.Bitcoin.TestNet4 {
3✔
2513
                        setSeedList(
×
2514
                                s.cfg.Bitcoin.DNSSeeds,
×
2515
                                chainreg.BitcoinTestnet4Genesis,
×
2516
                        )
×
2517
                }
×
2518
                if s.cfg.Bitcoin.SigNet {
3✔
2519
                        setSeedList(
×
2520
                                s.cfg.Bitcoin.DNSSeeds,
×
2521
                                chainreg.BitcoinSignetGenesis,
×
2522
                        )
×
2523
                }
×
2524

2525
                // If network bootstrapping hasn't been disabled, then we'll
2526
                // configure the set of active bootstrappers, and launch a
2527
                // dedicated goroutine to maintain a set of persistent
2528
                // connections.
2529
                if !s.cfg.NoNetBootstrap {
6✔
2530
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2531
                        if err != nil {
3✔
2532
                                startErr = err
×
2533
                                return
×
2534
                        }
×
2535

2536
                        s.wg.Add(1)
3✔
2537
                        go s.peerBootstrapper(
3✔
2538
                                ctx, defaultMinPeers, bootstrappers,
3✔
2539
                        )
3✔
2540
                } else {
3✔
2541
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2542
                }
3✔
2543

2544
                // Start the blockbeat after all other subsystems have been
2545
                // started so they are ready to receive new blocks.
2546
                cleanup = cleanup.add(func() error {
3✔
2547
                        s.blockbeatDispatcher.Stop()
×
2548
                        return nil
×
2549
                })
×
2550
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2551
                        startErr = err
×
2552
                        return
×
2553
                }
×
2554

2555
                // Set the active flag now that we've completed the full
2556
                // startup.
2557
                atomic.StoreInt32(&s.active, 1)
3✔
2558
        })
2559

2560
        if startErr != nil {
3✔
2561
                cleanup.run()
×
2562
        }
×
2563
        return startErr
3✔
2564
}
2565

2566
// Stop gracefully shutsdown the main daemon server. This function will signal
2567
// any active goroutines, or helper objects to exit, then blocks until they've
2568
// all successfully exited. Additionally, any/all listeners are closed.
2569
// NOTE: This function is safe for concurrent access.
2570
func (s *server) Stop() error {
3✔
2571
        s.stop.Do(func() {
6✔
2572
                atomic.StoreInt32(&s.stopping, 1)
3✔
2573

3✔
2574
                ctx := context.Background()
3✔
2575

3✔
2576
                close(s.quit)
3✔
2577

3✔
2578
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2579
                s.connMgr.Stop()
3✔
2580

3✔
2581
                // Stop dispatching blocks to other systems immediately.
3✔
2582
                s.blockbeatDispatcher.Stop()
3✔
2583

3✔
2584
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2585
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2586
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2587
                }
×
2588
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2589
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2590
                }
×
2591
                if err := s.sphinx.Stop(); err != nil {
3✔
2592
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2593
                }
×
2594
                if err := s.invoices.Stop(); err != nil {
3✔
2595
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2596
                }
×
2597
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2598
                        srvrLog.Warnf("failed to stop interceptable "+
×
2599
                                "switch: %v", err)
×
2600
                }
×
2601
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2602
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2603
                                "modifier: %v", err)
×
2604
                }
×
2605
                if err := s.chanRouter.Stop(); err != nil {
3✔
2606
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2607
                }
×
2608
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2609
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2610
                }
×
2611
                if err := s.graphDB.Stop(); err != nil {
3✔
2612
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2613
                }
×
2614
                if err := s.chainArb.Stop(); err != nil {
3✔
2615
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2616
                }
×
2617
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2618
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2619
                }
×
2620
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2621
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2622
                                err)
×
2623
                }
×
2624
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2625
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2626
                }
×
2627
                if err := s.authGossiper.Stop(); err != nil {
3✔
2628
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2629
                }
×
2630
                if err := s.sweeper.Stop(); err != nil {
3✔
2631
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2632
                }
×
2633
                if err := s.txPublisher.Stop(); err != nil {
3✔
2634
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2635
                }
×
2636
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2637
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2638
                }
×
2639
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2640
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2641
                }
×
2642
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2643
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2644
                }
×
2645

2646
                // Update channel.backup file. Make sure to do it before
2647
                // stopping chanSubSwapper.
2648
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2649
                        ctx, s.chanStateDB, s.addrSource,
3✔
2650
                )
3✔
2651
                if err != nil {
3✔
2652
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2653
                                err)
×
2654
                } else {
3✔
2655
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2656
                        if err != nil {
6✔
2657
                                srvrLog.Warnf("Manual update of channel "+
3✔
2658
                                        "backup failed: %v", err)
3✔
2659
                        }
3✔
2660
                }
2661

2662
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2663
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2664
                }
×
2665
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2666
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2667
                }
×
2668
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2669
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2670
                                err)
×
2671
                }
×
2672
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2673
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2674
                                err)
×
2675
                }
×
2676
                s.missionController.StopStoreTickers()
3✔
2677

3✔
2678
                // Disconnect from each active peers to ensure that
3✔
2679
                // peerTerminationWatchers signal completion to each peer.
3✔
2680
                for _, peer := range s.Peers() {
6✔
2681
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2682
                        if err != nil {
3✔
2683
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2684
                                        "received error: %v", peer.IdentityKey(),
×
2685
                                        err,
×
2686
                                )
×
2687
                        }
×
2688
                }
2689

2690
                // Now that all connections have been torn down, stop the tower
2691
                // client which will reliably flush all queued states to the
2692
                // tower. If this is halted for any reason, the force quit timer
2693
                // will kick in and abort to allow this method to return.
2694
                if s.towerClientMgr != nil {
6✔
2695
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2696
                                srvrLog.Warnf("Unable to shut down tower "+
×
2697
                                        "client manager: %v", err)
×
2698
                        }
×
2699
                }
2700

2701
                if s.hostAnn != nil {
3✔
2702
                        if err := s.hostAnn.Stop(); err != nil {
×
2703
                                srvrLog.Warnf("unable to shut down host "+
×
2704
                                        "annoucner: %v", err)
×
2705
                        }
×
2706
                }
2707

2708
                if s.livenessMonitor != nil {
6✔
2709
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2710
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2711
                                        "monitor: %v", err)
×
2712
                        }
×
2713
                }
2714

2715
                // Wait for all lingering goroutines to quit.
2716
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2717
                s.wg.Wait()
3✔
2718

3✔
2719
                srvrLog.Debug("Stopping buffer pools...")
3✔
2720
                s.sigPool.Stop()
3✔
2721
                s.writePool.Stop()
3✔
2722
                s.readPool.Stop()
3✔
2723
        })
2724

2725
        return nil
3✔
2726
}
2727

2728
// Stopped returns true if the server has been instructed to shutdown.
2729
// NOTE: This function is safe for concurrent access.
2730
func (s *server) Stopped() bool {
3✔
2731
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2732
}
3✔
2733

2734
// configurePortForwarding attempts to set up port forwarding for the different
2735
// ports that the server will be listening on.
2736
//
2737
// NOTE: This should only be used when using some kind of NAT traversal to
2738
// automatically set up forwarding rules.
2739
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2740
        ip, err := s.natTraversal.ExternalIP()
×
2741
        if err != nil {
×
2742
                return nil, err
×
2743
        }
×
2744
        s.lastDetectedIP = ip
×
2745

×
2746
        externalIPs := make([]string, 0, len(ports))
×
2747
        for _, port := range ports {
×
2748
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2749
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2750
                        continue
×
2751
                }
2752

2753
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2754
                externalIPs = append(externalIPs, hostIP)
×
2755
        }
2756

2757
        return externalIPs, nil
×
2758
}
2759

2760
// removePortForwarding attempts to clear the forwarding rules for the different
2761
// ports the server is currently listening on.
2762
//
2763
// NOTE: This should only be used when using some kind of NAT traversal to
2764
// automatically set up forwarding rules.
2765
func (s *server) removePortForwarding() {
×
2766
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2767
        for _, port := range forwardedPorts {
×
2768
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2769
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2770
                                "port %d: %v", port, err)
×
2771
                }
×
2772
        }
2773
}
2774

2775
// watchExternalIP continuously checks for an updated external IP address every
2776
// 15 minutes. Once a new IP address has been detected, it will automatically
2777
// handle port forwarding rules and send updated node announcements to the
2778
// currently connected peers.
2779
//
2780
// NOTE: This MUST be run as a goroutine.
2781
func (s *server) watchExternalIP() {
×
2782
        defer s.wg.Done()
×
2783

×
2784
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2785
        // up by the server.
×
2786
        defer s.removePortForwarding()
×
2787

×
2788
        // Keep track of the external IPs set by the user to avoid replacing
×
2789
        // them when detecting a new IP.
×
2790
        ipsSetByUser := make(map[string]struct{})
×
2791
        for _, ip := range s.cfg.ExternalIPs {
×
2792
                ipsSetByUser[ip.String()] = struct{}{}
×
2793
        }
×
2794

2795
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2796

×
2797
        ticker := time.NewTicker(15 * time.Minute)
×
2798
        defer ticker.Stop()
×
2799
out:
×
2800
        for {
×
2801
                select {
×
2802
                case <-ticker.C:
×
2803
                        // We'll start off by making sure a new IP address has
×
2804
                        // been detected.
×
2805
                        ip, err := s.natTraversal.ExternalIP()
×
2806
                        if err != nil {
×
2807
                                srvrLog.Debugf("Unable to retrieve the "+
×
2808
                                        "external IP address: %v", err)
×
2809
                                continue
×
2810
                        }
2811

2812
                        // Periodically renew the NAT port forwarding.
2813
                        for _, port := range forwardedPorts {
×
2814
                                err := s.natTraversal.AddPortMapping(port)
×
2815
                                if err != nil {
×
2816
                                        srvrLog.Warnf("Unable to automatically "+
×
2817
                                                "re-create port forwarding using %s: %v",
×
2818
                                                s.natTraversal.Name(), err)
×
2819
                                } else {
×
2820
                                        srvrLog.Debugf("Automatically re-created "+
×
2821
                                                "forwarding for port %d using %s to "+
×
2822
                                                "advertise external IP",
×
2823
                                                port, s.natTraversal.Name())
×
2824
                                }
×
2825
                        }
2826

2827
                        if ip.Equal(s.lastDetectedIP) {
×
2828
                                continue
×
2829
                        }
2830

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

×
2833
                        // Next, we'll craft the new addresses that will be
×
2834
                        // included in the new node announcement and advertised
×
2835
                        // to the network. Each address will consist of the new
×
2836
                        // IP detected and one of the currently advertised
×
2837
                        // ports.
×
2838
                        var newAddrs []net.Addr
×
2839
                        for _, port := range forwardedPorts {
×
2840
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2841
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2842
                                if err != nil {
×
2843
                                        srvrLog.Debugf("Unable to resolve "+
×
2844
                                                "host %v: %v", addr, err)
×
2845
                                        continue
×
2846
                                }
2847

2848
                                newAddrs = append(newAddrs, addr)
×
2849
                        }
2850

2851
                        // Skip the update if we weren't able to resolve any of
2852
                        // the new addresses.
2853
                        if len(newAddrs) == 0 {
×
2854
                                srvrLog.Debug("Skipping node announcement " +
×
2855
                                        "update due to not being able to " +
×
2856
                                        "resolve any new addresses")
×
2857
                                continue
×
2858
                        }
2859

2860
                        // Now, we'll need to update the addresses in our node's
2861
                        // announcement in order to propagate the update
2862
                        // throughout the network. We'll only include addresses
2863
                        // that have a different IP from the previous one, as
2864
                        // the previous IP is no longer valid.
2865
                        currentNodeAnn := s.getNodeAnnouncement()
×
2866

×
2867
                        for _, addr := range currentNodeAnn.Addresses {
×
2868
                                host, _, err := net.SplitHostPort(addr.String())
×
2869
                                if err != nil {
×
2870
                                        srvrLog.Debugf("Unable to determine "+
×
2871
                                                "host from address %v: %v",
×
2872
                                                addr, err)
×
2873
                                        continue
×
2874
                                }
2875

2876
                                // We'll also make sure to include external IPs
2877
                                // set manually by the user.
2878
                                _, setByUser := ipsSetByUser[addr.String()]
×
2879
                                if setByUser || host != s.lastDetectedIP.String() {
×
2880
                                        newAddrs = append(newAddrs, addr)
×
2881
                                }
×
2882
                        }
2883

2884
                        // Then, we'll generate a new timestamped node
2885
                        // announcement with the updated addresses and broadcast
2886
                        // it to our peers.
2887
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2888
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2889
                        )
×
2890
                        if err != nil {
×
2891
                                srvrLog.Debugf("Unable to generate new node "+
×
2892
                                        "announcement: %v", err)
×
2893
                                continue
×
2894
                        }
2895

2896
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2897
                        if err != nil {
×
2898
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2899
                                        "announcement to peers: %v", err)
×
2900
                                continue
×
2901
                        }
2902

2903
                        // Finally, update the last IP seen to the current one.
2904
                        s.lastDetectedIP = ip
×
2905
                case <-s.quit:
×
2906
                        break out
×
2907
                }
2908
        }
2909
}
2910

2911
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2912
// based on the server, and currently active bootstrap mechanisms as defined
2913
// within the current configuration.
2914
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2915
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2916

3✔
2917
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2918

3✔
2919
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2920
        // this can be used by default if we've already partially seeded the
3✔
2921
        // network.
3✔
2922
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2923
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2924
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2925
        )
3✔
2926
        if err != nil {
3✔
2927
                return nil, err
×
2928
        }
×
2929
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2930

3✔
2931
        // If this isn't using simnet or regtest mode, then one of our
3✔
2932
        // additional bootstrapping sources will be the set of running DNS
3✔
2933
        // seeds.
3✔
2934
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2935
                //nolint:ll
×
2936
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2937

×
2938
                // If we have a set of DNS seeds for this chain, then we'll add
×
2939
                // it as an additional bootstrapping source.
×
2940
                if ok {
×
2941
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2942
                                "seeds: %v", dnsSeeds)
×
2943

×
2944
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2945
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2946
                        )
×
2947
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2948
                }
×
2949
        }
2950

2951
        return bootStrappers, nil
3✔
2952
}
2953

2954
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2955
// needs to ignore, which is made of three parts,
2956
//   - the node itself needs to be skipped as it doesn't make sense to connect
2957
//     to itself.
2958
//   - the peers that already have connections with, as in s.peersByPub.
2959
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2960
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2961
        s.mu.RLock()
3✔
2962
        defer s.mu.RUnlock()
3✔
2963

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

3✔
2966
        // We should ignore ourselves from bootstrapping.
3✔
2967
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2968
        ignore[selfKey] = struct{}{}
3✔
2969

3✔
2970
        // Ignore all connected peers.
3✔
2971
        for _, peer := range s.peersByPub {
3✔
2972
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2973
                ignore[nID] = struct{}{}
×
2974
        }
×
2975

2976
        // Ignore all persistent peers as they have a dedicated reconnecting
2977
        // process.
2978
        for pubKeyStr := range s.persistentPeers {
3✔
2979
                var nID autopilot.NodeID
×
2980
                copy(nID[:], []byte(pubKeyStr))
×
2981
                ignore[nID] = struct{}{}
×
2982
        }
×
2983

2984
        return ignore
3✔
2985
}
2986

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

3✔
2995
        defer s.wg.Done()
3✔
2996

3✔
2997
        // Before we continue, init the ignore peers map.
3✔
2998
        ignoreList := s.createBootstrapIgnorePeers()
3✔
2999

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

3✔
3004
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3005
        // peers.
3✔
3006
        //
3✔
3007
        // We'll use a 15 second backoff, and double the time every time an
3✔
3008
        // epoch fails up to a ceiling.
3✔
3009
        backOff := time.Second * 15
3✔
3010

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

3✔
3016
        // We'll use the number of attempts and errors to determine if we need
3✔
3017
        // to increase the time between discovery epochs.
3✔
3018
        var epochErrors uint32 // To be used atomically.
3✔
3019
        var epochAttempts uint32
3✔
3020

3✔
3021
        for {
6✔
3022
                select {
3✔
3023
                // The ticker has just woken us up, so we'll need to check if
3024
                // we need to attempt to connect our to any more peers.
3025
                case <-sampleTicker.C:
×
3026
                        // Obtain the current number of peers, so we can gauge
×
3027
                        // if we need to sample more peers or not.
×
3028
                        s.mu.RLock()
×
3029
                        numActivePeers := uint32(len(s.peersByPub))
×
3030
                        s.mu.RUnlock()
×
3031

×
3032
                        // If we have enough peers, then we can loop back
×
3033
                        // around to the next round as we're done here.
×
3034
                        if numActivePeers >= numTargetPeers {
×
3035
                                continue
×
3036
                        }
3037

3038
                        // If all of our attempts failed during this last back
3039
                        // off period, then will increase our backoff to 5
3040
                        // minute ceiling to avoid an excessive number of
3041
                        // queries
3042
                        //
3043
                        // TODO(roasbeef): add reverse policy too?
3044

3045
                        if epochAttempts > 0 &&
×
3046
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3047

×
3048
                                sampleTicker.Stop()
×
3049

×
3050
                                backOff *= 2
×
3051
                                if backOff > bootstrapBackOffCeiling {
×
3052
                                        backOff = bootstrapBackOffCeiling
×
3053
                                }
×
3054

3055
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3056
                                        "%v", backOff)
×
3057
                                sampleTicker = time.NewTicker(backOff)
×
3058
                                continue
×
3059
                        }
3060

3061
                        atomic.StoreUint32(&epochErrors, 0)
×
3062
                        epochAttempts = 0
×
3063

×
3064
                        // Since we know need more peers, we'll compute the
×
3065
                        // exact number we need to reach our threshold.
×
3066
                        numNeeded := numTargetPeers - numActivePeers
×
3067

×
3068
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3069
                                "peers", numNeeded)
×
3070

×
3071
                        // With the number of peers we need calculated, we'll
×
3072
                        // query the network bootstrappers to sample a set of
×
3073
                        // random addrs for us.
×
3074
                        //
×
3075
                        // Before we continue, get a copy of the ignore peers
×
3076
                        // map.
×
3077
                        ignoreList = s.createBootstrapIgnorePeers()
×
3078

×
3079
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3080
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3081
                        )
×
3082
                        if err != nil {
×
3083
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3084
                                        "peers: %v", err)
×
3085
                                continue
×
3086
                        }
3087

3088
                        // Finally, we'll launch a new goroutine for each
3089
                        // prospective peer candidates.
3090
                        for _, addr := range peerAddrs {
×
3091
                                epochAttempts++
×
3092

×
3093
                                go func(a *lnwire.NetAddress) {
×
3094
                                        // TODO(roasbeef): can do AS, subnet,
×
3095
                                        // country diversity, etc
×
3096
                                        errChan := make(chan error, 1)
×
3097
                                        s.connectToPeer(
×
3098
                                                a, errChan,
×
3099
                                                s.cfg.ConnectionTimeout,
×
3100
                                        )
×
3101
                                        select {
×
3102
                                        case err := <-errChan:
×
3103
                                                if err == nil {
×
3104
                                                        return
×
3105
                                                }
×
3106

3107
                                                srvrLog.Errorf("Unable to "+
×
3108
                                                        "connect to %v: %v",
×
3109
                                                        a, err)
×
3110
                                                atomic.AddUint32(&epochErrors, 1)
×
3111
                                        case <-s.quit:
×
3112
                                        }
3113
                                }(addr)
3114
                        }
3115
                case <-s.quit:
3✔
3116
                        return
3✔
3117
                }
3118
        }
3119
}
3120

3121
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3122
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3123
// query back off each time we encounter a failure.
3124
const bootstrapBackOffCeiling = time.Minute * 5
3125

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

3✔
3133
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3134
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3135

3✔
3136
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3137
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3138
        var delaySignal <-chan time.Time
3✔
3139
        delayTime := time.Second * 2
3✔
3140

3✔
3141
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3142
        // then the main peer bootstrap logic.
3✔
3143
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3144

3✔
3145
        for attempts := 0; ; attempts++ {
6✔
3146
                // Check if the server has been requested to shut down in order
3✔
3147
                // to prevent blocking.
3✔
3148
                if s.Stopped() {
3✔
3149
                        return
×
3150
                }
×
3151

3152
                // We can exit our aggressive initial peer bootstrapping stage
3153
                // if we've reached out target number of peers.
3154
                s.mu.RLock()
3✔
3155
                numActivePeers := uint32(len(s.peersByPub))
3✔
3156
                s.mu.RUnlock()
3✔
3157

3✔
3158
                if numActivePeers >= numTargetPeers {
6✔
3159
                        return
3✔
3160
                }
3✔
3161

3162
                if attempts > 0 {
3✔
3163
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3164
                                "bootstrap peers (attempt #%v)", delayTime,
×
3165
                                attempts)
×
3166

×
3167
                        // We've completed at least one iterating and haven't
×
3168
                        // finished, so we'll start to insert a delay period
×
3169
                        // between each attempt.
×
3170
                        delaySignal = time.After(delayTime)
×
3171
                        select {
×
3172
                        case <-delaySignal:
×
3173
                        case <-s.quit:
×
3174
                                return
×
3175
                        }
3176

3177
                        // After our delay, we'll double the time we wait up to
3178
                        // the max back off period.
3179
                        delayTime *= 2
×
3180
                        if delayTime > backOffCeiling {
×
3181
                                delayTime = backOffCeiling
×
3182
                        }
×
3183
                }
3184

3185
                // Otherwise, we'll request for the remaining number of peers
3186
                // in order to reach our target.
3187
                peersNeeded := numTargetPeers - numActivePeers
3✔
3188
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3189
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3190
                )
3✔
3191
                if err != nil {
3✔
3192
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3193
                                "peers: %v", err)
×
3194
                        continue
×
3195
                }
3196

3197
                // Then, we'll attempt to establish a connection to the
3198
                // different peer addresses retrieved by our bootstrappers.
3199
                var wg sync.WaitGroup
3✔
3200
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3201
                        wg.Add(1)
3✔
3202
                        go func(addr *lnwire.NetAddress) {
6✔
3203
                                defer wg.Done()
3✔
3204

3✔
3205
                                errChan := make(chan error, 1)
3✔
3206
                                go s.connectToPeer(
3✔
3207
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3208
                                )
3✔
3209

3✔
3210
                                // We'll only allow this connection attempt to
3✔
3211
                                // take up to 3 seconds. This allows us to move
3✔
3212
                                // quickly by discarding peers that are slowing
3✔
3213
                                // us down.
3✔
3214
                                select {
3✔
3215
                                case err := <-errChan:
3✔
3216
                                        if err == nil {
6✔
3217
                                                return
3✔
3218
                                        }
3✔
3219
                                        srvrLog.Errorf("Unable to connect to "+
×
3220
                                                "%v: %v", addr, err)
×
3221
                                // TODO: tune timeout? 3 seconds might be *too*
3222
                                // aggressive but works well.
3223
                                case <-time.After(3 * time.Second):
×
3224
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3225
                                                "to not establishing a "+
×
3226
                                                "connection within 3 seconds",
×
3227
                                                addr)
×
3228
                                case <-s.quit:
×
3229
                                }
3230
                        }(bootstrapAddr)
3231
                }
3232

3233
                wg.Wait()
3✔
3234
        }
3235
}
3236

3237
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3238
// order to listen for inbound connections over Tor.
3239
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3240
        // Determine the different ports the server is listening on. The onion
×
3241
        // service's virtual port will map to these ports and one will be picked
×
3242
        // at random when the onion service is being accessed.
×
3243
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3244
        for _, listenAddr := range s.listenAddrs {
×
3245
                port := listenAddr.(*net.TCPAddr).Port
×
3246
                listenPorts = append(listenPorts, port)
×
3247
        }
×
3248

3249
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3250
        if err != nil {
×
3251
                return err
×
3252
        }
×
3253

3254
        // Once the port mapping has been set, we can go ahead and automatically
3255
        // create our onion service. The service's private key will be saved to
3256
        // disk in order to regain access to this service when restarting `lnd`.
3257
        onionCfg := tor.AddOnionConfig{
×
3258
                VirtualPort: defaultPeerPort,
×
3259
                TargetPorts: listenPorts,
×
3260
                Store: tor.NewOnionFile(
×
3261
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3262
                        encrypter,
×
3263
                ),
×
3264
        }
×
3265

×
3266
        switch {
×
3267
        case s.cfg.Tor.V2:
×
3268
                onionCfg.Type = tor.V2
×
3269
        case s.cfg.Tor.V3:
×
3270
                onionCfg.Type = tor.V3
×
3271
        }
3272

3273
        addr, err := s.torController.AddOnion(onionCfg)
×
3274
        if err != nil {
×
3275
                return err
×
3276
        }
×
3277

3278
        // Now that the onion service has been created, we'll add the onion
3279
        // address it can be reached at to our list of advertised addresses.
3280
        newNodeAnn, err := s.genNodeAnnouncement(
×
3281
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3282
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3283
                },
×
3284
        )
3285
        if err != nil {
×
3286
                return fmt.Errorf("unable to generate new node "+
×
3287
                        "announcement: %v", err)
×
3288
        }
×
3289

3290
        // Finally, we'll update the on-disk version of our announcement so it
3291
        // will eventually propagate to nodes in the network.
3292
        selfNode := &models.Node{
×
3293
                HaveNodeAnnouncement: true,
×
3294
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3295
                Addresses:            newNodeAnn.Addresses,
×
3296
                Alias:                newNodeAnn.Alias.String(),
×
3297
                Features: lnwire.NewFeatureVector(
×
3298
                        newNodeAnn.Features, lnwire.Features,
×
3299
                ),
×
3300
                Color:        newNodeAnn.RGBColor,
×
3301
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3302
        }
×
3303
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3304
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3305
                return fmt.Errorf("can't set self node: %w", err)
×
3306
        }
×
3307

3308
        return nil
×
3309
}
3310

3311
// findChannel finds a channel given a public key and ChannelID. It is an
3312
// optimization that is quicker than seeking for a channel given only the
3313
// ChannelID.
3314
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3315
        *channeldb.OpenChannel, error) {
3✔
3316

3✔
3317
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3318
        if err != nil {
3✔
3319
                return nil, err
×
3320
        }
×
3321

3322
        for _, channel := range nodeChans {
6✔
3323
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3324
                        return channel, nil
3✔
3325
                }
3✔
3326
        }
3327

3328
        return nil, fmt.Errorf("unable to find channel")
3✔
3329
}
3330

3331
// getNodeAnnouncement fetches the current, fully signed node announcement.
3332
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
3✔
3333
        s.mu.Lock()
3✔
3334
        defer s.mu.Unlock()
3✔
3335

3✔
3336
        return *s.currentNodeAnn
3✔
3337
}
3✔
3338

3339
// genNodeAnnouncement generates and returns the current fully signed node
3340
// announcement. The time stamp of the announcement will be updated in order
3341
// to ensure it propagates through the network.
3342
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3343
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
3✔
3344

3✔
3345
        s.mu.Lock()
3✔
3346
        defer s.mu.Unlock()
3✔
3347

3✔
3348
        // Create a shallow copy of the current node announcement to work on.
3✔
3349
        // This ensures the original announcement remains unchanged
3✔
3350
        // until the new announcement is fully signed and valid.
3✔
3351
        newNodeAnn := *s.currentNodeAnn
3✔
3352

3✔
3353
        // First, try to update our feature manager with the updated set of
3✔
3354
        // features.
3✔
3355
        if features != nil {
6✔
3356
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3357
                        feature.SetNodeAnn: features,
3✔
3358
                }
3✔
3359
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3360
                if err != nil {
6✔
3361
                        return lnwire.NodeAnnouncement1{}, err
3✔
3362
                }
3✔
3363

3364
                // If we could successfully update our feature manager, add
3365
                // an update modifier to include these new features to our
3366
                // set.
3367
                modifiers = append(
3✔
3368
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3369
                )
3✔
3370
        }
3371

3372
        // Always update the timestamp when refreshing to ensure the update
3373
        // propagates.
3374
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3375

3✔
3376
        // Apply the requested changes to the node announcement.
3✔
3377
        for _, modifier := range modifiers {
6✔
3378
                modifier(&newNodeAnn)
3✔
3379
        }
3✔
3380

3381
        // Sign a new update after applying all of the passed modifiers.
3382
        err := netann.SignNodeAnnouncement(
3✔
3383
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3384
        )
3✔
3385
        if err != nil {
3✔
3386
                return lnwire.NodeAnnouncement1{}, err
×
3387
        }
×
3388

3389
        // If signing succeeds, update the current announcement.
3390
        *s.currentNodeAnn = newNodeAnn
3✔
3391

3✔
3392
        return *s.currentNodeAnn, nil
3✔
3393
}
3394

3395
// updateAndBroadcastSelfNode generates a new node announcement
3396
// applying the giving modifiers and updating the time stamp
3397
// to ensure it propagates through the network. Then it broadcasts
3398
// it to the network.
3399
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3400
        features *lnwire.RawFeatureVector,
3401
        modifiers ...netann.NodeAnnModifier) error {
3✔
3402

3✔
3403
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3404
        if err != nil {
6✔
3405
                return fmt.Errorf("unable to generate new node "+
3✔
3406
                        "announcement: %v", err)
3✔
3407
        }
3✔
3408

3409
        // Update the on-disk version of our announcement.
3410
        // Load and modify self node istead of creating anew instance so we
3411
        // don't risk overwriting any existing values.
3412
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3413
        if err != nil {
3✔
3414
                return fmt.Errorf("unable to get current source node: %w", err)
×
3415
        }
×
3416

3417
        selfNode.HaveNodeAnnouncement = true
3✔
3418
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3419
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3420
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3421
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3422
        selfNode.Color = newNodeAnn.RGBColor
3✔
3423
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3424

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

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

3431
        // Finally, propagate it to the nodes in the network.
3432
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3433
        if err != nil {
3✔
3434
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3435
                        "announcement to peers: %v", err)
×
3436
                return err
×
3437
        }
×
3438

3439
        return nil
3✔
3440
}
3441

3442
type nodeAddresses struct {
3443
        pubKey    *btcec.PublicKey
3444
        addresses []net.Addr
3445
}
3446

3447
// establishPersistentConnections attempts to establish persistent connections
3448
// to all our direct channel collaborators. In order to promote liveness of our
3449
// active channels, we instruct the connection manager to attempt to establish
3450
// and maintain persistent connections to all our direct channel counterparties.
3451
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3452
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3453
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3454
        // since other PubKey forms can't be compared.
3✔
3455
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3456

3✔
3457
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3458
        // attempt to connect to based on our set of previous connections. Set
3✔
3459
        // the reconnection port to the default peer port.
3✔
3460
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3461
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3462
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3463
        }
×
3464

3465
        for _, node := range linkNodes {
6✔
3466
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3467
                nodeAddrs := &nodeAddresses{
3✔
3468
                        pubKey:    node.IdentityPub,
3✔
3469
                        addresses: node.Addresses,
3✔
3470
                }
3✔
3471
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3472
        }
3✔
3473

3474
        // After checking our previous connections for addresses to connect to,
3475
        // iterate through the nodes in our channel graph to find addresses
3476
        // that have been added via NodeAnnouncement1 messages.
3477
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3478
        // each of the nodes.
3479
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3480
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3481
                havePolicy bool, channelPeer *models.Node) error {
6✔
3482

3✔
3483
                // If the remote party has announced the channel to us, but we
3✔
3484
                // haven't yet, then we won't have a policy. However, we don't
3✔
3485
                // need this to connect to the peer, so we'll log it and move on.
3✔
3486
                if !havePolicy {
3✔
3487
                        srvrLog.Warnf("No channel policy found for "+
×
3488
                                "ChannelPoint(%v): ", chanPoint)
×
3489
                }
×
3490

3491
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3492

3✔
3493
                // Add all unique addresses from channel
3✔
3494
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3495
                // connect to for this peer.
3✔
3496
                addrSet := make(map[string]net.Addr)
3✔
3497
                for _, addr := range channelPeer.Addresses {
6✔
3498
                        switch addr.(type) {
3✔
3499
                        case *net.TCPAddr:
3✔
3500
                                addrSet[addr.String()] = addr
3✔
3501

3502
                        // We'll only attempt to connect to Tor addresses if Tor
3503
                        // outbound support is enabled.
3504
                        case *tor.OnionAddr:
×
3505
                                if s.cfg.Tor.Active {
×
3506
                                        addrSet[addr.String()] = addr
×
3507
                                }
×
3508
                        }
3509
                }
3510

3511
                // If this peer is also recorded as a link node, we'll add any
3512
                // additional addresses that have not already been selected.
3513
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3514
                if ok {
6✔
3515
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3516
                                switch lnAddress.(type) {
3✔
3517
                                case *net.TCPAddr:
3✔
3518
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3519

3520
                                // We'll only attempt to connect to Tor
3521
                                // addresses if Tor outbound support is enabled.
3522
                                case *tor.OnionAddr:
×
3523
                                        if s.cfg.Tor.Active {
×
3524
                                                //nolint:ll
×
3525
                                                addrSet[lnAddress.String()] = lnAddress
×
3526
                                        }
×
3527
                                }
3528
                        }
3529
                }
3530

3531
                // Construct a slice of the deduped addresses.
3532
                var addrs []net.Addr
3✔
3533
                for _, addr := range addrSet {
6✔
3534
                        addrs = append(addrs, addr)
3✔
3535
                }
3✔
3536

3537
                n := &nodeAddresses{
3✔
3538
                        addresses: addrs,
3✔
3539
                }
3✔
3540
                n.pubKey, err = channelPeer.PubKey()
3✔
3541
                if err != nil {
3✔
3542
                        return err
×
3543
                }
×
3544

3545
                graphAddrs[pubStr] = n
3✔
3546
                return nil
3✔
3547
        }
3548
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3549
                ctx, forEachSrcNodeChan, func() {
6✔
3550
                        clear(graphAddrs)
3✔
3551
                },
3✔
3552
        )
3553
        if err != nil {
3✔
3554
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3555
                        "%v", err)
×
3556

×
3557
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3558
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3559

×
3560
                        return err
×
3561
                }
×
3562
        }
3563

3564
        // Combine the addresses from the link nodes and the channel graph.
3565
        for pubStr, nodeAddr := range graphAddrs {
6✔
3566
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3567
        }
3✔
3568

3569
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3570
                len(nodeAddrsMap))
3✔
3571

3✔
3572
        // Acquire and hold server lock until all persistent connection requests
3✔
3573
        // have been recorded and sent to the connection manager.
3✔
3574
        s.mu.Lock()
3✔
3575
        defer s.mu.Unlock()
3✔
3576

3✔
3577
        // Iterate through the combined list of addresses from prior links and
3✔
3578
        // node announcements and attempt to reconnect to each node.
3✔
3579
        var numOutboundConns int
3✔
3580
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3581
                // Add this peer to the set of peers we should maintain a
3✔
3582
                // persistent connection with. We set the value to false to
3✔
3583
                // indicate that we should not continue to reconnect if the
3✔
3584
                // number of channels returns to zero, since this peer has not
3✔
3585
                // been requested as perm by the user.
3✔
3586
                s.persistentPeers[pubStr] = false
3✔
3587
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3588
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3589
                }
3✔
3590

3591
                for _, address := range nodeAddr.addresses {
6✔
3592
                        // Create a wrapper address which couples the IP and
3✔
3593
                        // the pubkey so the brontide authenticated connection
3✔
3594
                        // can be established.
3✔
3595
                        lnAddr := &lnwire.NetAddress{
3✔
3596
                                IdentityKey: nodeAddr.pubKey,
3✔
3597
                                Address:     address,
3✔
3598
                        }
3✔
3599

3✔
3600
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3601
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3602
                }
3✔
3603

3604
                // We'll connect to the first 10 peers immediately, then
3605
                // randomly stagger any remaining connections if the
3606
                // stagger initial reconnect flag is set. This ensures
3607
                // that mobile nodes or nodes with a small number of
3608
                // channels obtain connectivity quickly, but larger
3609
                // nodes are able to disperse the costs of connecting to
3610
                // all peers at once.
3611
                if numOutboundConns < numInstantInitReconnect ||
3✔
3612
                        !s.cfg.StaggerInitialReconnect {
6✔
3613

3✔
3614
                        go s.connectToPersistentPeer(pubStr)
3✔
3615
                } else {
3✔
3616
                        go s.delayInitialReconnect(pubStr)
×
3617
                }
×
3618

3619
                numOutboundConns++
3✔
3620
        }
3621

3622
        return nil
3✔
3623
}
3624

3625
// delayInitialReconnect will attempt a reconnection to the given peer after
3626
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3627
//
3628
// NOTE: This method MUST be run as a goroutine.
3629
func (s *server) delayInitialReconnect(pubStr string) {
×
3630
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3631
        select {
×
3632
        case <-time.After(delay):
×
3633
                s.connectToPersistentPeer(pubStr)
×
3634
        case <-s.quit:
×
3635
        }
3636
}
3637

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

3✔
3644
        s.mu.Lock()
3✔
3645
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3646
                delete(s.persistentPeers, pubKeyStr)
3✔
3647
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3648
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3649
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3650
                s.mu.Unlock()
3✔
3651

3✔
3652
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3653
                        "peer has no open channels", compressedPubKey)
3✔
3654

3✔
3655
                return
3✔
3656
        }
3✔
3657
        s.mu.Unlock()
3✔
3658
}
3659

3660
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3661
// is instead used to remove persistent peer state for a peer that has been
3662
// disconnected for good cause by the server. Currently, a gossip ban from
3663
// sending garbage and the server running out of restricted-access
3664
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3665
// future, this function may expand when more ban criteria is added.
3666
//
3667
// NOTE: The server's write lock MUST be held when this is called.
3668
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3669
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3670
                delete(s.persistentPeers, remotePub)
×
3671
                delete(s.persistentPeersBackoff, remotePub)
×
3672
                delete(s.persistentPeerAddrs, remotePub)
×
3673
                s.cancelConnReqs(remotePub, nil)
×
3674
        }
×
3675
}
3676

3677
// BroadcastMessage sends a request to the server to broadcast a set of
3678
// messages to all peers other than the one specified by the `skips` parameter.
3679
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3680
// the target peers.
3681
//
3682
// NOTE: This function is safe for concurrent access.
3683
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3684
        msgs ...lnwire.Message) error {
3✔
3685

3✔
3686
        // Filter out peers found in the skips map. We synchronize access to
3✔
3687
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3688
        // exact set of peers present at the time of invocation.
3✔
3689
        s.mu.RLock()
3✔
3690
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3691
        for pubStr, sPeer := range s.peersByPub {
6✔
3692
                if skips != nil {
6✔
3693
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3694
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3695
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3696
                                continue
3✔
3697
                        }
3698
                }
3699

3700
                peers = append(peers, sPeer)
3✔
3701
        }
3702
        s.mu.RUnlock()
3✔
3703

3✔
3704
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3705
        // all messages to each of peers.
3✔
3706
        var wg sync.WaitGroup
3✔
3707
        for _, sPeer := range peers {
6✔
3708
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3709
                        sPeer.PubKey())
3✔
3710

3✔
3711
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3712
                wg.Add(1)
3✔
3713
                s.wg.Add(1)
3✔
3714
                go func(p lnpeer.Peer) {
6✔
3715
                        defer s.wg.Done()
3✔
3716
                        defer wg.Done()
3✔
3717

3✔
3718
                        p.SendMessageLazy(false, msgs...)
3✔
3719
                }(sPeer)
3✔
3720
        }
3721

3722
        // Wait for all messages to have been dispatched before returning to
3723
        // caller.
3724
        wg.Wait()
3✔
3725

3✔
3726
        return nil
3✔
3727
}
3728

3729
// NotifyWhenOnline can be called by other subsystems to get notified when a
3730
// particular peer comes online. The peer itself is sent across the peerChan.
3731
//
3732
// NOTE: This function is safe for concurrent access.
3733
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3734
        peerChan chan<- lnpeer.Peer) {
3✔
3735

3✔
3736
        s.mu.Lock()
3✔
3737

3✔
3738
        // Compute the target peer's identifier.
3✔
3739
        pubStr := string(peerKey[:])
3✔
3740

3✔
3741
        // Check if peer is connected.
3✔
3742
        peer, ok := s.peersByPub[pubStr]
3✔
3743
        if ok {
6✔
3744
                // Unlock here so that the mutex isn't held while we are
3✔
3745
                // waiting for the peer to become active.
3✔
3746
                s.mu.Unlock()
3✔
3747

3✔
3748
                // Wait until the peer signals that it is actually active
3✔
3749
                // rather than only in the server's maps.
3✔
3750
                select {
3✔
3751
                case <-peer.ActiveSignal():
3✔
3752
                case <-peer.QuitSignal():
×
3753
                        // The peer quit, so we'll add the channel to the slice
×
3754
                        // and return.
×
3755
                        s.mu.Lock()
×
3756
                        s.peerConnectedListeners[pubStr] = append(
×
3757
                                s.peerConnectedListeners[pubStr], peerChan,
×
3758
                        )
×
3759
                        s.mu.Unlock()
×
3760
                        return
×
3761
                }
3762

3763
                // Connected, can return early.
3764
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3765

3✔
3766
                select {
3✔
3767
                case peerChan <- peer:
3✔
3768
                case <-s.quit:
×
3769
                }
3770

3771
                return
3✔
3772
        }
3773

3774
        // Not connected, store this listener such that it can be notified when
3775
        // the peer comes online.
3776
        s.peerConnectedListeners[pubStr] = append(
3✔
3777
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3778
        )
3✔
3779
        s.mu.Unlock()
3✔
3780
}
3781

3782
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3783
// the given public key has been disconnected. The notification is signaled by
3784
// closing the channel returned.
3785
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3786
        s.mu.Lock()
3✔
3787
        defer s.mu.Unlock()
3✔
3788

3✔
3789
        c := make(chan struct{})
3✔
3790

3✔
3791
        // If the peer is already offline, we can immediately trigger the
3✔
3792
        // notification.
3✔
3793
        peerPubKeyStr := string(peerPubKey[:])
3✔
3794
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3795
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3796
                close(c)
×
3797
                return c
×
3798
        }
×
3799

3800
        // Otherwise, the peer is online, so we'll keep track of the channel to
3801
        // trigger the notification once the server detects the peer
3802
        // disconnects.
3803
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3804
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3805
        )
3✔
3806

3✔
3807
        return c
3✔
3808
}
3809

3810
// FindPeer will return the peer that corresponds to the passed in public key.
3811
// This function is used by the funding manager, allowing it to update the
3812
// daemon's local representation of the remote peer.
3813
//
3814
// NOTE: This function is safe for concurrent access.
3815
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3816
        s.mu.RLock()
3✔
3817
        defer s.mu.RUnlock()
3✔
3818

3✔
3819
        pubStr := string(peerKey.SerializeCompressed())
3✔
3820

3✔
3821
        return s.findPeerByPubStr(pubStr)
3✔
3822
}
3✔
3823

3824
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3825
// which should be a string representation of the peer's serialized, compressed
3826
// public key.
3827
//
3828
// NOTE: This function is safe for concurrent access.
3829
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3830
        s.mu.RLock()
3✔
3831
        defer s.mu.RUnlock()
3✔
3832

3✔
3833
        return s.findPeerByPubStr(pubStr)
3✔
3834
}
3✔
3835

3836
// findPeerByPubStr is an internal method that retrieves the specified peer from
3837
// the server's internal state using.
3838
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3839
        peer, ok := s.peersByPub[pubStr]
3✔
3840
        if !ok {
6✔
3841
                return nil, ErrPeerNotConnected
3✔
3842
        }
3✔
3843

3844
        return peer, nil
3✔
3845
}
3846

3847
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3848
// exponential backoff. If no previous backoff was known, the default is
3849
// returned.
3850
func (s *server) nextPeerBackoff(pubStr string,
3851
        startTime time.Time) time.Duration {
3✔
3852

3✔
3853
        // Now, determine the appropriate backoff to use for the retry.
3✔
3854
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3855
        if !ok {
6✔
3856
                // If an existing backoff was unknown, use the default.
3✔
3857
                return s.cfg.MinBackoff
3✔
3858
        }
3✔
3859

3860
        // If the peer failed to start properly, we'll just use the previous
3861
        // backoff to compute the subsequent randomized exponential backoff
3862
        // duration. This will roughly double on average.
3863
        if startTime.IsZero() {
3✔
3864
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3865
        }
×
3866

3867
        // The peer succeeded in starting. If the connection didn't last long
3868
        // enough to be considered stable, we'll continue to back off retries
3869
        // with this peer.
3870
        connDuration := time.Since(startTime)
3✔
3871
        if connDuration < defaultStableConnDuration {
6✔
3872
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3873
        }
3✔
3874

3875
        // The peer succeed in starting and this was stable peer, so we'll
3876
        // reduce the timeout duration by the length of the connection after
3877
        // applying randomized exponential backoff. We'll only apply this in the
3878
        // case that:
3879
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3880
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3881
        if relaxedBackoff > s.cfg.MinBackoff {
×
3882
                return relaxedBackoff
×
3883
        }
×
3884

3885
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3886
        // the stable connection lasted much longer than our previous backoff.
3887
        // To reward such good behavior, we'll reconnect after the default
3888
        // timeout.
3889
        return s.cfg.MinBackoff
×
3890
}
3891

3892
// shouldDropLocalConnection determines if our local connection to a remote peer
3893
// should be dropped in the case of concurrent connection establishment. In
3894
// order to deterministically decide which connection should be dropped, we'll
3895
// utilize the ordering of the local and remote public key. If we didn't use
3896
// such a tie breaker, then we risk _both_ connections erroneously being
3897
// dropped.
3898
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3899
        localPubBytes := local.SerializeCompressed()
×
3900
        remotePubPbytes := remote.SerializeCompressed()
×
3901

×
3902
        // The connection that comes from the node with a "smaller" pubkey
×
3903
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3904
        // should drop our established connection.
×
3905
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3906
}
×
3907

3908
// InboundPeerConnected initializes a new peer in response to a new inbound
3909
// connection.
3910
//
3911
// NOTE: This function is safe for concurrent access.
3912
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3913
        // Exit early if we have already been instructed to shutdown, this
3✔
3914
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3915
        if s.Stopped() {
3✔
3916
                return
×
3917
        }
×
3918

3919
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3920
        pubSer := nodePub.SerializeCompressed()
3✔
3921
        pubStr := string(pubSer)
3✔
3922

3✔
3923
        var pubBytes [33]byte
3✔
3924
        copy(pubBytes[:], pubSer)
3✔
3925

3✔
3926
        s.mu.Lock()
3✔
3927
        defer s.mu.Unlock()
3✔
3928

3✔
3929
        // If we already have an outbound connection to this peer, then ignore
3✔
3930
        // this new connection.
3✔
3931
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3932
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3933
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3934
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3935

3✔
3936
                conn.Close()
3✔
3937
                return
3✔
3938
        }
3✔
3939

3940
        // If we already have a valid connection that is scheduled to take
3941
        // precedence once the prior peer has finished disconnecting, we'll
3942
        // ignore this connection.
3943
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
3944
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3945
                        "scheduled", conn.RemoteAddr(), p)
×
3946
                conn.Close()
×
3947
                return
×
3948
        }
×
3949

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

3✔
3952
        // Check to see if we already have a connection with this peer. If so,
3✔
3953
        // we may need to drop our existing connection. This prevents us from
3✔
3954
        // having duplicate connections to the same peer. We forgo adding a
3✔
3955
        // default case as we expect these to be the only error values returned
3✔
3956
        // from findPeerByPubStr.
3✔
3957
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
3958
        switch err {
3✔
3959
        case ErrPeerNotConnected:
3✔
3960
                // We were unable to locate an existing connection with the
3✔
3961
                // target peer, proceed to connect.
3✔
3962
                s.cancelConnReqs(pubStr, nil)
3✔
3963
                s.peerConnected(conn, nil, true)
3✔
3964

3965
        case nil:
3✔
3966
                ctx := btclog.WithCtx(
3✔
3967
                        context.TODO(),
3✔
3968
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
3969
                )
3✔
3970

3✔
3971
                // We already have a connection with the incoming peer. If the
3✔
3972
                // connection we've already established should be kept and is
3✔
3973
                // not of the same type of the new connection (inbound), then
3✔
3974
                // we'll close out the new connection s.t there's only a single
3✔
3975
                // connection between us.
3✔
3976
                localPub := s.identityECDH.PubKey()
3✔
3977
                if !connectedPeer.Inbound() &&
3✔
3978
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
3979

×
3980
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
3981
                                "peer, but already have outbound "+
×
3982
                                "connection, dropping conn",
×
3983
                                fmt.Errorf("already have outbound conn"))
×
3984
                        conn.Close()
×
3985
                        return
×
3986
                }
×
3987

3988
                // Otherwise, if we should drop the connection, then we'll
3989
                // disconnect our already connected peer.
3990
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
3991

3✔
3992
                s.cancelConnReqs(pubStr, nil)
3✔
3993

3✔
3994
                // Remove the current peer from the server's internal state and
3✔
3995
                // signal that the peer termination watcher does not need to
3✔
3996
                // execute for this peer.
3✔
3997
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
3998
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
3999
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4000
                        s.peerConnected(conn, nil, true)
3✔
4001
                }
3✔
4002
        }
4003
}
4004

4005
// OutboundPeerConnected initializes a new peer in response to a new outbound
4006
// connection.
4007
// NOTE: This function is safe for concurrent access.
4008
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4009
        // Exit early if we have already been instructed to shutdown, this
3✔
4010
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4011
        if s.Stopped() {
3✔
4012
                return
×
4013
        }
×
4014

4015
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4016
        pubSer := nodePub.SerializeCompressed()
3✔
4017
        pubStr := string(pubSer)
3✔
4018

3✔
4019
        var pubBytes [33]byte
3✔
4020
        copy(pubBytes[:], pubSer)
3✔
4021

3✔
4022
        s.mu.Lock()
3✔
4023
        defer s.mu.Unlock()
3✔
4024

3✔
4025
        // If we already have an inbound connection to this peer, then ignore
3✔
4026
        // this new connection.
3✔
4027
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4028
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4029
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4030
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4031

3✔
4032
                if connReq != nil {
6✔
4033
                        s.connMgr.Remove(connReq.ID())
3✔
4034
                }
3✔
4035
                conn.Close()
3✔
4036
                return
3✔
4037
        }
4038
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4039
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4040
                s.connMgr.Remove(connReq.ID())
×
4041
                conn.Close()
×
4042
                return
×
4043
        }
×
4044

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

×
4051
                if connReq != nil {
×
4052
                        s.connMgr.Remove(connReq.ID())
×
4053
                }
×
4054

4055
                conn.Close()
×
4056
                return
×
4057
        }
4058

4059
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4060
                conn.RemoteAddr())
3✔
4061

3✔
4062
        if connReq != nil {
6✔
4063
                // A successful connection was returned by the connmgr.
3✔
4064
                // Immediately cancel all pending requests, excluding the
3✔
4065
                // outbound connection we just established.
3✔
4066
                ignore := connReq.ID()
3✔
4067
                s.cancelConnReqs(pubStr, &ignore)
3✔
4068
        } else {
6✔
4069
                // This was a successful connection made by some other
3✔
4070
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4071
                s.cancelConnReqs(pubStr, nil)
3✔
4072
        }
3✔
4073

4074
        // If we already have a connection with this peer, decide whether or not
4075
        // we need to drop the stale connection. We forgo adding a default case
4076
        // as we expect these to be the only error values returned from
4077
        // findPeerByPubStr.
4078
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4079
        switch err {
3✔
4080
        case ErrPeerNotConnected:
3✔
4081
                // We were unable to locate an existing connection with the
3✔
4082
                // target peer, proceed to connect.
3✔
4083
                s.peerConnected(conn, connReq, false)
3✔
4084

4085
        case nil:
3✔
4086
                ctx := btclog.WithCtx(
3✔
4087
                        context.TODO(),
3✔
4088
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4089
                )
3✔
4090

3✔
4091
                // We already have a connection with the incoming peer. If the
3✔
4092
                // connection we've already established should be kept and is
3✔
4093
                // not of the same type of the new connection (outbound), then
3✔
4094
                // we'll close out the new connection s.t there's only a single
3✔
4095
                // connection between us.
3✔
4096
                localPub := s.identityECDH.PubKey()
3✔
4097
                if connectedPeer.Inbound() &&
3✔
4098
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4099

×
4100
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4101
                                "to peer, but already have inbound "+
×
4102
                                "connection, dropping conn",
×
4103
                                fmt.Errorf("already have inbound conn"))
×
4104
                        if connReq != nil {
×
4105
                                s.connMgr.Remove(connReq.ID())
×
4106
                        }
×
4107
                        conn.Close()
×
4108
                        return
×
4109
                }
4110

4111
                // Otherwise, _their_ connection should be dropped. So we'll
4112
                // disconnect the peer and send the now obsolete peer to the
4113
                // server for garbage collection.
4114
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4115

3✔
4116
                // Remove the current peer from the server's internal state and
3✔
4117
                // signal that the peer termination watcher does not need to
3✔
4118
                // execute for this peer.
3✔
4119
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4120
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4121
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4122
                        s.peerConnected(conn, connReq, false)
3✔
4123
                }
3✔
4124
        }
4125
}
4126

4127
// UnassignedConnID is the default connection ID that a request can have before
4128
// it actually is submitted to the connmgr.
4129
// TODO(conner): move into connmgr package, or better, add connmgr method for
4130
// generating atomic IDs
4131
const UnassignedConnID uint64 = 0
4132

4133
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4134
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4135
// Afterwards, each connection request removed from the connmgr. The caller can
4136
// optionally specify a connection ID to ignore, which prevents us from
4137
// canceling a successful request. All persistent connreqs for the provided
4138
// pubkey are discarded after the operationjw.
4139
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4140
        // First, cancel any lingering persistent retry attempts, which will
3✔
4141
        // prevent retries for any with backoffs that are still maturing.
3✔
4142
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4143
                close(cancelChan)
3✔
4144
                delete(s.persistentRetryCancels, pubStr)
3✔
4145
        }
3✔
4146

4147
        // Next, check to see if we have any outstanding persistent connection
4148
        // requests to this peer. If so, then we'll remove all of these
4149
        // connection requests, and also delete the entry from the map.
4150
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4151
        if !ok {
6✔
4152
                return
3✔
4153
        }
3✔
4154

4155
        for _, connReq := range connReqs {
6✔
4156
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4157

3✔
4158
                // Atomically capture the current request identifier.
3✔
4159
                connID := connReq.ID()
3✔
4160

3✔
4161
                // Skip any zero IDs, this indicates the request has not
3✔
4162
                // yet been schedule.
3✔
4163
                if connID == UnassignedConnID {
3✔
4164
                        continue
×
4165
                }
4166

4167
                // Skip a particular connection ID if instructed.
4168
                if skip != nil && connID == *skip {
6✔
4169
                        continue
3✔
4170
                }
4171

4172
                s.connMgr.Remove(connID)
3✔
4173
        }
4174

4175
        delete(s.persistentConnReqs, pubStr)
3✔
4176
}
4177

4178
// handleCustomMessage dispatches an incoming custom peers message to
4179
// subscribers.
4180
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4181
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4182
                peer, msg.Type)
3✔
4183

3✔
4184
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4185
                Peer: peer,
3✔
4186
                Msg:  msg,
3✔
4187
        })
3✔
4188
}
3✔
4189

4190
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4191
// messages.
4192
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4193
        return s.customMessageServer.Subscribe()
3✔
4194
}
3✔
4195

4196
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4197
// the channelNotifier's NotifyOpenChannelEvent.
4198
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4199
        remotePub *btcec.PublicKey) {
3✔
4200

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

4207
        // Notify subscribers about this open channel event.
4208
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4209
}
4210

4211
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4212
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4213
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4214
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4215

3✔
4216
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4217
        // peer.
3✔
4218
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4219
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4220
                        "channel[%v] pending open",
×
4221
                        remotePub.SerializeCompressed(), op)
×
4222
        }
×
4223

4224
        // Notify subscribers about this event.
4225
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4226
}
4227

4228
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4229
// calls the channelNotifier's NotifyFundingTimeout.
4230
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4231
        remotePub *btcec.PublicKey) {
3✔
4232

3✔
4233
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4234
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4235
        if err != nil {
3✔
4236
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4237
                        "channel[%v] pending close",
×
4238
                        remotePub.SerializeCompressed(), op)
×
4239
        }
×
4240

4241
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4242
                // If we encounter an error while attempting to disconnect the
×
4243
                // peer, log the error.
×
4244
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4245
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4246
                }
×
4247
        }
4248

4249
        // Notify subscribers about this event.
4250
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4251
}
4252

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

3✔
4260
        brontideConn := conn.(*brontide.Conn)
3✔
4261
        addr := conn.RemoteAddr()
3✔
4262
        pubKey := brontideConn.RemotePub()
3✔
4263

3✔
4264
        // Only restrict access for inbound connections, which means if the
3✔
4265
        // remote node's public key is banned or the restricted slots are used
3✔
4266
        // up, we will drop the connection.
3✔
4267
        //
3✔
4268
        // TODO(yy): Consider perform this check in
3✔
4269
        // `peerAccessMan.addPeerAccess`.
3✔
4270
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4271
        if inbound && err != nil {
3✔
4272
                pubSer := pubKey.SerializeCompressed()
×
4273

×
4274
                // Clean up the persistent peer maps if we're dropping this
×
4275
                // connection.
×
4276
                s.bannedPersistentPeerConnection(string(pubSer))
×
4277

×
4278
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4279
                        "of restricted-access connection slots: %v.", pubSer,
×
4280
                        err)
×
4281

×
4282
                conn.Close()
×
4283

×
4284
                return
×
4285
        }
×
4286

4287
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4288
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4289

3✔
4290
        peerAddr := &lnwire.NetAddress{
3✔
4291
                IdentityKey: pubKey,
3✔
4292
                Address:     addr,
3✔
4293
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4294
        }
3✔
4295

3✔
4296
        // With the brontide connection established, we'll now craft the feature
3✔
4297
        // vectors to advertise to the remote node.
3✔
4298
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4299
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4300

3✔
4301
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4302
        // found, create a fresh buffer.
3✔
4303
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4304
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4305
        if !ok {
6✔
4306
                var err error
3✔
4307
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4308
                if err != nil {
3✔
4309
                        srvrLog.Errorf("unable to create peer %v", err)
×
4310
                        return
×
4311
                }
×
4312
        }
4313

4314
        // If we directly set the peer.Config TowerClient member to the
4315
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4316
        // the peer.Config's TowerClient member will not evaluate to nil even
4317
        // though the underlying value is nil. To avoid this gotcha which can
4318
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4319
        // TowerClient if needed.
4320
        var towerClient wtclient.ClientManager
3✔
4321
        if s.towerClientMgr != nil {
6✔
4322
                towerClient = s.towerClientMgr
3✔
4323
        }
3✔
4324

4325
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4326
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4327

3✔
4328
        // Now that we've established a connection, create a peer, and it to the
3✔
4329
        // set of currently active peers. Configure the peer with the incoming
3✔
4330
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4331
        // offered that would trigger channel closure. In case of outgoing
3✔
4332
        // htlcs, an extra block is added to prevent the channel from being
3✔
4333
        // closed when the htlc is outstanding and a new block comes in.
3✔
4334
        pCfg := peer.Config{
3✔
4335
                Conn:                    brontideConn,
3✔
4336
                ConnReq:                 connReq,
3✔
4337
                Addr:                    peerAddr,
3✔
4338
                Inbound:                 inbound,
3✔
4339
                Features:                initFeatures,
3✔
4340
                LegacyFeatures:          legacyFeatures,
3✔
4341
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4342
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4343
                ErrorBuffer:             errBuffer,
3✔
4344
                WritePool:               s.writePool,
3✔
4345
                ReadPool:                s.readPool,
3✔
4346
                Switch:                  s.htlcSwitch,
3✔
4347
                InterceptSwitch:         s.interceptableSwitch,
3✔
4348
                ChannelDB:               s.chanStateDB,
3✔
4349
                ChannelGraph:            s.graphDB,
3✔
4350
                ChainArb:                s.chainArb,
3✔
4351
                AuthGossiper:            s.authGossiper,
3✔
4352
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4353
                ChainIO:                 s.cc.ChainIO,
3✔
4354
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4355
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4356
                SigPool:                 s.sigPool,
3✔
4357
                Wallet:                  s.cc.Wallet,
3✔
4358
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4359
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4360
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4361
                Sphinx:                  s.sphinx,
3✔
4362
                WitnessBeacon:           s.witnessBeacon,
3✔
4363
                Invoices:                s.invoices,
3✔
4364
                ChannelNotifier:         s.channelNotifier,
3✔
4365
                HtlcNotifier:            s.htlcNotifier,
3✔
4366
                TowerClient:             towerClient,
3✔
4367
                DisconnectPeer:          s.DisconnectPeer,
3✔
4368
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4369
                        lnwire.NodeAnnouncement1, error) {
6✔
4370

3✔
4371
                        return s.genNodeAnnouncement(nil)
3✔
4372
                },
3✔
4373

4374
                PongBuf: s.pongBuf,
4375

4376
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4377

4378
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4379

4380
                FundingManager: s.fundingMgr,
4381

4382
                Hodl:                    s.cfg.Hodl,
4383
                UnsafeReplay:            s.cfg.UnsafeReplay,
4384
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4385
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4386
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4387
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4388
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4389
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4390
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4391
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4392
                HandleCustomMessage:    s.handleCustomMessage,
4393
                GetAliases:             s.aliasMgr.GetAliases,
4394
                RequestAlias:           s.aliasMgr.RequestAlias,
4395
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4396
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4397
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4398
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4399
                MaxFeeExposure:         thresholdMSats,
4400
                Quit:                   s.quit,
4401
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4402
                AuxSigner:              s.implCfg.AuxSigner,
4403
                MsgRouter:              s.implCfg.MsgRouter,
4404
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4405
                AuxResolver:            s.implCfg.AuxContractResolver,
4406
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4407
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4408
                ShouldFwdExpEndorsement: func() bool {
3✔
4409
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4410
                                return false
3✔
4411
                        }
3✔
4412

4413
                        return clock.NewDefaultClock().Now().Before(
3✔
4414
                                EndorsementExperimentEnd,
3✔
4415
                        )
3✔
4416
                },
4417
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4418
        }
4419

4420
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4421
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4422

3✔
4423
        p := peer.NewBrontide(pCfg)
3✔
4424

3✔
4425
        // Update the access manager with the access permission for this peer.
3✔
4426
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4427

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

3✔
4431
        s.addPeer(p)
3✔
4432

3✔
4433
        // Once we have successfully added the peer to the server, we can
3✔
4434
        // delete the previous error buffer from the server's map of error
3✔
4435
        // buffers.
3✔
4436
        delete(s.peerErrors, pkStr)
3✔
4437

3✔
4438
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4439
        // includes sending and receiving Init messages, which would be a DOS
3✔
4440
        // vector if we held the server's mutex throughout the procedure.
3✔
4441
        s.wg.Add(1)
3✔
4442
        go s.peerInitializer(p)
3✔
4443
}
4444

4445
// addPeer adds the passed peer to the server's global state of all active
4446
// peers.
4447
func (s *server) addPeer(p *peer.Brontide) {
3✔
4448
        if p == nil {
3✔
4449
                return
×
4450
        }
×
4451

4452
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4453

3✔
4454
        // Ignore new peers if we're shutting down.
3✔
4455
        if s.Stopped() {
3✔
4456
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4457
                        pubBytes)
×
4458
                p.Disconnect(ErrServerShuttingDown)
×
4459

×
4460
                return
×
4461
        }
×
4462

4463
        // Track the new peer in our indexes so we can quickly look it up either
4464
        // according to its public key, or its peer ID.
4465
        // TODO(roasbeef): pipe all requests through to the
4466
        // queryHandler/peerManager
4467

4468
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4469
        // be human-readable.
4470
        pubStr := string(pubBytes)
3✔
4471

3✔
4472
        s.peersByPub[pubStr] = p
3✔
4473

3✔
4474
        if p.Inbound() {
6✔
4475
                s.inboundPeers[pubStr] = p
3✔
4476
        } else {
6✔
4477
                s.outboundPeers[pubStr] = p
3✔
4478
        }
3✔
4479

4480
        // Inform the peer notifier of a peer online event so that it can be reported
4481
        // to clients listening for peer events.
4482
        var pubKey [33]byte
3✔
4483
        copy(pubKey[:], pubBytes)
3✔
4484
}
4485

4486
// peerInitializer asynchronously starts a newly connected peer after it has
4487
// been added to the server's peer map. This method sets up a
4488
// peerTerminationWatcher for the given peer, and ensures that it executes even
4489
// if the peer failed to start. In the event of a successful connection, this
4490
// method reads the negotiated, local feature-bits and spawns the appropriate
4491
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4492
// be signaled of the new peer once the method returns.
4493
//
4494
// NOTE: This MUST be launched as a goroutine.
4495
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4496
        defer s.wg.Done()
3✔
4497

3✔
4498
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4499

3✔
4500
        // Avoid initializing peers while the server is exiting.
3✔
4501
        if s.Stopped() {
3✔
4502
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4503
                        pubBytes)
×
4504
                return
×
4505
        }
×
4506

4507
        // Create a channel that will be used to signal a successful start of
4508
        // the link. This prevents the peer termination watcher from beginning
4509
        // its duty too early.
4510
        ready := make(chan struct{})
3✔
4511

3✔
4512
        // Before starting the peer, launch a goroutine to watch for the
3✔
4513
        // unexpected termination of this peer, which will ensure all resources
3✔
4514
        // are properly cleaned up, and re-establish persistent connections when
3✔
4515
        // necessary. The peer termination watcher will be short circuited if
3✔
4516
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4517
        // that the server has already handled the removal of this peer.
3✔
4518
        s.wg.Add(1)
3✔
4519
        go s.peerTerminationWatcher(p, ready)
3✔
4520

3✔
4521
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4522
        // will unblock the peerTerminationWatcher.
3✔
4523
        if err := p.Start(); err != nil {
6✔
4524
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4525

3✔
4526
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4527
                return
3✔
4528
        }
3✔
4529

4530
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4531
        // was successful, and to begin watching the peer's wait group.
4532
        close(ready)
3✔
4533

3✔
4534
        s.mu.Lock()
3✔
4535
        defer s.mu.Unlock()
3✔
4536

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

3✔
4540
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4541
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4542
        pubStr := string(pubBytes)
3✔
4543
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4544
                select {
3✔
4545
                case peerChan <- p:
3✔
4546
                case <-s.quit:
×
4547
                        return
×
4548
                }
4549
        }
4550
        delete(s.peerConnectedListeners, pubStr)
3✔
4551

3✔
4552
        // Since the peer has been fully initialized, now it's time to notify
3✔
4553
        // the RPC about the peer online event.
3✔
4554
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4555
}
4556

4557
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4558
// and then cleans up all resources allocated to the peer, notifies relevant
4559
// sub-systems of its demise, and finally handles re-connecting to the peer if
4560
// it's persistent. If the server intentionally disconnects a peer, it should
4561
// have a corresponding entry in the ignorePeerTermination map which will cause
4562
// the cleanup routine to exit early. The passed `ready` chan is used to
4563
// synchronize when WaitForDisconnect should begin watching on the peer's
4564
// waitgroup. The ready chan should only be signaled if the peer starts
4565
// successfully, otherwise the peer should be disconnected instead.
4566
//
4567
// NOTE: This MUST be launched as a goroutine.
4568
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4569
        defer s.wg.Done()
3✔
4570

3✔
4571
        ctx := btclog.WithCtx(
3✔
4572
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4573
        )
3✔
4574

3✔
4575
        p.WaitForDisconnect(ready)
3✔
4576

3✔
4577
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4578

3✔
4579
        // If the server is exiting then we can bail out early ourselves as all
3✔
4580
        // the other sub-systems will already be shutting down.
3✔
4581
        if s.Stopped() {
6✔
4582
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4583
                return
3✔
4584
        }
3✔
4585

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

3✔
4592
        pubKey := p.IdentityKey()
3✔
4593

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

3✔
4598
        // Tell the switch to remove all links associated with this peer.
3✔
4599
        // Passing nil as the target link indicates that all links associated
3✔
4600
        // with this interface should be closed.
3✔
4601
        //
3✔
4602
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4603
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4604
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4605
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4606
        }
×
4607

4608
        for _, link := range links {
6✔
4609
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4610
        }
3✔
4611

4612
        s.mu.Lock()
3✔
4613
        defer s.mu.Unlock()
3✔
4614

3✔
4615
        // If there were any notification requests for when this peer
3✔
4616
        // disconnected, we can trigger them now.
3✔
4617
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4618
        pubStr := string(pubKey.SerializeCompressed())
3✔
4619
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4620
                close(offlineChan)
3✔
4621
        }
3✔
4622
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4623

3✔
4624
        // If the server has already removed this peer, we can short circuit the
3✔
4625
        // peer termination watcher and skip cleanup.
3✔
4626
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4627
                delete(s.ignorePeerTermination, p)
3✔
4628

3✔
4629
                pubKey := p.PubKey()
3✔
4630
                pubStr := string(pubKey[:])
3✔
4631

3✔
4632
                // If a connection callback is present, we'll go ahead and
3✔
4633
                // execute it now that previous peer has fully disconnected. If
3✔
4634
                // the callback is not present, this likely implies the peer was
3✔
4635
                // purposefully disconnected via RPC, and that no reconnect
3✔
4636
                // should be attempted.
3✔
4637
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4638
                if ok {
6✔
4639
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4640
                        connCallback()
3✔
4641
                }
3✔
4642
                return
3✔
4643
        }
4644

4645
        // First, cleanup any remaining state the server has regarding the peer
4646
        // in question.
4647
        s.removePeerUnsafe(ctx, p)
3✔
4648

3✔
4649
        // Next, check to see if this is a persistent peer or not.
3✔
4650
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4651
                return
3✔
4652
        }
3✔
4653

4654
        // Get the last address that we used to connect to the peer.
4655
        addrs := []net.Addr{
3✔
4656
                p.NetAddress().Address,
3✔
4657
        }
3✔
4658

3✔
4659
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4660
        // reconnection purposes.
3✔
4661
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4662
        switch {
3✔
4663
        // We found advertised addresses, so use them.
4664
        case err == nil:
3✔
4665
                addrs = advertisedAddrs
3✔
4666

4667
        // The peer doesn't have an advertised address.
4668
        case err == errNoAdvertisedAddr:
3✔
4669
                // If it is an outbound peer then we fall back to the existing
3✔
4670
                // peer address.
3✔
4671
                if !p.Inbound() {
6✔
4672
                        break
3✔
4673
                }
4674

4675
                // Fall back to the existing peer address if
4676
                // we're not accepting connections over Tor.
4677
                if s.torController == nil {
6✔
4678
                        break
3✔
4679
                }
4680

4681
                // If we are, the peer's address won't be known
4682
                // to us (we'll see a private address, which is
4683
                // the address used by our onion service to dial
4684
                // to lnd), so we don't have enough information
4685
                // to attempt a reconnect.
4686
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4687
                        "to inbound peer without advertised address")
×
4688
                return
×
4689

4690
        // We came across an error retrieving an advertised
4691
        // address, log it, and fall back to the existing peer
4692
        // address.
4693
        default:
3✔
4694
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4695
                        "address for peer", err)
3✔
4696
        }
4697

4698
        // Make an easy lookup map so that we can check if an address
4699
        // is already in the address list that we have stored for this peer.
4700
        existingAddrs := make(map[string]bool)
3✔
4701
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4702
                existingAddrs[addr.String()] = true
3✔
4703
        }
3✔
4704

4705
        // Add any missing addresses for this peer to persistentPeerAddr.
4706
        for _, addr := range addrs {
6✔
4707
                if existingAddrs[addr.String()] {
3✔
4708
                        continue
×
4709
                }
4710

4711
                s.persistentPeerAddrs[pubStr] = append(
3✔
4712
                        s.persistentPeerAddrs[pubStr],
3✔
4713
                        &lnwire.NetAddress{
3✔
4714
                                IdentityKey: p.IdentityKey(),
3✔
4715
                                Address:     addr,
3✔
4716
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4717
                        },
3✔
4718
                )
3✔
4719
        }
4720

4721
        // Record the computed backoff in the backoff map.
4722
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4723
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4724

3✔
4725
        // Initialize a retry canceller for this peer if one does not
3✔
4726
        // exist.
3✔
4727
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4728
        if !ok {
6✔
4729
                cancelChan = make(chan struct{})
3✔
4730
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4731
        }
3✔
4732

4733
        // We choose not to wait group this go routine since the Connect
4734
        // call can stall for arbitrarily long if we shutdown while an
4735
        // outbound connection attempt is being made.
4736
        go func() {
6✔
4737
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4738
                        "re-establishment to persistent peer",
3✔
4739
                        "reconnecting_in", backoff)
3✔
4740

3✔
4741
                select {
3✔
4742
                case <-time.After(backoff):
3✔
4743
                case <-cancelChan:
3✔
4744
                        return
3✔
4745
                case <-s.quit:
3✔
4746
                        return
3✔
4747
                }
4748

4749
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4750
                        "connection")
3✔
4751

3✔
4752
                s.connectToPersistentPeer(pubStr)
3✔
4753
        }()
4754
}
4755

4756
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4757
// to connect to the peer. It creates connection requests if there are
4758
// currently none for a given address and it removes old connection requests
4759
// if the associated address is no longer in the latest address list for the
4760
// peer.
4761
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4762
        s.mu.Lock()
3✔
4763
        defer s.mu.Unlock()
3✔
4764

3✔
4765
        // Create an easy lookup map of the addresses we have stored for the
3✔
4766
        // peer. We will remove entries from this map if we have existing
3✔
4767
        // connection requests for the associated address and then any leftover
3✔
4768
        // entries will indicate which addresses we should create new
3✔
4769
        // connection requests for.
3✔
4770
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4771
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4772
                addrMap[addr.String()] = addr
3✔
4773
        }
3✔
4774

4775
        // Go through each of the existing connection requests and
4776
        // check if they correspond to the latest set of addresses. If
4777
        // there is a connection requests that does not use one of the latest
4778
        // advertised addresses then remove that connection request.
4779
        var updatedConnReqs []*connmgr.ConnReq
3✔
4780
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4781
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4782

3✔
4783
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4784
                // If the existing connection request is using one of the
4785
                // latest advertised addresses for the peer then we add it to
4786
                // updatedConnReqs and remove the associated address from
4787
                // addrMap so that we don't recreate this connReq later on.
4788
                case true:
×
4789
                        updatedConnReqs = append(
×
4790
                                updatedConnReqs, connReq,
×
4791
                        )
×
4792
                        delete(addrMap, lnAddr)
×
4793

4794
                // If the existing connection request is using an address that
4795
                // is not one of the latest advertised addresses for the peer
4796
                // then we remove the connecting request from the connection
4797
                // manager.
4798
                case false:
3✔
4799
                        srvrLog.Info(
3✔
4800
                                "Removing conn req:", connReq.Addr.String(),
3✔
4801
                        )
3✔
4802
                        s.connMgr.Remove(connReq.ID())
3✔
4803
                }
4804
        }
4805

4806
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4807

3✔
4808
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4809
        if !ok {
6✔
4810
                cancelChan = make(chan struct{})
3✔
4811
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4812
        }
3✔
4813

4814
        // Any addresses left in addrMap are new ones that we have not made
4815
        // connection requests for. So create new connection requests for those.
4816
        // If there is more than one address in the address map, stagger the
4817
        // creation of the connection requests for those.
4818
        go func() {
6✔
4819
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4820
                defer ticker.Stop()
3✔
4821

3✔
4822
                for _, addr := range addrMap {
6✔
4823
                        // Send the persistent connection request to the
3✔
4824
                        // connection manager, saving the request itself so we
3✔
4825
                        // can cancel/restart the process as needed.
3✔
4826
                        connReq := &connmgr.ConnReq{
3✔
4827
                                Addr:      addr,
3✔
4828
                                Permanent: true,
3✔
4829
                        }
3✔
4830

3✔
4831
                        s.mu.Lock()
3✔
4832
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4833
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4834
                        )
3✔
4835
                        s.mu.Unlock()
3✔
4836

3✔
4837
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4838
                                "channel peer %v", addr)
3✔
4839

3✔
4840
                        go s.connMgr.Connect(connReq)
3✔
4841

3✔
4842
                        select {
3✔
4843
                        case <-s.quit:
3✔
4844
                                return
3✔
4845
                        case <-cancelChan:
3✔
4846
                                return
3✔
4847
                        case <-ticker.C:
3✔
4848
                        }
4849
                }
4850
        }()
4851
}
4852

4853
// removePeerUnsafe removes the passed peer from the server's state of all
4854
// active peers.
4855
//
4856
// NOTE: Server mutex must be held when calling this function.
4857
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4858
        if p == nil {
3✔
4859
                return
×
4860
        }
×
4861

4862
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4863

3✔
4864
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4865
        // will be disconnected in the server shutdown process.
3✔
4866
        if s.Stopped() {
3✔
4867
                return
×
4868
        }
×
4869

4870
        // Capture the peer's public key and string representation.
4871
        pKey := p.PubKey()
3✔
4872
        pubSer := pKey[:]
3✔
4873
        pubStr := string(pubSer)
3✔
4874

3✔
4875
        delete(s.peersByPub, pubStr)
3✔
4876

3✔
4877
        if p.Inbound() {
6✔
4878
                delete(s.inboundPeers, pubStr)
3✔
4879
        } else {
6✔
4880
                delete(s.outboundPeers, pubStr)
3✔
4881
        }
3✔
4882

4883
        // When removing the peer we make sure to disconnect it asynchronously
4884
        // to avoid blocking the main server goroutine because it is holding the
4885
        // server's mutex. Disconnecting the peer might block and wait until the
4886
        // peer has fully started up. This can happen if an inbound and outbound
4887
        // race condition occurs.
4888
        s.wg.Add(1)
3✔
4889
        go func() {
6✔
4890
                defer s.wg.Done()
3✔
4891

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

3✔
4894
                // If this peer had an active persistent connection request,
3✔
4895
                // remove it.
3✔
4896
                if p.ConnReq() != nil {
6✔
4897
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4898
                }
3✔
4899

4900
                // Remove the peer's access permission from the access manager.
4901
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4902
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4903

3✔
4904
                // Copy the peer's error buffer across to the server if it has
3✔
4905
                // any items in it so that we can restore peer errors across
3✔
4906
                // connections. We need to look up the error after the peer has
3✔
4907
                // been disconnected because we write the error in the
3✔
4908
                // `Disconnect` method.
3✔
4909
                s.mu.Lock()
3✔
4910
                if p.ErrorBuffer().Total() > 0 {
6✔
4911
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4912
                }
3✔
4913
                s.mu.Unlock()
3✔
4914

3✔
4915
                // Inform the peer notifier of a peer offline event so that it
3✔
4916
                // can be reported to clients listening for peer events.
3✔
4917
                var pubKey [33]byte
3✔
4918
                copy(pubKey[:], pubSer)
3✔
4919

3✔
4920
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4921
        }()
4922
}
4923

4924
// ConnectToPeer requests that the server connect to a Lightning Network peer
4925
// at the specified address. This function will *block* until either a
4926
// connection is established, or the initial handshake process fails.
4927
//
4928
// NOTE: This function is safe for concurrent access.
4929
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4930
        perm bool, timeout time.Duration) error {
3✔
4931

3✔
4932
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4933

3✔
4934
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4935
        // better granularity.  In certain conditions, this method requires
3✔
4936
        // making an outbound connection to a remote peer, which requires the
3✔
4937
        // lock to be released, and subsequently reacquired.
3✔
4938
        s.mu.Lock()
3✔
4939

3✔
4940
        // Ensure we're not already connected to this peer.
3✔
4941
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4942

3✔
4943
        // When there's no error it means we already have a connection with this
3✔
4944
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4945
        // set, we will ignore the existing connection and continue.
3✔
4946
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4947
                s.mu.Unlock()
3✔
4948
                return &errPeerAlreadyConnected{peer: peer}
3✔
4949
        }
3✔
4950

4951
        // Peer was not found, continue to pursue connection with peer.
4952

4953
        // If there's already a pending connection request for this pubkey,
4954
        // then we ignore this request to ensure we don't create a redundant
4955
        // connection.
4956
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4957
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4958
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4959
        }
3✔
4960

4961
        // If there's not already a pending or active connection to this node,
4962
        // then instruct the connection manager to attempt to establish a
4963
        // persistent connection to the peer.
4964
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4965
        if perm {
6✔
4966
                connReq := &connmgr.ConnReq{
3✔
4967
                        Addr:      addr,
3✔
4968
                        Permanent: true,
3✔
4969
                }
3✔
4970

3✔
4971
                // Since the user requested a permanent connection, we'll set
3✔
4972
                // the entry to true which will tell the server to continue
3✔
4973
                // reconnecting even if the number of channels with this peer is
3✔
4974
                // zero.
3✔
4975
                s.persistentPeers[targetPub] = true
3✔
4976
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
4977
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
4978
                }
3✔
4979
                s.persistentConnReqs[targetPub] = append(
3✔
4980
                        s.persistentConnReqs[targetPub], connReq,
3✔
4981
                )
3✔
4982
                s.mu.Unlock()
3✔
4983

3✔
4984
                go s.connMgr.Connect(connReq)
3✔
4985

3✔
4986
                return nil
3✔
4987
        }
4988
        s.mu.Unlock()
3✔
4989

3✔
4990
        // If we're not making a persistent connection, then we'll attempt to
3✔
4991
        // connect to the target peer. If the we can't make the connection, or
3✔
4992
        // the crypto negotiation breaks down, then return an error to the
3✔
4993
        // caller.
3✔
4994
        errChan := make(chan error, 1)
3✔
4995
        s.connectToPeer(addr, errChan, timeout)
3✔
4996

3✔
4997
        select {
3✔
4998
        case err := <-errChan:
3✔
4999
                return err
3✔
5000
        case <-s.quit:
×
5001
                return ErrServerShuttingDown
×
5002
        }
5003
}
5004

5005
// connectToPeer establishes a connection to a remote peer. errChan is used to
5006
// notify the caller if the connection attempt has failed. Otherwise, it will be
5007
// closed.
5008
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5009
        errChan chan<- error, timeout time.Duration) {
3✔
5010

3✔
5011
        conn, err := brontide.Dial(
3✔
5012
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5013
        )
3✔
5014
        if err != nil {
6✔
5015
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5016
                select {
3✔
5017
                case errChan <- err:
3✔
5018
                case <-s.quit:
×
5019
                }
5020
                return
3✔
5021
        }
5022

5023
        close(errChan)
3✔
5024

3✔
5025
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5026
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5027

3✔
5028
        s.OutboundPeerConnected(nil, conn)
3✔
5029
}
5030

5031
// DisconnectPeer sends the request to server to close the connection with peer
5032
// identified by public key.
5033
//
5034
// NOTE: This function is safe for concurrent access.
5035
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5036
        pubBytes := pubKey.SerializeCompressed()
3✔
5037
        pubStr := string(pubBytes)
3✔
5038

3✔
5039
        s.mu.Lock()
3✔
5040
        defer s.mu.Unlock()
3✔
5041

3✔
5042
        // Check that were actually connected to this peer. If not, then we'll
3✔
5043
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5044
        // currently connected to.
3✔
5045
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5046
        if err == ErrPeerNotConnected {
6✔
5047
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5048
        }
3✔
5049

5050
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5051

3✔
5052
        s.cancelConnReqs(pubStr, nil)
3✔
5053

3✔
5054
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5055
        // them from this map so we don't attempt to re-connect after we
3✔
5056
        // disconnect.
3✔
5057
        delete(s.persistentPeers, pubStr)
3✔
5058
        delete(s.persistentPeersBackoff, pubStr)
3✔
5059

3✔
5060
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5061
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5062
        //
3✔
5063
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5064
        // goroutine because we might hold the server's mutex.
3✔
5065
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5066

3✔
5067
        return nil
3✔
5068
}
5069

5070
// OpenChannel sends a request to the server to open a channel to the specified
5071
// peer identified by nodeKey with the passed channel funding parameters.
5072
//
5073
// NOTE: This function is safe for concurrent access.
5074
func (s *server) OpenChannel(
5075
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5076

3✔
5077
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5078
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5079
        // not blocked if the caller is not reading the updates.
3✔
5080
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5081
        req.Err = make(chan error, 1)
3✔
5082

3✔
5083
        // First attempt to locate the target peer to open a channel with, if
3✔
5084
        // we're unable to locate the peer then this request will fail.
3✔
5085
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5086
        s.mu.RLock()
3✔
5087
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5088
        if !ok {
3✔
5089
                s.mu.RUnlock()
×
5090

×
5091
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5092
                return req.Updates, req.Err
×
5093
        }
×
5094
        req.Peer = peer
3✔
5095
        s.mu.RUnlock()
3✔
5096

3✔
5097
        // We'll wait until the peer is active before beginning the channel
3✔
5098
        // opening process.
3✔
5099
        select {
3✔
5100
        case <-peer.ActiveSignal():
3✔
5101
        case <-peer.QuitSignal():
×
5102
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5103
                return req.Updates, req.Err
×
5104
        case <-s.quit:
×
5105
                req.Err <- ErrServerShuttingDown
×
5106
                return req.Updates, req.Err
×
5107
        }
5108

5109
        // If the fee rate wasn't specified at this point we fail the funding
5110
        // because of the missing fee rate information. The caller of the
5111
        // `OpenChannel` method needs to make sure that default values for the
5112
        // fee rate are set beforehand.
5113
        if req.FundingFeePerKw == 0 {
3✔
5114
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5115
                        "the channel opening transaction")
×
5116

×
5117
                return req.Updates, req.Err
×
5118
        }
×
5119

5120
        // Spawn a goroutine to send the funding workflow request to the funding
5121
        // manager. This allows the server to continue handling queries instead
5122
        // of blocking on this request which is exported as a synchronous
5123
        // request to the outside world.
5124
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5125

3✔
5126
        return req.Updates, req.Err
3✔
5127
}
5128

5129
// Peers returns a slice of all active peers.
5130
//
5131
// NOTE: This function is safe for concurrent access.
5132
func (s *server) Peers() []*peer.Brontide {
3✔
5133
        s.mu.RLock()
3✔
5134
        defer s.mu.RUnlock()
3✔
5135

3✔
5136
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5137
        for _, peer := range s.peersByPub {
6✔
5138
                peers = append(peers, peer)
3✔
5139
        }
3✔
5140

5141
        return peers
3✔
5142
}
5143

5144
// computeNextBackoff uses a truncated exponential backoff to compute the next
5145
// backoff using the value of the exiting backoff. The returned duration is
5146
// randomized in either direction by 1/20 to prevent tight loops from
5147
// stabilizing.
5148
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5149
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5150
        nextBackoff := 2 * currBackoff
3✔
5151
        if nextBackoff > maxBackoff {
6✔
5152
                nextBackoff = maxBackoff
3✔
5153
        }
3✔
5154

5155
        // Using 1/10 of our duration as a margin, compute a random offset to
5156
        // avoid the nodes entering connection cycles.
5157
        margin := nextBackoff / 10
3✔
5158

3✔
5159
        var wiggle big.Int
3✔
5160
        wiggle.SetUint64(uint64(margin))
3✔
5161
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5162
                // Randomizing is not mission critical, so we'll just return the
×
5163
                // current backoff.
×
5164
                return nextBackoff
×
5165
        }
×
5166

5167
        // Otherwise add in our wiggle, but subtract out half of the margin so
5168
        // that the backoff can tweaked by 1/20 in either direction.
5169
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5170
}
5171

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

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

3✔
5180
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5181
        if err != nil {
3✔
5182
                return nil, err
×
5183
        }
×
5184

5185
        node, err := s.graphDB.FetchNode(ctx, vertex)
3✔
5186
        if err != nil {
6✔
5187
                return nil, err
3✔
5188
        }
3✔
5189

5190
        if len(node.Addresses) == 0 {
6✔
5191
                return nil, errNoAdvertisedAddr
3✔
5192
        }
3✔
5193

5194
        return node.Addresses, nil
3✔
5195
}
5196

5197
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5198
// channel update for a target channel.
5199
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5200
        *lnwire.ChannelUpdate1, error) {
3✔
5201

3✔
5202
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5203
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5204
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5205
                if err != nil {
6✔
5206
                        return nil, err
3✔
5207
                }
3✔
5208

5209
                return netann.ExtractChannelUpdate(
3✔
5210
                        ourPubKey[:], info, edge1, edge2,
3✔
5211
                )
3✔
5212
        }
5213
}
5214

5215
// applyChannelUpdate applies the channel update to the different sub-systems of
5216
// the server. The useAlias boolean denotes whether or not to send an alias in
5217
// place of the real SCID.
5218
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5219
        op *wire.OutPoint, useAlias bool) error {
3✔
5220

3✔
5221
        var (
3✔
5222
                peerAlias    *lnwire.ShortChannelID
3✔
5223
                defaultAlias lnwire.ShortChannelID
3✔
5224
        )
3✔
5225

3✔
5226
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5227

3✔
5228
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5229
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5230
        if useAlias {
6✔
5231
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5232
                if foundAlias != defaultAlias {
6✔
5233
                        peerAlias = &foundAlias
3✔
5234
                }
3✔
5235
        }
5236

5237
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5238
                update, discovery.RemoteAlias(peerAlias),
3✔
5239
        )
3✔
5240
        select {
3✔
5241
        case err := <-errChan:
3✔
5242
                return err
3✔
5243
        case <-s.quit:
×
5244
                return ErrServerShuttingDown
×
5245
        }
5246
}
5247

5248
// SendCustomMessage sends a custom message to the peer with the specified
5249
// pubkey.
5250
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5251
        data []byte) error {
3✔
5252

3✔
5253
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5254
        if err != nil {
6✔
5255
                return err
3✔
5256
        }
3✔
5257

5258
        // We'll wait until the peer is active.
5259
        select {
3✔
5260
        case <-peer.ActiveSignal():
3✔
5261
        case <-peer.QuitSignal():
×
5262
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5263
        case <-s.quit:
×
5264
                return ErrServerShuttingDown
×
5265
        }
5266

5267
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5268
        if err != nil {
6✔
5269
                return err
3✔
5270
        }
3✔
5271

5272
        // Send the message as low-priority. For now we assume that all
5273
        // application-defined message are low priority.
5274
        return peer.SendMessageLazy(true, msg)
3✔
5275
}
5276

5277
// newSweepPkScriptGen creates closure that generates a new public key script
5278
// which should be used to sweep any funds into the on-chain wallet.
5279
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5280
// (p2wkh) output.
5281
func newSweepPkScriptGen(
5282
        wallet lnwallet.WalletController,
5283
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5284

3✔
5285
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5286
                sweepAddr, err := wallet.NewAddress(
3✔
5287
                        lnwallet.TaprootPubkey, false,
3✔
5288
                        lnwallet.DefaultAccountName,
3✔
5289
                )
3✔
5290
                if err != nil {
3✔
5291
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5292
                }
×
5293

5294
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5295
                if err != nil {
3✔
5296
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5297
                }
×
5298

5299
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5300
                        wallet, netParams, addr,
3✔
5301
                )
3✔
5302
                if err != nil {
3✔
5303
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5304
                }
×
5305

5306
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5307
                        DeliveryAddress: addr,
3✔
5308
                        InternalKey:     internalKeyDesc,
3✔
5309
                })
3✔
5310
        }
5311
}
5312

5313
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5314
// finished.
5315
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5316
        // Get a list of closed channels.
3✔
5317
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5318
        if err != nil {
3✔
5319
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5320
                return nil
×
5321
        }
×
5322

5323
        // Save the SCIDs in a map.
5324
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5325
        for _, c := range channels {
6✔
5326
                // If the channel is not pending, its FC has been finalized.
3✔
5327
                if !c.IsPending {
6✔
5328
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5329
                }
3✔
5330
        }
5331

5332
        // Double check whether the reported closed channel has indeed finished
5333
        // closing.
5334
        //
5335
        // NOTE: There are misalignments regarding when a channel's FC is
5336
        // marked as finalized. We double check the pending channels to make
5337
        // sure the returned SCIDs are indeed terminated.
5338
        //
5339
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5340
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5341
        if err != nil {
3✔
5342
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5343
                return nil
×
5344
        }
×
5345

5346
        for _, c := range pendings {
6✔
5347
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5348
                        continue
3✔
5349
                }
5350

5351
                // If the channel is still reported as pending, remove it from
5352
                // the map.
5353
                delete(closedSCIDs, c.ShortChannelID)
×
5354

×
5355
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5356
                        c.ShortChannelID)
×
5357
        }
5358

5359
        return closedSCIDs
3✔
5360
}
5361

5362
// getStartingBeat returns the current beat. This is used during the startup to
5363
// initialize blockbeat consumers.
5364
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5365
        // beat is the current blockbeat.
3✔
5366
        var beat *chainio.Beat
3✔
5367

3✔
5368
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5369
        // we will skip fetching the best block.
3✔
5370
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5371
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5372
                        "mode")
×
5373

×
5374
                return &chainio.Beat{}, nil
×
5375
        }
×
5376

5377
        // We should get a notification with the current best block immediately
5378
        // by passing a nil block.
5379
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5380
        if err != nil {
3✔
5381
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5382
        }
×
5383
        defer blockEpochs.Cancel()
3✔
5384

3✔
5385
        // We registered for the block epochs with a nil request. The notifier
3✔
5386
        // should send us the current best block immediately. So we need to
3✔
5387
        // wait for it here because we need to know the current best height.
3✔
5388
        select {
3✔
5389
        case bestBlock := <-blockEpochs.Epochs:
3✔
5390
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5391
                        bestBlock.Hash, bestBlock.Height)
3✔
5392

3✔
5393
                // Update the current blockbeat.
3✔
5394
                beat = chainio.NewBeat(*bestBlock)
3✔
5395

5396
        case <-s.quit:
×
5397
                srvrLog.Debug("LND shutting down")
×
5398
        }
5399

5400
        return beat, nil
3✔
5401
}
5402

5403
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5404
// point has an active RBF chan closer.
5405
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5406
        chanPoint wire.OutPoint) bool {
3✔
5407

3✔
5408
        pubBytes := peerPub.SerializeCompressed()
3✔
5409

3✔
5410
        s.mu.RLock()
3✔
5411
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5412
        s.mu.RUnlock()
3✔
5413
        if !ok {
3✔
5414
                return false
×
5415
        }
×
5416

5417
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5418
}
5419

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

3✔
5428
        // First, we'll attempt to look up the channel based on it's
3✔
5429
        // ChannelPoint.
3✔
5430
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5431
        if err != nil {
3✔
5432
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5433
        }
×
5434

5435
        // From the channel, we can now get the pubkey of the peer, then use
5436
        // that to eventually get the chan closer.
5437
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5438

3✔
5439
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5440
        s.mu.RLock()
3✔
5441
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5442
        s.mu.RUnlock()
3✔
5443
        if !ok {
3✔
5444
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5445
                        "not online", chanPoint)
×
5446
        }
×
5447

5448
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5449
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5450
        )
3✔
5451
        if err != nil {
3✔
5452
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5453
                        "%w", err)
×
5454
        }
×
5455

5456
        return closeUpdates, nil
3✔
5457
}
5458

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

3✔
5467
        // If the channel is present in the switch, then the request should flow
3✔
5468
        // through the switch instead.
3✔
5469
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5470
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5471
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5472
                        "invalid request", chanPoint)
×
5473
        }
×
5474

5475
        // At this point, we know that the channel isn't present in the link, so
5476
        // we'll check to see if we have an entry in the active chan closer map.
5477
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5478
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5479
        )
3✔
5480
        if err != nil {
3✔
5481
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5482
                        "ChannelPoint(%v)", chanPoint)
×
5483
        }
×
5484

5485
        return updates, nil
3✔
5486
}
5487

5488
// setSelfNode configures and sets the server's self node. It sets the node
5489
// announcement, signs it, and updates the source node in the graph. When
5490
// determining values such as color and alias, the method prioritizes values
5491
// set in the config, then values previously persisted on disk, and finally
5492
// falls back to the defaults.
5493
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5494
        listenAddrs []net.Addr) error {
3✔
5495

3✔
5496
        // If we were requested to automatically configure port forwarding,
3✔
5497
        // we'll use the ports that the server will be listening on.
3✔
5498
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5499
        for _, ip := range s.cfg.ExternalIPs {
6✔
5500
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5501
        }
3✔
5502
        if s.natTraversal != nil {
3✔
5503
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5504
                for _, listenAddr := range listenAddrs {
×
5505
                        // At this point, the listen addresses should have
×
5506
                        // already been normalized, so it's safe to ignore the
×
5507
                        // errors.
×
5508
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5509
                        port, _ := strconv.Atoi(portStr)
×
5510

×
5511
                        listenPorts = append(listenPorts, uint16(port))
×
5512
                }
×
5513

5514
                ips, err := s.configurePortForwarding(listenPorts...)
×
5515
                if err != nil {
×
5516
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5517
                                "forwarding using %s: %v",
×
5518
                                s.natTraversal.Name(), err)
×
5519
                } else {
×
5520
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5521
                                "using %s to advertise external IP",
×
5522
                                s.natTraversal.Name())
×
5523
                        externalIPStrings = append(externalIPStrings, ips...)
×
5524
                }
×
5525
        }
5526

5527
        // Normalize the external IP strings to net.Addr.
5528
        addrs, err := lncfg.NormalizeAddresses(
3✔
5529
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5530
                s.cfg.net.ResolveTCPAddr,
3✔
5531
        )
3✔
5532
        if err != nil {
3✔
5533
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5534
        }
×
5535

5536
        // Parse the color from config. We will update this later if the config
5537
        // color is not changed from default (#3399FF) and we have a value in
5538
        // the source node.
5539
        color, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5540
        if err != nil {
3✔
5541
                return fmt.Errorf("unable to parse color: %w", err)
×
5542
        }
×
5543

5544
        var (
3✔
5545
                alias          = s.cfg.Alias
3✔
5546
                nodeLastUpdate = time.Now()
3✔
5547
        )
3✔
5548

3✔
5549
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5550
        switch {
3✔
5551
        case err == nil:
3✔
5552
                // If we have a source node persisted in the DB already, then we
3✔
5553
                // just need to make sure that the new LastUpdate time is at
3✔
5554
                // least one second after the last update time.
3✔
5555
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
5556
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
5557
                }
3✔
5558

5559
                // If the color is not changed from default, it means that we
5560
                // didn't specify a different color in the config. We'll use the
5561
                // source node's color.
5562
                if s.cfg.Color == defaultColor {
6✔
5563
                        color = srcNode.Color
3✔
5564
                }
3✔
5565

5566
                // If an alias is not specified in the config, we'll use the
5567
                // source node's alias.
5568
                if alias == "" {
6✔
5569
                        alias = srcNode.Alias
3✔
5570
                }
3✔
5571

5572
                // If the `externalip` is not specified in the config, it means
5573
                // `addrs` will be empty, we'll use the source node's addresses.
5574
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5575
                        addrs = srcNode.Addresses
3✔
5576
                }
3✔
5577

5578
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5579
                // If an alias is not specified in the config, we'll use the
3✔
5580
                // default, which is the first 10 bytes of the serialized
3✔
5581
                // pubkey.
3✔
5582
                if alias == "" {
6✔
5583
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5584
                }
3✔
5585

5586
        // If the above cases are not matched, then we have an unhandled non
5587
        // nil error.
5588
        default:
×
5589
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5590
        }
5591

5592
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5593
        if err != nil {
3✔
5594
                return err
×
5595
        }
×
5596

5597
        // TODO(abdulkbk): potentially find a way to use the source node's
5598
        // features in the self node.
5599
        selfNode := &models.Node{
3✔
5600
                HaveNodeAnnouncement: true,
3✔
5601
                LastUpdate:           nodeLastUpdate,
3✔
5602
                Addresses:            addrs,
3✔
5603
                Alias:                nodeAlias.String(),
3✔
5604
                Color:                color,
3✔
5605
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
5606
        }
3✔
5607

3✔
5608
        copy(selfNode.PubKeyBytes[:], nodePub[:])
3✔
5609

3✔
5610
        // Based on the disk representation of the node announcement generated
3✔
5611
        // above, we'll generate a node announcement that can go out on the
3✔
5612
        // network so we can properly sign it.
3✔
5613
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5614
        if err != nil {
3✔
5615
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5616
        }
×
5617

5618
        // With the announcement generated, we'll sign it to properly
5619
        // authenticate the message on the network.
5620
        authSig, err := netann.SignAnnouncement(
3✔
5621
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5622
        )
3✔
5623
        if err != nil {
3✔
5624
                return fmt.Errorf("unable to generate signature for self node "+
×
5625
                        "announcement: %v", err)
×
5626
        }
×
5627

5628
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5629
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5630
                selfNode.AuthSigBytes,
3✔
5631
        )
3✔
5632
        if err != nil {
3✔
5633
                return err
×
5634
        }
×
5635

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

5642
        s.currentNodeAnn = nodeAnn
3✔
5643

3✔
5644
        return nil
3✔
5645
}
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