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

lightningnetwork / lnd / 22126266334

18 Feb 2026 04:15AM UTC coverage: 65.193% (+0.08%) from 65.117%
22126266334

Pull #10589

github

web-flow
Merge a4ed4750f into 14a01eb84
Pull Request #10589: discovery: replace chan error w/ actor.Promise[error] for gossip results

139 of 215 new or added lines in 8 files covered. (64.65%)

106 existing lines in 24 files now uncovered.

139750 of 214363 relevant lines covered (65.19%)

20470.0 hits per line

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

70.08
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

185
        // peerStatusTemporary indicates that the peer only has temporary p2p
186
        // access to the server.
187
        peerStatusTemporary
188

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

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

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

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

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

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

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

227
        start sync.Once
228
        stop  sync.Once
229

230
        cfg *Config
231

232
        implCfg *ImplementationCfg
233

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

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

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

245
        chanStatusMgr *netann.ChanStatusManager
246

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

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

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

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

267
        mu sync.RWMutex
268

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

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

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

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

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

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

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

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

319
        cc *chainreg.ChainControl
320

321
        fundingMgr *funding.Manager
322

323
        graphDB *graphdb.ChannelGraph
324
        v1Graph *graphdb.VersionedGraph
325

326
        chanStateDB *channeldb.ChannelStateDB
327

328
        addrSource channeldb.AddrSource
329

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

334
        invoicesDB invoices.InvoiceDB
335

336
        // paymentsDB is the DB that contains all functions for managing
337
        // payments.
338
        paymentsDB paymentsdb.DB
339

340
        aliasMgr *aliasmgr.Manager
341

342
        htlcSwitch *htlcswitch.Switch
343

344
        interceptableSwitch *htlcswitch.InterceptableSwitch
345

346
        invoices *invoices.InvoiceRegistry
347

348
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
349

350
        channelNotifier *channelnotifier.ChannelNotifier
351

352
        peerNotifier *peernotifier.PeerNotifier
353

354
        htlcNotifier *htlcswitch.HtlcNotifier
355

356
        witnessBeacon contractcourt.WitnessBeacon
357

358
        breachArbitrator *contractcourt.BreachArbitrator
359

360
        missionController *routing.MissionController
361
        defaultMC         *routing.MissionControl
362

363
        graphBuilder *graph.Builder
364

365
        chanRouter *routing.ChannelRouter
366

367
        controlTower routing.ControlTower
368

369
        authGossiper *discovery.AuthenticatedGossiper
370

371
        localChanMgr *localchans.Manager
372

373
        utxoNursery *contractcourt.UtxoNursery
374

375
        sweeper *sweep.UtxoSweeper
376

377
        chainArb *contractcourt.ChainArbitrator
378

379
        sphinx *hop.OnionProcessor
380

381
        towerClientMgr *wtclient.Manager
382

383
        connMgr *connmgr.ConnManager
384

385
        sigPool *lnwallet.SigPool
386

387
        writePool *pool.Write
388

389
        readPool *pool.Read
390

391
        tlsManager *TLSManager
392

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

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

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

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

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

415
        hostAnn *netann.HostAnnouncer
416

417
        // livenessMonitor monitors that lnd has access to critical resources.
418
        livenessMonitor *healthcheck.Monitor
419

420
        customMessageServer *subscribe.Server
421

422
        onionMessageServer *subscribe.Server
423

424
        // txPublisher is a publisher with fee-bumping capability.
425
        txPublisher *sweep.TxPublisher
426

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

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

434
        quit chan struct{}
435

436
        wg sync.WaitGroup
437
}
438

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

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

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

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

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

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

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

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

494
                                        s.mu.Lock()
3✔
495

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

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

510
                                        s.mu.Unlock()
3✔
511

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

518
        return nil
3✔
519
}
520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
673
        v1Graph := graphdb.NewVersionedGraph(
3✔
674
                dbs.GraphDB, lnwire.GossipVersion1,
3✔
675
        )
3✔
676

3✔
677
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, v1Graph)
3✔
678

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

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

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

3✔
706
                listenAddrs: listenAddrs,
3✔
707

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

3✔
712
                torController: torController,
3✔
713

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

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

3✔
730
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
731

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

3✔
734
                onionMessageServer: subscribe.NewServer(),
3✔
735

3✔
736
                tlsManager: tlsManager,
3✔
737

3✔
738
                featureMgr: featureMgr,
3✔
739
                quit:       make(chan struct{}),
3✔
740
        }
3✔
741

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

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

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

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

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

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

3✔
768
                return nil
3✔
769
        }
770

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

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

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

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

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

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

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

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

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

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

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

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

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

889
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
890
        // Set the self node which represents our node in the graph.
3✔
891
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
892
        if err != nil {
3✔
893
                return nil, err
×
894
        }
×
895

896
        // The router will get access to the payment ID sequencer, such that it
897
        // can generate unique payment IDs.
898
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
899
        if err != nil {
3✔
900
                return nil, err
×
901
        }
×
902

903
        // Instantiate mission control with config from the sub server.
904
        //
905
        // TODO(joostjager): When we are further in the process of moving to sub
906
        // servers, the mission control instance itself can be moved there too.
907
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
908

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

3✔
924
                        estimator, err = routing.NewAprioriEstimator(
3✔
925
                                aprioriConfig,
3✔
926
                        )
3✔
927
                        if err != nil {
3✔
928
                                return nil, err
×
929
                        }
×
930

931
                case routing.BimodalEstimatorName:
×
932
                        bCfg := routingConfig.BimodalConfig
×
933
                        bimodalConfig := routing.BimodalConfig{
×
934
                                BimodalNodeWeight: bCfg.NodeWeight,
×
935
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
936
                                        bCfg.Scale,
×
937
                                ),
×
938
                                BimodalDecayTime: bCfg.DecayTime,
×
939
                        }
×
940

×
941
                        estimator, err = routing.NewBimodalEstimator(
×
942
                                bimodalConfig,
×
943
                        )
×
944
                        if err != nil {
×
945
                                return nil, err
×
946
                        }
×
947

948
                default:
×
949
                        return nil, fmt.Errorf("unknown estimator type %v",
×
950
                                routingConfig.ProbabilityEstimatorType)
×
951
                }
952
        }
953

954
        mcCfg := &routing.MissionControlConfig{
3✔
955
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
956
                Estimator:               estimator,
3✔
957
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
958
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
959
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
960
        }
3✔
961

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

977
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
978
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
979
                int64(routingConfig.AttemptCost),
3✔
980
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
981
                routingConfig.MinRouteProbability)
3✔
982

3✔
983
        pathFindingConfig := routing.PathFindingConfig{
3✔
984
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
985
                        routingConfig.AttemptCost,
3✔
986
                ),
3✔
987
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
988
                MinProbability: routingConfig.MinRouteProbability,
3✔
989
        }
3✔
990

3✔
991
        sourceNode, err := s.v1Graph.SourceNode(ctx)
3✔
992
        if err != nil {
3✔
993
                return nil, fmt.Errorf("error getting source node: %w", err)
×
994
        }
×
995
        paymentSessionSource := &routing.SessionSource{
3✔
996
                GraphSessionFactory: dbs.GraphDB,
3✔
997
                SourceNode:          sourceNode,
3✔
998
                MissionControl:      s.defaultMC,
3✔
999
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1000
                PathFindingConfig:   pathFindingConfig,
3✔
1001
        }
3✔
1002

3✔
1003
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1004

3✔
1005
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1006
                cfg.Routing.StrictZombiePruning
3✔
1007

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

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

1045
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1046
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1047
        if err != nil {
3✔
1048
                return nil, err
×
1049
        }
×
1050
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1051
        if err != nil {
3✔
1052
                return nil, err
×
1053
        }
×
1054

1055
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1056

3✔
1057
        s.authGossiper = discovery.New(discovery.Config{
3✔
1058
                Graph:                 s.graphBuilder,
3✔
1059
                ChainIO:               s.cc.ChainIO,
3✔
1060
                Notifier:              s.cc.ChainNotifier,
3✔
1061
                ChainParams:           s.cfg.ActiveNetParams.Params,
3✔
1062
                Broadcast:             s.BroadcastMessage,
3✔
1063
                ChanSeries:            chanSeries,
3✔
1064
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1065
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1066
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1067
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
3✔
1068
                        error) {
3✔
1069

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

1104
        accessCfg := &accessManConfig{
3✔
1105
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1106
                        error) {
6✔
1107

3✔
1108
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1109
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1110
                                genesisHash[:],
3✔
1111
                        )
3✔
1112
                },
3✔
1113
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1114
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1115
        }
1116

1117
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1118
        if err != nil {
3✔
1119
                return nil, err
×
1120
        }
×
1121

1122
        s.peerAccessMan = peerAccessMan
3✔
1123

3✔
1124
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1125
        //nolint:ll
3✔
1126
        s.localChanMgr = &localchans.Manager{
3✔
1127
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1128
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1129
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1130
                        cb func(*models.ChannelEdgeInfo,
3✔
1131
                                *models.ChannelEdgePolicy) error,
3✔
1132
                        reset func()) error {
6✔
1133

3✔
1134
                        return s.v1Graph.ForEachNodeChannel(
3✔
1135
                                ctx, selfVertex,
3✔
1136
                                func(c *models.ChannelEdgeInfo,
3✔
1137
                                        e *models.ChannelEdgePolicy,
3✔
1138
                                        _ *models.ChannelEdgePolicy) error {
6✔
1139

3✔
1140
                                        // NOTE: The invoked callback here may
3✔
1141
                                        // receive a nil channel policy.
3✔
1142
                                        return cb(c, e)
3✔
1143
                                }, reset,
3✔
1144
                        )
1145
                },
1146
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1147
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1148
                FetchChannel:              s.chanStateDB.FetchChannel,
1149
                AddEdge: func(ctx context.Context,
1150
                        edge *models.ChannelEdgeInfo) error {
×
1151

×
1152
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1153
                },
×
1154
        }
1155

1156
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1157
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1158
        )
3✔
1159
        if err != nil {
3✔
1160
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1161
                return nil, err
×
1162
        }
×
1163

1164
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1165
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1166
        )
3✔
1167
        if err != nil {
3✔
1168
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1169
                return nil, err
×
1170
        }
×
1171

1172
        aggregator := sweep.NewBudgetAggregator(
3✔
1173
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1174
                s.implCfg.AuxSweeper,
3✔
1175
        )
3✔
1176

3✔
1177
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1178
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1179
                Wallet:     cc.Wallet,
3✔
1180
                Estimator:  cc.FeeEstimator,
3✔
1181
                Notifier:   cc.ChainNotifier,
3✔
1182
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1183
        })
3✔
1184

3✔
1185
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1186
                FeeEstimator: cc.FeeEstimator,
3✔
1187
                GenSweepScript: newSweepPkScriptGen(
3✔
1188
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1189
                ),
3✔
1190
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1191
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1192
                Mempool:              cc.MempoolNotifier,
3✔
1193
                Notifier:             cc.ChainNotifier,
3✔
1194
                Store:                sweeperStore,
3✔
1195
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1196
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1197
                Aggregator:           aggregator,
3✔
1198
                Publisher:            s.txPublisher,
3✔
1199
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1200
        })
3✔
1201

3✔
1202
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1203
                ChainIO:             cc.ChainIO,
3✔
1204
                ConfDepth:           1,
3✔
1205
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1206
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1207
                Notifier:            cc.ChainNotifier,
3✔
1208
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1209
                Store:               utxnStore,
3✔
1210
                SweepInput:          s.sweeper.SweepInput,
3✔
1211
                Budget:              s.cfg.Sweeper.Budget,
3✔
1212
        })
3✔
1213

3✔
1214
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1215
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1216
                closureType contractcourt.ChannelCloseType) {
6✔
1217
                // TODO(conner): Properly respect the update and error channels
3✔
1218
                // returned by CloseLink.
3✔
1219

3✔
1220
                // Instruct the switch to close the channel.  Provide no close out
3✔
1221
                // delivery script or target fee per kw because user input is not
3✔
1222
                // available when the remote peer closes the channel.
3✔
1223
                s.htlcSwitch.CloseLink(
3✔
1224
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1225
                )
3✔
1226
        }
3✔
1227

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

3✔
1232
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1233
                &contractcourt.BreachConfig{
3✔
1234
                        CloseLink: closeLink,
3✔
1235
                        DB:        s.chanStateDB,
3✔
1236
                        Estimator: s.cc.FeeEstimator,
3✔
1237
                        GenSweepScript: newSweepPkScriptGen(
3✔
1238
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1239
                        ),
3✔
1240
                        Notifier:           cc.ChainNotifier,
3✔
1241
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1242
                        ContractBreaches:   contractBreaches,
3✔
1243
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1244
                        Store: contractcourt.NewRetributionStore(
3✔
1245
                                dbs.ChanStateDB,
3✔
1246
                        ),
3✔
1247
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1248
                },
3✔
1249
        )
3✔
1250

3✔
1251
        //nolint:ll
3✔
1252
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1253
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1254
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1255
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1256
                NewSweepAddr: func() ([]byte, error) {
3✔
1257
                        addr, err := newSweepPkScriptGen(
×
1258
                                cc.Wallet, netParams,
×
1259
                        )().Unpack()
×
1260
                        if err != nil {
×
1261
                                return nil, err
×
1262
                        }
×
1263

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

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

3✔
1302
                        // processACK will handle the BreachArbitrator ACKing
3✔
1303
                        // the event.
3✔
1304
                        finalErr := make(chan error, 1)
3✔
1305
                        processACK := func(brarErr error) {
6✔
1306
                                if brarErr != nil {
3✔
1307
                                        finalErr <- brarErr
×
1308
                                        return
×
1309
                                }
×
1310

1311
                                // If the BreachArbitrator successfully handled
1312
                                // the event, we can signal that the handoff
1313
                                // was successful.
1314
                                finalErr <- nil
3✔
1315
                        }
1316

1317
                        event := &contractcourt.ContractBreachEvent{
3✔
1318
                                ChanPoint:         chanPoint,
3✔
1319
                                ProcessACK:        processACK,
3✔
1320
                                BreachRetribution: breachRet,
3✔
1321
                        }
3✔
1322

3✔
1323
                        // Send the contract breach event to the
3✔
1324
                        // BreachArbitrator.
3✔
1325
                        select {
3✔
1326
                        case contractBreaches <- event:
3✔
1327
                        case <-s.quit:
×
1328
                                return ErrServerShuttingDown
×
1329
                        }
1330

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

1356
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1357
                QueryIncomingCircuit: func(
1358
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1359

3✔
1360
                        // Get the circuit map.
3✔
1361
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1362

3✔
1363
                        // Lookup the outgoing circuit.
3✔
1364
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1365
                        if pc == nil {
5✔
1366
                                return nil
2✔
1367
                        }
2✔
1368

1369
                        return &pc.Incoming
3✔
1370
                },
1371
                AuxLeafStore: implCfg.AuxLeafStore,
1372
                AuxSigner:    implCfg.AuxSigner,
1373
                AuxResolver:  implCfg.AuxContractResolver,
1374
                AuxCloser: fn.MapOption(
1375
                        func(c chcl.AuxChanCloser) contractcourt.AuxChanCloser {
×
1376
                                return c
×
1377
                        },
×
1378
                )(implCfg.AuxChanCloser),
1379
                ChannelCloseConfs: s.cfg.Dev.ChannelCloseConfs(),
1380
        }, dbs.ChanStateDB)
1381

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

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

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

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

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

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

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

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

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

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

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

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

1456
        // Attempt to parse the provided upfront-shutdown address (if any).
1457
        script, err := chcl.ParseUpfrontShutdownAddress(
3✔
1458
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
3✔
1459
        )
3✔
1460
        if err != nil {
3✔
1461
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1462
                        err)
×
1463
        }
×
1464

1465
        //nolint:ll
1466
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1467
                Dev:                devCfg,
3✔
1468
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1469
                IDKey:              nodeKeyDesc.PubKey,
3✔
1470
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1471
                Wallet:             cc.Wallet,
3✔
1472
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1473
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1474
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1475
                },
3✔
1476
                Notifier:     cc.ChainNotifier,
1477
                ChannelDB:    s.chanStateDB,
1478
                FeeEstimator: cc.FeeEstimator,
1479
                SignMessage:  cc.MsgSigner.SignMessage,
1480
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1481
                        error) {
3✔
1482

3✔
1483
                        return s.genNodeAnnouncement(nil)
3✔
1484
                },
3✔
1485
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1486
                NotifyWhenOnline:     s.NotifyWhenOnline,
1487
                TempChanIDSeed:       chanIDSeed,
1488
                FindChannel:          s.findChannel,
1489
                DefaultRoutingPolicy: cc.RoutingPolicy,
1490
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1491
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1492
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1493
                        // In case the user has explicitly specified
3✔
1494
                        // a default value for the number of
3✔
1495
                        // confirmations, we use it.
3✔
1496
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1497
                        if defaultConf != 0 {
6✔
1498
                                return defaultConf
3✔
1499
                        }
3✔
1500

1501
                        // Otherwise, scale the number of confirmations based on
1502
                        // the channel amount and push amount. For large
1503
                        // channels we increase the number of
1504
                        // confirmations we require for the channel to be
1505
                        // considered open. As it is always the
1506
                        // responder that gets to choose value, the
1507
                        // pushAmt is value being pushed to us. This
1508
                        // means we have more to lose in the case this
1509
                        // gets re-orged out, and we will require more
1510
                        // confirmations before we consider it open.
1511
                        return lnwallet.FundingConfsForAmounts(chanAmt, pushAmt)
×
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
                ShutdownScript:       peer.ChooseAddr(script),
1622
        })
1623
        if err != nil {
3✔
1624
                return nil, err
×
1625
        }
×
1626

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1924
                chainBackendAttempts = 0
×
1925
        }
×
1926

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
2131
        s.start.Do(func() {
6✔
2132
                // Before starting any subsystems, repair any link nodes that
3✔
2133
                // may have been incorrectly pruned due to the race condition
3✔
2134
                // that was fixed in the link node pruning logic. This must
3✔
2135
                // happen before the chain arbitrator and other subsystems load
3✔
2136
                // channels, to ensure the invariant "link node exists iff
3✔
2137
                // channels exist" is maintained.
3✔
2138
                err := s.chanStateDB.RepairLinkNodes(s.cfg.ActiveNetParams.Net)
3✔
2139
                if err != nil {
3✔
2140
                        srvrLog.Errorf("Failed to repair link nodes: %v", err)
×
2141

×
2142
                        startErr = err
×
2143

×
2144
                        return
×
2145
                }
×
2146

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

2153
                cleanup = cleanup.add(s.onionMessageServer.Stop)
3✔
2154
                if err := s.onionMessageServer.Start(); err != nil {
3✔
2155
                        startErr = err
×
2156
                        return
×
2157
                }
×
2158

2159
                if s.hostAnn != nil {
3✔
2160
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2161
                        if err := s.hostAnn.Start(); err != nil {
×
2162
                                startErr = err
×
2163
                                return
×
2164
                        }
×
2165
                }
2166

2167
                if s.livenessMonitor != nil {
6✔
2168
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2169
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2170
                                startErr = err
×
2171
                                return
×
2172
                        }
×
2173
                }
2174

2175
                // Start the notification server. This is used so channel
2176
                // management goroutines can be notified when a funding
2177
                // transaction reaches a sufficient number of confirmations, or
2178
                // when the input for the funding transaction is spent in an
2179
                // attempt at an uncooperative close by the counterparty.
2180
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2181
                if err := s.sigPool.Start(); err != nil {
3✔
2182
                        startErr = err
×
2183
                        return
×
2184
                }
×
2185

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

2192
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2193
                if err := s.readPool.Start(); err != nil {
3✔
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

2198
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2199
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2200
                        startErr = err
×
2201
                        return
×
2202
                }
×
2203

2204
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2205
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2206
                        startErr = err
×
2207
                        return
×
2208
                }
×
2209

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

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

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

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

2238
                beat, err := s.getStartingBeat()
3✔
2239
                if err != nil {
3✔
2240
                        startErr = err
×
2241
                        return
×
2242
                }
×
2243

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

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

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

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

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

2274
                // htlcSwitch must be started before chainArb since the latter
2275
                // relies on htlcSwitch to deliver resolution message upon
2276
                // start.
2277
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2278
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2279
                        startErr = err
×
2280
                        return
×
2281
                }
×
2282

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

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

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

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

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

2313
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2314
                if err := s.chanRouter.Start(); err != nil {
3✔
2315
                        startErr = err
×
2316
                        return
×
2317
                }
×
2318
                // The authGossiper depends on the chanRouter and therefore
2319
                // should be started after it.
2320
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2321
                if err := s.authGossiper.Start(); err != nil {
3✔
2322
                        startErr = err
×
2323
                        return
×
2324
                }
×
2325

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

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

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

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

2350
                cleanup.add(func() error {
3✔
2351
                        s.missionController.StopStoreTickers()
×
2352
                        return nil
×
2353
                })
×
2354
                s.missionController.RunStoreTickers()
3✔
2355

3✔
2356
                // Before we start the connMgr, we'll check to see if we have
3✔
2357
                // any backups to recover. We do this now as we want to ensure
3✔
2358
                // that have all the information we need to handle channel
3✔
2359
                // recovery _before_ we even accept connections from any peers.
3✔
2360
                chanRestorer := &chanDBRestorer{
3✔
2361
                        db:         s.chanStateDB,
3✔
2362
                        secretKeys: s.cc.KeyRing,
3✔
2363
                        chainArb:   s.chainArb,
3✔
2364
                }
3✔
2365
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2366
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2367
                                s.chansToRestore.PackedSingleChanBackups,
×
2368
                                s.cc.KeyRing, chanRestorer, s,
×
2369
                        )
×
2370
                        if err != nil {
×
2371
                                startErr = fmt.Errorf("unable to unpack single "+
×
2372
                                        "backups: %v", err)
×
2373
                                return
×
2374
                        }
×
2375
                }
2376
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2377
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2378
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2379
                                s.cc.KeyRing, chanRestorer, s,
3✔
2380
                        )
3✔
2381
                        if err != nil {
3✔
2382
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2383
                                        "backup: %v", err)
×
2384
                                return
×
2385
                        }
×
2386
                }
2387

2388
                // chanSubSwapper must be started after the `channelNotifier`
2389
                // because it depends on channel events as a synchronization
2390
                // point.
2391
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2392
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2393
                        startErr = err
×
2394
                        return
×
2395
                }
×
2396

2397
                if s.torController != nil {
3✔
2398
                        cleanup = cleanup.add(s.torController.Stop)
×
2399
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2400
                                startErr = err
×
2401
                                return
×
2402
                        }
×
2403
                }
2404

2405
                if s.natTraversal != nil {
3✔
2406
                        s.wg.Add(1)
×
2407
                        go s.watchExternalIP()
×
2408
                }
×
2409

2410
                // Start connmgr last to prevent connections before init.
2411
                cleanup = cleanup.add(func() error {
3✔
2412
                        s.connMgr.Stop()
×
2413
                        return nil
×
2414
                })
×
2415

2416
                // RESOLVE: s.connMgr.Start() is called here, but
2417
                // brontide.NewListener() is called in newServer. This means
2418
                // that we are actually listening and partially accepting
2419
                // inbound connections even before the connMgr starts.
2420
                //
2421
                // TODO(yy): move the log into the connMgr's `Start` method.
2422
                srvrLog.Info("connMgr starting...")
3✔
2423
                s.connMgr.Start()
3✔
2424
                srvrLog.Debug("connMgr started")
3✔
2425

3✔
2426
                // If peers are specified as a config option, we'll add those
3✔
2427
                // peers first.
3✔
2428
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2429
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2430
                                peerAddrCfg,
3✔
2431
                        )
3✔
2432
                        if err != nil {
3✔
2433
                                startErr = fmt.Errorf("unable to parse peer "+
×
2434
                                        "pubkey from config: %v", err)
×
2435
                                return
×
2436
                        }
×
2437
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2438
                        if err != nil {
3✔
2439
                                startErr = fmt.Errorf("unable to parse peer "+
×
2440
                                        "address provided as a config option: "+
×
2441
                                        "%v", err)
×
2442
                                return
×
2443
                        }
×
2444

2445
                        peerAddr := &lnwire.NetAddress{
3✔
2446
                                IdentityKey: parsedPubkey,
3✔
2447
                                Address:     addr,
3✔
2448
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2449
                        }
3✔
2450

3✔
2451
                        err = s.ConnectToPeer(
3✔
2452
                                peerAddr, true,
3✔
2453
                                s.cfg.ConnectionTimeout,
3✔
2454
                        )
3✔
2455
                        if err != nil {
3✔
2456
                                startErr = fmt.Errorf("unable to connect to "+
×
2457
                                        "peer address provided as a config "+
×
2458
                                        "option: %v", err)
×
2459
                                return
×
2460
                        }
×
2461
                }
2462

2463
                // Subscribe to NodeAnnouncements that advertise new addresses
2464
                // our persistent peers.
2465
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2466
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2467
                                "addr: %v", err)
×
2468

×
2469
                        startErr = err
×
2470
                        return
×
2471
                }
×
2472

2473
                // With all the relevant sub-systems started, we'll now attempt
2474
                // to establish persistent connections to our direct channel
2475
                // collaborators within the network. Before doing so however,
2476
                // we'll prune our set of link nodes to ensure we don't
2477
                // reconnect to any nodes we no longer have open channels with.
2478
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2479
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2480

×
2481
                        startErr = err
×
2482
                        return
×
2483
                }
×
2484

2485
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2486
                        srvrLog.Errorf("Failed to establish persistent "+
×
2487
                                "connections: %v", err)
×
2488
                }
×
2489

2490
                // setSeedList is a helper function that turns multiple DNS seed
2491
                // server tuples from the command line or config file into the
2492
                // data structure we need and does a basic formal sanity check
2493
                // in the process.
2494
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2495
                        if len(tuples) == 0 {
×
2496
                                return
×
2497
                        }
×
2498

2499
                        result := make([][2]string, len(tuples))
×
2500
                        for idx, tuple := range tuples {
×
2501
                                tuple = strings.TrimSpace(tuple)
×
2502
                                if len(tuple) == 0 {
×
2503
                                        return
×
2504
                                }
×
2505

2506
                                servers := strings.Split(tuple, ",")
×
2507
                                if len(servers) > 2 || len(servers) == 0 {
×
2508
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2509
                                                "seed tuple: %v", servers)
×
2510
                                        return
×
2511
                                }
×
2512

2513
                                copy(result[idx][:], servers)
×
2514
                        }
2515

2516
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2517
                }
2518

2519
                // Let users overwrite the DNS seed nodes. We only allow them
2520
                // for bitcoin mainnet/testnet/signet.
2521
                if s.cfg.Bitcoin.MainNet {
3✔
2522
                        setSeedList(
×
2523
                                s.cfg.Bitcoin.DNSSeeds,
×
2524
                                chainreg.BitcoinMainnetGenesis,
×
2525
                        )
×
2526
                }
×
2527
                if s.cfg.Bitcoin.TestNet3 {
3✔
2528
                        setSeedList(
×
2529
                                s.cfg.Bitcoin.DNSSeeds,
×
2530
                                chainreg.BitcoinTestnetGenesis,
×
2531
                        )
×
2532
                }
×
2533
                if s.cfg.Bitcoin.TestNet4 {
3✔
2534
                        setSeedList(
×
2535
                                s.cfg.Bitcoin.DNSSeeds,
×
2536
                                chainreg.BitcoinTestnet4Genesis,
×
2537
                        )
×
2538
                }
×
2539
                if s.cfg.Bitcoin.SigNet {
3✔
2540
                        setSeedList(
×
2541
                                s.cfg.Bitcoin.DNSSeeds,
×
2542
                                chainreg.BitcoinSignetGenesis,
×
2543
                        )
×
2544
                }
×
2545

2546
                // If network bootstrapping hasn't been disabled, then we'll
2547
                // configure the set of active bootstrappers, and launch a
2548
                // dedicated goroutine to maintain a set of persistent
2549
                // connections.
2550
                if !s.cfg.NoNetBootstrap {
6✔
2551
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2552
                        if err != nil {
3✔
2553
                                startErr = err
×
2554
                                return
×
2555
                        }
×
2556

2557
                        s.wg.Add(1)
3✔
2558
                        go s.peerBootstrapper(
3✔
2559
                                ctx, defaultMinPeers, bootstrappers,
3✔
2560
                        )
3✔
2561
                } else {
3✔
2562
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2563
                }
3✔
2564

2565
                // Start the blockbeat after all other subsystems have been
2566
                // started so they are ready to receive new blocks.
2567
                cleanup = cleanup.add(func() error {
3✔
2568
                        s.blockbeatDispatcher.Stop()
×
2569
                        return nil
×
2570
                })
×
2571
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2572
                        startErr = err
×
2573
                        return
×
2574
                }
×
2575

2576
                // Set the active flag now that we've completed the full
2577
                // startup.
2578
                atomic.StoreInt32(&s.active, 1)
3✔
2579
        })
2580

2581
        if startErr != nil {
3✔
2582
                cleanup.run()
×
2583
        }
×
2584
        return startErr
3✔
2585
}
2586

2587
// Stop gracefully shutsdown the main daemon server. This function will signal
2588
// any active goroutines, or helper objects to exit, then blocks until they've
2589
// all successfully exited. Additionally, any/all listeners are closed.
2590
// NOTE: This function is safe for concurrent access.
2591
func (s *server) Stop() error {
3✔
2592
        s.stop.Do(func() {
6✔
2593
                atomic.StoreInt32(&s.stopping, 1)
3✔
2594

3✔
2595
                ctx := context.Background()
3✔
2596

3✔
2597
                close(s.quit)
3✔
2598

3✔
2599
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2600
                s.connMgr.Stop()
3✔
2601

3✔
2602
                // Stop dispatching blocks to other systems immediately.
3✔
2603
                s.blockbeatDispatcher.Stop()
3✔
2604

3✔
2605
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2606
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2607
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2608
                }
×
2609
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2610
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2611
                }
×
2612
                if err := s.sphinx.Stop(); err != nil {
3✔
2613
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2614
                }
×
2615
                if err := s.invoices.Stop(); err != nil {
3✔
2616
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2617
                }
×
2618
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2619
                        srvrLog.Warnf("failed to stop interceptable "+
×
2620
                                "switch: %v", err)
×
2621
                }
×
2622
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2623
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2624
                                "modifier: %v", err)
×
2625
                }
×
2626
                if err := s.chanRouter.Stop(); err != nil {
3✔
2627
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2628
                }
×
2629
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2630
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2631
                }
×
2632
                if err := s.graphDB.Stop(); err != nil {
3✔
2633
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2634
                }
×
2635
                if err := s.chainArb.Stop(); err != nil {
3✔
2636
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2637
                }
×
2638
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2639
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2640
                }
×
2641
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2642
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2643
                                err)
×
2644
                }
×
2645
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2646
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2647
                }
×
2648
                if err := s.authGossiper.Stop(); err != nil {
3✔
2649
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2650
                }
×
2651
                if err := s.sweeper.Stop(); err != nil {
3✔
2652
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2653
                }
×
2654
                if err := s.txPublisher.Stop(); err != nil {
3✔
2655
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2656
                }
×
2657
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2658
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2659
                }
×
2660
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2661
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2662
                }
×
2663
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2664
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2665
                }
×
2666

2667
                // Update channel.backup file. Make sure to do it before
2668
                // stopping chanSubSwapper.
2669
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2670
                        ctx, s.chanStateDB, s.addrSource,
3✔
2671
                )
3✔
2672
                if err != nil {
3✔
2673
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2674
                                err)
×
2675
                } else {
3✔
2676
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2677
                        if err != nil {
6✔
2678
                                srvrLog.Warnf("Manual update of channel "+
3✔
2679
                                        "backup failed: %v", err)
3✔
2680
                        }
3✔
2681
                }
2682

2683
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2684
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2685
                }
×
2686
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2688
                }
×
2689
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2691
                                err)
×
2692
                }
×
2693
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2694
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2695
                                err)
×
2696
                }
×
2697
                s.missionController.StopStoreTickers()
3✔
2698

3✔
2699
                // Disconnect from each active peers to ensure that
3✔
2700
                // peerTerminationWatchers signal completion to each peer.
3✔
2701
                for _, peer := range s.Peers() {
6✔
2702
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2703
                        if err != nil {
3✔
2704
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2705
                                        "received error: %v", peer.IdentityKey(),
×
2706
                                        err,
×
2707
                                )
×
2708
                        }
×
2709
                }
2710

2711
                // Now that all connections have been torn down, stop the tower
2712
                // client which will reliably flush all queued states to the
2713
                // tower. If this is halted for any reason, the force quit timer
2714
                // will kick in and abort to allow this method to return.
2715
                if s.towerClientMgr != nil {
6✔
2716
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2717
                                srvrLog.Warnf("Unable to shut down tower "+
×
2718
                                        "client manager: %v", err)
×
2719
                        }
×
2720
                }
2721

2722
                if s.hostAnn != nil {
3✔
2723
                        if err := s.hostAnn.Stop(); err != nil {
×
2724
                                srvrLog.Warnf("unable to shut down host "+
×
2725
                                        "annoucner: %v", err)
×
2726
                        }
×
2727
                }
2728

2729
                if s.livenessMonitor != nil {
6✔
2730
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2731
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2732
                                        "monitor: %v", err)
×
2733
                        }
×
2734
                }
2735

2736
                // Wait for all lingering goroutines to quit.
2737
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2738
                s.wg.Wait()
3✔
2739

3✔
2740
                srvrLog.Debug("Stopping buffer pools...")
3✔
2741
                s.sigPool.Stop()
3✔
2742
                s.writePool.Stop()
3✔
2743
                s.readPool.Stop()
3✔
2744
        })
2745

2746
        return nil
3✔
2747
}
2748

2749
// Stopped returns true if the server has been instructed to shutdown.
2750
// NOTE: This function is safe for concurrent access.
2751
func (s *server) Stopped() bool {
3✔
2752
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2753
}
3✔
2754

2755
// configurePortForwarding attempts to set up port forwarding for the different
2756
// ports that the server will be listening on.
2757
//
2758
// NOTE: This should only be used when using some kind of NAT traversal to
2759
// automatically set up forwarding rules.
2760
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2761
        ip, err := s.natTraversal.ExternalIP()
×
2762
        if err != nil {
×
2763
                return nil, err
×
2764
        }
×
2765
        s.lastDetectedIP = ip
×
2766

×
2767
        externalIPs := make([]string, 0, len(ports))
×
2768
        for _, port := range ports {
×
2769
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2770
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2771
                        continue
×
2772
                }
2773

2774
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2775
                externalIPs = append(externalIPs, hostIP)
×
2776
        }
2777

2778
        return externalIPs, nil
×
2779
}
2780

2781
// removePortForwarding attempts to clear the forwarding rules for the different
2782
// ports the server is currently listening on.
2783
//
2784
// NOTE: This should only be used when using some kind of NAT traversal to
2785
// automatically set up forwarding rules.
2786
func (s *server) removePortForwarding() {
×
2787
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2788
        for _, port := range forwardedPorts {
×
2789
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2790
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2791
                                "port %d: %v", port, err)
×
2792
                }
×
2793
        }
2794
}
2795

2796
// watchExternalIP continuously checks for an updated external IP address every
2797
// 15 minutes. Once a new IP address has been detected, it will automatically
2798
// handle port forwarding rules and send updated node announcements to the
2799
// currently connected peers.
2800
//
2801
// NOTE: This MUST be run as a goroutine.
2802
func (s *server) watchExternalIP() {
×
2803
        defer s.wg.Done()
×
2804

×
2805
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2806
        // up by the server.
×
2807
        defer s.removePortForwarding()
×
2808

×
2809
        // Keep track of the external IPs set by the user to avoid replacing
×
2810
        // them when detecting a new IP.
×
2811
        ipsSetByUser := make(map[string]struct{})
×
2812
        for _, ip := range s.cfg.ExternalIPs {
×
2813
                ipsSetByUser[ip.String()] = struct{}{}
×
2814
        }
×
2815

2816
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2817

×
2818
        ticker := time.NewTicker(15 * time.Minute)
×
2819
        defer ticker.Stop()
×
2820
out:
×
2821
        for {
×
2822
                select {
×
2823
                case <-ticker.C:
×
2824
                        // We'll start off by making sure a new IP address has
×
2825
                        // been detected.
×
2826
                        ip, err := s.natTraversal.ExternalIP()
×
2827
                        if err != nil {
×
2828
                                srvrLog.Debugf("Unable to retrieve the "+
×
2829
                                        "external IP address: %v", err)
×
2830
                                continue
×
2831
                        }
2832

2833
                        // Periodically renew the NAT port forwarding.
2834
                        for _, port := range forwardedPorts {
×
2835
                                err := s.natTraversal.AddPortMapping(port)
×
2836
                                if err != nil {
×
2837
                                        srvrLog.Warnf("Unable to automatically "+
×
2838
                                                "re-create port forwarding using %s: %v",
×
2839
                                                s.natTraversal.Name(), err)
×
2840
                                } else {
×
2841
                                        srvrLog.Debugf("Automatically re-created "+
×
2842
                                                "forwarding for port %d using %s to "+
×
2843
                                                "advertise external IP",
×
2844
                                                port, s.natTraversal.Name())
×
2845
                                }
×
2846
                        }
2847

2848
                        if ip.Equal(s.lastDetectedIP) {
×
2849
                                continue
×
2850
                        }
2851

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

×
2854
                        // Next, we'll craft the new addresses that will be
×
2855
                        // included in the new node announcement and advertised
×
2856
                        // to the network. Each address will consist of the new
×
2857
                        // IP detected and one of the currently advertised
×
2858
                        // ports.
×
2859
                        var newAddrs []net.Addr
×
2860
                        for _, port := range forwardedPorts {
×
2861
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2862
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2863
                                if err != nil {
×
2864
                                        srvrLog.Debugf("Unable to resolve "+
×
2865
                                                "host %v: %v", addr, err)
×
2866
                                        continue
×
2867
                                }
2868

2869
                                newAddrs = append(newAddrs, addr)
×
2870
                        }
2871

2872
                        // Skip the update if we weren't able to resolve any of
2873
                        // the new addresses.
2874
                        if len(newAddrs) == 0 {
×
2875
                                srvrLog.Debug("Skipping node announcement " +
×
2876
                                        "update due to not being able to " +
×
2877
                                        "resolve any new addresses")
×
2878
                                continue
×
2879
                        }
2880

2881
                        // Now, we'll need to update the addresses in our node's
2882
                        // announcement in order to propagate the update
2883
                        // throughout the network. We'll only include addresses
2884
                        // that have a different IP from the previous one, as
2885
                        // the previous IP is no longer valid.
2886
                        currentNodeAnn := s.getNodeAnnouncement()
×
2887

×
2888
                        for _, addr := range currentNodeAnn.Addresses {
×
2889
                                host, _, err := net.SplitHostPort(addr.String())
×
2890
                                if err != nil {
×
2891
                                        srvrLog.Debugf("Unable to determine "+
×
2892
                                                "host from address %v: %v",
×
2893
                                                addr, err)
×
2894
                                        continue
×
2895
                                }
2896

2897
                                // We'll also make sure to include external IPs
2898
                                // set manually by the user.
2899
                                _, setByUser := ipsSetByUser[addr.String()]
×
2900
                                if setByUser || host != s.lastDetectedIP.String() {
×
2901
                                        newAddrs = append(newAddrs, addr)
×
2902
                                }
×
2903
                        }
2904

2905
                        // Then, we'll generate a new timestamped node
2906
                        // announcement with the updated addresses and broadcast
2907
                        // it to our peers.
2908
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2909
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2910
                        )
×
2911
                        if err != nil {
×
2912
                                srvrLog.Debugf("Unable to generate new node "+
×
2913
                                        "announcement: %v", err)
×
2914
                                continue
×
2915
                        }
2916

2917
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2918
                        if err != nil {
×
2919
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2920
                                        "announcement to peers: %v", err)
×
2921
                                continue
×
2922
                        }
2923

2924
                        // Finally, update the last IP seen to the current one.
2925
                        s.lastDetectedIP = ip
×
2926
                case <-s.quit:
×
2927
                        break out
×
2928
                }
2929
        }
2930
}
2931

2932
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2933
// based on the server, and currently active bootstrap mechanisms as defined
2934
// within the current configuration.
2935
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2936
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2937

3✔
2938
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2939

3✔
2940
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2941
        // this can be used by default if we've already partially seeded the
3✔
2942
        // network.
3✔
2943
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2944
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2945
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2946
        )
3✔
2947
        if err != nil {
3✔
2948
                return nil, err
×
2949
        }
×
2950
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2951

3✔
2952
        // If this isn't using simnet or regtest mode, then one of our
3✔
2953
        // additional bootstrapping sources will be the set of running DNS
3✔
2954
        // seeds.
3✔
2955
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2956
                //nolint:ll
×
2957
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2958

×
2959
                // If we have a set of DNS seeds for this chain, then we'll add
×
2960
                // it as an additional bootstrapping source.
×
2961
                if ok {
×
2962
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2963
                                "seeds: %v", dnsSeeds)
×
2964

×
2965
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2966
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2967
                        )
×
2968
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2969
                }
×
2970
        }
2971

2972
        return bootStrappers, nil
3✔
2973
}
2974

2975
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2976
// needs to ignore, which is made of three parts,
2977
//   - the node itself needs to be skipped as it doesn't make sense to connect
2978
//     to itself.
2979
//   - the peers that already have connections with, as in s.peersByPub.
2980
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2981
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
2982
        s.mu.RLock()
3✔
2983
        defer s.mu.RUnlock()
3✔
2984

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

3✔
2987
        // We should ignore ourselves from bootstrapping.
3✔
2988
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
2989
        ignore[selfKey] = struct{}{}
3✔
2990

3✔
2991
        // Ignore all connected peers.
3✔
2992
        for _, peer := range s.peersByPub {
3✔
2993
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2994
                ignore[nID] = struct{}{}
×
2995
        }
×
2996

2997
        // Ignore all persistent peers as they have a dedicated reconnecting
2998
        // process.
2999
        for pubKeyStr := range s.persistentPeers {
3✔
3000
                var nID autopilot.NodeID
×
3001
                copy(nID[:], []byte(pubKeyStr))
×
3002
                ignore[nID] = struct{}{}
×
3003
        }
×
3004

3005
        return ignore
3✔
3006
}
3007

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

3✔
3016
        defer s.wg.Done()
3✔
3017

3✔
3018
        // Before we continue, init the ignore peers map.
3✔
3019
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3020

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

3✔
3025
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3026
        // peers.
3✔
3027
        //
3✔
3028
        // We'll use a 15 second backoff, and double the time every time an
3✔
3029
        // epoch fails up to a ceiling.
3✔
3030
        backOff := time.Second * 15
3✔
3031

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

3✔
3037
        // We'll use the number of attempts and errors to determine if we need
3✔
3038
        // to increase the time between discovery epochs.
3✔
3039
        var epochErrors uint32 // To be used atomically.
3✔
3040
        var epochAttempts uint32
3✔
3041

3✔
3042
        for {
6✔
3043
                select {
3✔
3044
                // The ticker has just woken us up, so we'll need to check if
3045
                // we need to attempt to connect our to any more peers.
3046
                case <-sampleTicker.C:
×
3047
                        // Obtain the current number of peers, so we can gauge
×
3048
                        // if we need to sample more peers or not.
×
3049
                        s.mu.RLock()
×
3050
                        numActivePeers := uint32(len(s.peersByPub))
×
3051
                        s.mu.RUnlock()
×
3052

×
3053
                        // If we have enough peers, then we can loop back
×
3054
                        // around to the next round as we're done here.
×
3055
                        if numActivePeers >= numTargetPeers {
×
3056
                                continue
×
3057
                        }
3058

3059
                        // If all of our attempts failed during this last back
3060
                        // off period, then will increase our backoff to 5
3061
                        // minute ceiling to avoid an excessive number of
3062
                        // queries
3063
                        //
3064
                        // TODO(roasbeef): add reverse policy too?
3065

3066
                        if epochAttempts > 0 &&
×
3067
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3068

×
3069
                                sampleTicker.Stop()
×
3070

×
3071
                                backOff *= 2
×
3072
                                if backOff > bootstrapBackOffCeiling {
×
3073
                                        backOff = bootstrapBackOffCeiling
×
3074
                                }
×
3075

3076
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3077
                                        "%v", backOff)
×
3078
                                sampleTicker = time.NewTicker(backOff)
×
3079
                                continue
×
3080
                        }
3081

3082
                        atomic.StoreUint32(&epochErrors, 0)
×
3083
                        epochAttempts = 0
×
3084

×
3085
                        // Since we know need more peers, we'll compute the
×
3086
                        // exact number we need to reach our threshold.
×
3087
                        numNeeded := numTargetPeers - numActivePeers
×
3088

×
3089
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3090
                                "peers", numNeeded)
×
3091

×
3092
                        // With the number of peers we need calculated, we'll
×
3093
                        // query the network bootstrappers to sample a set of
×
3094
                        // random addrs for us.
×
3095
                        //
×
3096
                        // Before we continue, get a copy of the ignore peers
×
3097
                        // map.
×
3098
                        ignoreList = s.createBootstrapIgnorePeers()
×
3099

×
3100
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3101
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3102
                        )
×
3103
                        if err != nil {
×
3104
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3105
                                        "peers: %v", err)
×
3106
                                continue
×
3107
                        }
3108

3109
                        // Finally, we'll launch a new goroutine for each
3110
                        // prospective peer candidates.
3111
                        for _, addr := range peerAddrs {
×
3112
                                epochAttempts++
×
3113

×
3114
                                go func(a *lnwire.NetAddress) {
×
3115
                                        // TODO(roasbeef): can do AS, subnet,
×
3116
                                        // country diversity, etc
×
3117
                                        errChan := make(chan error, 1)
×
3118
                                        s.connectToPeer(
×
3119
                                                a, errChan,
×
3120
                                                s.cfg.ConnectionTimeout,
×
3121
                                        )
×
3122
                                        select {
×
3123
                                        case err := <-errChan:
×
3124
                                                if err == nil {
×
3125
                                                        return
×
3126
                                                }
×
3127

3128
                                                srvrLog.Errorf("Unable to "+
×
3129
                                                        "connect to %v: %v",
×
3130
                                                        a, err)
×
3131
                                                atomic.AddUint32(&epochErrors, 1)
×
3132
                                        case <-s.quit:
×
3133
                                        }
3134
                                }(addr)
3135
                        }
3136
                case <-s.quit:
3✔
3137
                        return
3✔
3138
                }
3139
        }
3140
}
3141

3142
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3143
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3144
// query back off each time we encounter a failure.
3145
const bootstrapBackOffCeiling = time.Minute * 5
3146

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

3✔
3154
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3155
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3156

3✔
3157
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3158
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3159
        var delaySignal <-chan time.Time
3✔
3160
        delayTime := time.Second * 2
3✔
3161

3✔
3162
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3163
        // then the main peer bootstrap logic.
3✔
3164
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3165

3✔
3166
        for attempts := 0; ; attempts++ {
6✔
3167
                // Check if the server has been requested to shut down in order
3✔
3168
                // to prevent blocking.
3✔
3169
                if s.Stopped() {
3✔
3170
                        return
×
3171
                }
×
3172

3173
                // We can exit our aggressive initial peer bootstrapping stage
3174
                // if we've reached out target number of peers.
3175
                s.mu.RLock()
3✔
3176
                numActivePeers := uint32(len(s.peersByPub))
3✔
3177
                s.mu.RUnlock()
3✔
3178

3✔
3179
                if numActivePeers >= numTargetPeers {
5✔
3180
                        return
2✔
3181
                }
2✔
3182

3183
                if attempts > 0 {
4✔
3184
                        srvrLog.Debugf("Waiting %v before trying to locate "+
1✔
3185
                                "bootstrap peers (attempt #%v)", delayTime,
1✔
3186
                                attempts)
1✔
3187

1✔
3188
                        // We've completed at least one iterating and haven't
1✔
3189
                        // finished, so we'll start to insert a delay period
1✔
3190
                        // between each attempt.
1✔
3191
                        delaySignal = time.After(delayTime)
1✔
3192
                        select {
1✔
3193
                        case <-delaySignal:
1✔
3194
                        case <-s.quit:
1✔
3195
                                return
1✔
3196
                        }
3197

3198
                        // After our delay, we'll double the time we wait up to
3199
                        // the max back off period.
3200
                        delayTime *= 2
1✔
3201
                        if delayTime > backOffCeiling {
1✔
3202
                                delayTime = backOffCeiling
×
3203
                        }
×
3204
                }
3205

3206
                // Otherwise, we'll request for the remaining number of peers
3207
                // in order to reach our target.
3208
                peersNeeded := numTargetPeers - numActivePeers
3✔
3209
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3210
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3211
                )
3✔
3212
                if err != nil {
4✔
3213
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
1✔
3214
                                "peers: %v", err)
1✔
3215
                        continue
1✔
3216
                }
3217

3218
                // Then, we'll attempt to establish a connection to the
3219
                // different peer addresses retrieved by our bootstrappers.
3220
                var wg sync.WaitGroup
3✔
3221
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3222
                        wg.Add(1)
3✔
3223
                        go func(addr *lnwire.NetAddress) {
6✔
3224
                                defer wg.Done()
3✔
3225

3✔
3226
                                errChan := make(chan error, 1)
3✔
3227
                                go s.connectToPeer(
3✔
3228
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3229
                                )
3✔
3230

3✔
3231
                                // We'll only allow this connection attempt to
3✔
3232
                                // take up to 3 seconds. This allows us to move
3✔
3233
                                // quickly by discarding peers that are slowing
3✔
3234
                                // us down.
3✔
3235
                                select {
3✔
3236
                                case err := <-errChan:
3✔
3237
                                        if err == nil {
6✔
3238
                                                return
3✔
3239
                                        }
3✔
3240
                                        srvrLog.Errorf("Unable to connect to "+
×
3241
                                                "%v: %v", addr, err)
×
3242
                                // TODO: tune timeout? 3 seconds might be *too*
3243
                                // aggressive but works well.
3244
                                case <-time.After(3 * time.Second):
×
3245
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3246
                                                "to not establishing a "+
×
3247
                                                "connection within 3 seconds",
×
3248
                                                addr)
×
3249
                                case <-s.quit:
×
3250
                                }
3251
                        }(bootstrapAddr)
3252
                }
3253

3254
                wg.Wait()
3✔
3255
        }
3256
}
3257

3258
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3259
// order to listen for inbound connections over Tor.
3260
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3261
        // Determine the different ports the server is listening on. The onion
×
3262
        // service's virtual port will map to these ports and one will be picked
×
3263
        // at random when the onion service is being accessed.
×
3264
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3265
        for _, listenAddr := range s.listenAddrs {
×
3266
                port := listenAddr.(*net.TCPAddr).Port
×
3267
                listenPorts = append(listenPorts, port)
×
3268
        }
×
3269

3270
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3271
        if err != nil {
×
3272
                return err
×
3273
        }
×
3274

3275
        // Once the port mapping has been set, we can go ahead and automatically
3276
        // create our onion service. The service's private key will be saved to
3277
        // disk in order to regain access to this service when restarting `lnd`.
3278
        onionCfg := tor.AddOnionConfig{
×
3279
                VirtualPort: defaultPeerPort,
×
3280
                TargetPorts: listenPorts,
×
3281
                Store: tor.NewOnionFile(
×
3282
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3283
                        encrypter,
×
3284
                ),
×
3285
        }
×
3286

×
3287
        switch {
×
3288
        case s.cfg.Tor.V2:
×
3289
                onionCfg.Type = tor.V2
×
3290
        case s.cfg.Tor.V3:
×
3291
                onionCfg.Type = tor.V3
×
3292
        }
3293

3294
        addr, err := s.torController.AddOnion(onionCfg)
×
3295
        if err != nil {
×
3296
                return err
×
3297
        }
×
3298

3299
        // Now that the onion service has been created, we'll add the onion
3300
        // address it can be reached at to our list of advertised addresses.
3301
        newNodeAnn, err := s.genNodeAnnouncement(
×
3302
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3303
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3304
                },
×
3305
        )
3306
        if err != nil {
×
3307
                return fmt.Errorf("unable to generate new node "+
×
3308
                        "announcement: %v", err)
×
3309
        }
×
3310

3311
        // Finally, we'll update the on-disk version of our announcement so it
3312
        // will eventually propagate to nodes in the network.
3313
        selfNode := models.NewV1Node(
×
3314
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3315
                        Addresses:    newNodeAnn.Addresses,
×
3316
                        Features:     newNodeAnn.Features,
×
3317
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3318
                        Color:        newNodeAnn.RGBColor,
×
3319
                        Alias:        newNodeAnn.Alias.String(),
×
3320
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3321
                },
×
3322
        )
×
3323

×
3324
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3325
                return fmt.Errorf("can't set self node: %w", err)
×
3326
        }
×
3327

3328
        return nil
×
3329
}
3330

3331
// findChannel finds a channel given a public key and ChannelID. It is an
3332
// optimization that is quicker than seeking for a channel given only the
3333
// ChannelID.
3334
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3335
        *channeldb.OpenChannel, error) {
3✔
3336

3✔
3337
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3338
        if err != nil {
3✔
3339
                return nil, err
×
3340
        }
×
3341

3342
        for _, channel := range nodeChans {
6✔
3343
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3344
                        return channel, nil
3✔
3345
                }
3✔
3346
        }
3347

3348
        return nil, fmt.Errorf("unable to find channel")
3✔
3349
}
3350

3351
// getNodeAnnouncement fetches the current, fully signed node announcement.
3352
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
3✔
3353
        s.mu.Lock()
3✔
3354
        defer s.mu.Unlock()
3✔
3355

3✔
3356
        return *s.currentNodeAnn
3✔
3357
}
3✔
3358

3359
// genNodeAnnouncement generates and returns the current fully signed node
3360
// announcement. The time stamp of the announcement will be updated in order
3361
// to ensure it propagates through the network.
3362
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3363
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
3✔
3364

3✔
3365
        s.mu.Lock()
3✔
3366
        defer s.mu.Unlock()
3✔
3367

3✔
3368
        // Create a shallow copy of the current node announcement to work on.
3✔
3369
        // This ensures the original announcement remains unchanged
3✔
3370
        // until the new announcement is fully signed and valid.
3✔
3371
        newNodeAnn := *s.currentNodeAnn
3✔
3372

3✔
3373
        // First, try to update our feature manager with the updated set of
3✔
3374
        // features.
3✔
3375
        if features != nil {
6✔
3376
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3377
                        feature.SetNodeAnn: features,
3✔
3378
                }
3✔
3379
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3380
                if err != nil {
6✔
3381
                        return lnwire.NodeAnnouncement1{}, err
3✔
3382
                }
3✔
3383

3384
                // If we could successfully update our feature manager, add
3385
                // an update modifier to include these new features to our
3386
                // set.
3387
                modifiers = append(
3✔
3388
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3389
                )
3✔
3390
        }
3391

3392
        // Always update the timestamp when refreshing to ensure the update
3393
        // propagates.
3394
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3395

3✔
3396
        // Apply the requested changes to the node announcement.
3✔
3397
        for _, modifier := range modifiers {
6✔
3398
                modifier(&newNodeAnn)
3✔
3399
        }
3✔
3400

3401
        // The modifiers may have added duplicate addresses, so we need to
3402
        // de-duplicate them here.
3403
        uniqueAddrs := map[string]struct{}{}
3✔
3404
        dedupedAddrs := make([]net.Addr, 0)
3✔
3405
        for _, addr := range newNodeAnn.Addresses {
6✔
3406
                if _, ok := uniqueAddrs[addr.String()]; !ok {
6✔
3407
                        uniqueAddrs[addr.String()] = struct{}{}
3✔
3408
                        dedupedAddrs = append(dedupedAddrs, addr)
3✔
3409
                }
3✔
3410
        }
3411
        newNodeAnn.Addresses = dedupedAddrs
3✔
3412

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

3421
        // If signing succeeds, update the current announcement.
3422
        *s.currentNodeAnn = newNodeAnn
3✔
3423

3✔
3424
        return *s.currentNodeAnn, nil
3✔
3425
}
3426

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

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

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

3449
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3450
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3451
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
3✔
3452
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3453
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
3✔
3454
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3455

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

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

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

3470
        return nil
3✔
3471
}
3472

3473
type nodeAddresses struct {
3474
        pubKey    *btcec.PublicKey
3475
        addresses []net.Addr
3476
}
3477

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

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

3496
        for _, node := range linkNodes {
6✔
3497
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3498
                nodeAddrs := &nodeAddresses{
3✔
3499
                        pubKey:    node.IdentityPub,
3✔
3500
                        addresses: node.Addresses,
3✔
3501
                }
3✔
3502
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3503
        }
3✔
3504

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

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

3522
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3523

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

3533
                        // We'll only attempt to connect to Tor addresses if Tor
3534
                        // outbound support is enabled.
3535
                        case *tor.OnionAddr:
×
3536
                                if s.cfg.Tor.Active {
×
3537
                                        addrSet[addr.String()] = addr
×
3538
                                }
×
3539
                        }
3540
                }
3541

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

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

3562
                // Construct a slice of the deduped addresses.
3563
                var addrs []net.Addr
3✔
3564
                for _, addr := range addrSet {
6✔
3565
                        addrs = append(addrs, addr)
3✔
3566
                }
3✔
3567

3568
                n := &nodeAddresses{
3✔
3569
                        addresses: addrs,
3✔
3570
                }
3✔
3571
                n.pubKey, err = channelPeer.PubKey()
3✔
3572
                if err != nil {
3✔
3573
                        return err
×
3574
                }
×
3575

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

×
3588
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3589
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3590

×
3591
                        return err
×
3592
                }
×
3593
        }
3594

3595
        // Combine the addresses from the link nodes and the channel graph.
3596
        for pubStr, nodeAddr := range graphAddrs {
6✔
3597
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3598
        }
3✔
3599

3600
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3601
                len(nodeAddrsMap))
3✔
3602

3✔
3603
        // Acquire and hold server lock until all persistent connection requests
3✔
3604
        // have been recorded and sent to the connection manager.
3✔
3605
        s.mu.Lock()
3✔
3606
        defer s.mu.Unlock()
3✔
3607

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

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

3✔
3631
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3632
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3633
                }
3✔
3634

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

3✔
3645
                        go s.connectToPersistentPeer(pubStr)
3✔
3646
                } else {
3✔
3647
                        go s.delayInitialReconnect(pubStr)
×
3648
                }
×
3649

3650
                numOutboundConns++
3✔
3651
        }
3652

3653
        return nil
3✔
3654
}
3655

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

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

3✔
3675
        s.mu.Lock()
3✔
3676
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3677
                delete(s.persistentPeers, pubKeyStr)
3✔
3678
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3679
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3680
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3681
                s.mu.Unlock()
3✔
3682

3✔
3683
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3684
                        "peer has no open channels", compressedPubKey)
3✔
3685

3✔
3686
                return
3✔
3687
        }
3✔
3688
        s.mu.Unlock()
3✔
3689
}
3690

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

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

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

3731
                peers = append(peers, sPeer)
3✔
3732
        }
3733
        s.mu.RUnlock()
3✔
3734

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

3✔
3742
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3743
                wg.Add(1)
3✔
3744
                s.wg.Add(1)
3✔
3745
                go func(p lnpeer.Peer) {
6✔
3746
                        defer s.wg.Done()
3✔
3747
                        defer wg.Done()
3✔
3748

3✔
3749
                        p.SendMessageLazy(false, msgs...)
3✔
3750
                }(sPeer)
3✔
3751
        }
3752

3753
        // Wait for all messages to have been dispatched before returning to
3754
        // caller.
3755
        wg.Wait()
3✔
3756

3✔
3757
        return nil
3✔
3758
}
3759

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

3✔
3767
        s.mu.Lock()
3✔
3768

3✔
3769
        // Compute the target peer's identifier.
3✔
3770
        pubStr := string(peerKey[:])
3✔
3771

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

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

3794
                // Connected, can return early.
3795
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3796

3✔
3797
                select {
3✔
3798
                case peerChan <- peer:
3✔
UNCOV
3799
                case <-s.quit:
×
3800
                }
3801

3802
                return
3✔
3803
        }
3804

3805
        // Not connected, store this listener such that it can be notified when
3806
        // the peer comes online.
3807
        s.peerConnectedListeners[pubStr] = append(
3✔
3808
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3809
        )
3✔
3810
        s.mu.Unlock()
3✔
3811
}
3812

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

3✔
3820
        c := make(chan struct{})
3✔
3821

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

3831
        // Otherwise, the peer is online, so we'll keep track of the channel to
3832
        // trigger the notification once the server detects the peer
3833
        // disconnects.
3834
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3835
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3836
        )
3✔
3837

3✔
3838
        return c
3✔
3839
}
3840

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

3✔
3850
        pubStr := string(peerKey.SerializeCompressed())
3✔
3851

3✔
3852
        return s.findPeerByPubStr(pubStr)
3✔
3853
}
3✔
3854

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

3✔
3864
        return s.findPeerByPubStr(pubStr)
3✔
3865
}
3✔
3866

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

3875
        return peer, nil
3✔
3876
}
3877

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

3✔
3884
        // Now, determine the appropriate backoff to use for the retry.
3✔
3885
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3886
        if !ok {
6✔
3887
                // If an existing backoff was unknown, use the default.
3✔
3888
                return s.cfg.MinBackoff
3✔
3889
        }
3✔
3890

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

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

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

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

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

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

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

3950
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3951
        pubSer := nodePub.SerializeCompressed()
3✔
3952
        pubStr := string(pubSer)
3✔
3953

3✔
3954
        var pubBytes [33]byte
3✔
3955
        copy(pubBytes[:], pubSer)
3✔
3956

3✔
3957
        s.mu.Lock()
3✔
3958
        defer s.mu.Unlock()
3✔
3959

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

3✔
3967
                conn.Close()
3✔
3968
                return
3✔
3969
        }
3✔
3970

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

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

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

3996
        case nil:
3✔
3997
                ctx := btclog.WithCtx(
3✔
3998
                        context.TODO(),
3✔
3999
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4000
                )
3✔
4001

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

×
4011
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4012
                                "peer, but already have outbound "+
×
4013
                                "connection, dropping conn",
×
4014
                                fmt.Errorf("already have outbound conn"))
×
4015
                        conn.Close()
×
4016
                        return
×
4017
                }
×
4018

4019
                // Otherwise, if we should drop the connection, then we'll
4020
                // disconnect our already connected peer.
4021
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4022

3✔
4023
                s.cancelConnReqs(pubStr, nil)
3✔
4024

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

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

4046
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4047
        pubSer := nodePub.SerializeCompressed()
3✔
4048
        pubStr := string(pubSer)
3✔
4049

3✔
4050
        var pubBytes [33]byte
3✔
4051
        copy(pubBytes[:], pubSer)
3✔
4052

3✔
4053
        s.mu.Lock()
3✔
4054
        defer s.mu.Unlock()
3✔
4055

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

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

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

×
4082
                if connReq != nil {
×
4083
                        s.connMgr.Remove(connReq.ID())
×
4084
                }
×
4085

4086
                conn.Close()
×
4087
                return
×
4088
        }
4089

4090
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4091
                conn.RemoteAddr())
3✔
4092

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

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

4116
        case nil:
3✔
4117
                ctx := btclog.WithCtx(
3✔
4118
                        context.TODO(),
3✔
4119
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4120
                )
3✔
4121

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

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

4142
                // Otherwise, _their_ connection should be dropped. So we'll
4143
                // disconnect the peer and send the now obsolete peer to the
4144
                // server for garbage collection.
4145
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4146

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

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

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

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

4186
        for _, connReq := range connReqs {
6✔
4187
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4188

3✔
4189
                // Atomically capture the current request identifier.
3✔
4190
                connID := connReq.ID()
3✔
4191

3✔
4192
                // Skip any zero IDs, this indicates the request has not
3✔
4193
                // yet been schedule.
3✔
4194
                if connID == UnassignedConnID {
3✔
4195
                        continue
×
4196
                }
4197

4198
                // Skip a particular connection ID if instructed.
4199
                if skip != nil && connID == *skip {
6✔
4200
                        continue
3✔
4201
                }
4202

4203
                s.connMgr.Remove(connID)
3✔
4204
        }
4205

4206
        delete(s.persistentConnReqs, pubStr)
3✔
4207
}
4208

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

3✔
4215
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4216
                Peer: peer,
3✔
4217
                Msg:  msg,
3✔
4218
        })
3✔
4219
}
3✔
4220

4221
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4222
// messages.
4223
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4224
        return s.customMessageServer.Subscribe()
3✔
4225
}
3✔
4226

4227
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4228
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4229
        return s.onionMessageServer.Subscribe()
3✔
4230
}
3✔
4231

4232
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4233
// the channelNotifier's NotifyOpenChannelEvent.
4234
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4235
        remotePub *btcec.PublicKey) {
3✔
4236

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

4243
        // Notify subscribers about this open channel event.
4244
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4245
}
4246

4247
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4248
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4249
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4250
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4251

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

4260
        // Notify subscribers about this event.
4261
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4262
}
4263

4264
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4265
// calls the channelNotifier's NotifyFundingTimeout.
4266
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4267
        remotePub *btcec.PublicKey) {
3✔
4268

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

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

4285
        // Notify subscribers about this event.
4286
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4287
}
4288

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

3✔
4296
        brontideConn := conn.(*brontide.Conn)
3✔
4297
        addr := conn.RemoteAddr()
3✔
4298
        pubKey := brontideConn.RemotePub()
3✔
4299

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

×
4310
                // Clean up the persistent peer maps if we're dropping this
×
4311
                // connection.
×
4312
                s.bannedPersistentPeerConnection(string(pubSer))
×
4313

×
4314
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4315
                        "of restricted-access connection slots: %v.", pubSer,
×
4316
                        err)
×
4317

×
4318
                conn.Close()
×
4319

×
4320
                return
×
4321
        }
×
4322

4323
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4324
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4325

3✔
4326
        peerAddr := &lnwire.NetAddress{
3✔
4327
                IdentityKey: pubKey,
3✔
4328
                Address:     addr,
3✔
4329
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4330
        }
3✔
4331

3✔
4332
        // With the brontide connection established, we'll now craft the feature
3✔
4333
        // vectors to advertise to the remote node.
3✔
4334
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4335
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4336

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

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

4361
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4362
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4363

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

3✔
4408
                        return s.genNodeAnnouncement(nil)
3✔
4409
                },
3✔
4410

4411
                PongBuf: s.pongBuf,
4412

4413
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4414

4415
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4416

4417
                FundingManager: s.fundingMgr,
4418

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

4452
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4453
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4454

3✔
4455
        p := peer.NewBrontide(pCfg)
3✔
4456

3✔
4457
        // Update the access manager with the access permission for this peer.
3✔
4458
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4459

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

3✔
4463
        s.addPeer(p)
3✔
4464

3✔
4465
        // Once we have successfully added the peer to the server, we can
3✔
4466
        // delete the previous error buffer from the server's map of error
3✔
4467
        // buffers.
3✔
4468
        delete(s.peerErrors, pkStr)
3✔
4469

3✔
4470
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4471
        // includes sending and receiving Init messages, which would be a DOS
3✔
4472
        // vector if we held the server's mutex throughout the procedure.
3✔
4473
        s.wg.Add(1)
3✔
4474
        go s.peerInitializer(p)
3✔
4475
}
4476

4477
// addPeer adds the passed peer to the server's global state of all active
4478
// peers.
4479
func (s *server) addPeer(p *peer.Brontide) {
3✔
4480
        if p == nil {
3✔
4481
                return
×
4482
        }
×
4483

4484
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4485

3✔
4486
        // Ignore new peers if we're shutting down.
3✔
4487
        if s.Stopped() {
3✔
4488
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4489
                        pubBytes)
×
4490
                p.Disconnect(ErrServerShuttingDown)
×
4491

×
4492
                return
×
4493
        }
×
4494

4495
        // Track the new peer in our indexes so we can quickly look it up either
4496
        // according to its public key, or its peer ID.
4497
        // TODO(roasbeef): pipe all requests through to the
4498
        // queryHandler/peerManager
4499

4500
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4501
        // be human-readable.
4502
        pubStr := string(pubBytes)
3✔
4503

3✔
4504
        s.peersByPub[pubStr] = p
3✔
4505

3✔
4506
        if p.Inbound() {
6✔
4507
                s.inboundPeers[pubStr] = p
3✔
4508
        } else {
6✔
4509
                s.outboundPeers[pubStr] = p
3✔
4510
        }
3✔
4511

4512
        // Inform the peer notifier of a peer online event so that it can be reported
4513
        // to clients listening for peer events.
4514
        var pubKey [33]byte
3✔
4515
        copy(pubKey[:], pubBytes)
3✔
4516
}
4517

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

3✔
4530
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4531

3✔
4532
        // Avoid initializing peers while the server is exiting.
3✔
4533
        if s.Stopped() {
3✔
4534
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4535
                        pubBytes)
×
4536
                return
×
4537
        }
×
4538

4539
        // Create a channel that will be used to signal a successful start of
4540
        // the link. This prevents the peer termination watcher from beginning
4541
        // its duty too early.
4542
        ready := make(chan struct{})
3✔
4543

3✔
4544
        // Before starting the peer, launch a goroutine to watch for the
3✔
4545
        // unexpected termination of this peer, which will ensure all resources
3✔
4546
        // are properly cleaned up, and re-establish persistent connections when
3✔
4547
        // necessary. The peer termination watcher will be short circuited if
3✔
4548
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4549
        // that the server has already handled the removal of this peer.
3✔
4550
        s.wg.Add(1)
3✔
4551
        go s.peerTerminationWatcher(p, ready)
3✔
4552

3✔
4553
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4554
        // will unblock the peerTerminationWatcher.
3✔
4555
        if err := p.Start(); err != nil {
6✔
4556
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4557

3✔
4558
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4559
                return
3✔
4560
        }
3✔
4561

4562
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4563
        // was successful, and to begin watching the peer's wait group.
4564
        close(ready)
3✔
4565

3✔
4566
        s.mu.Lock()
3✔
4567
        defer s.mu.Unlock()
3✔
4568

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

3✔
4572
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4573
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4574
        pubStr := string(pubBytes)
3✔
4575
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4576
                select {
3✔
4577
                case peerChan <- p:
3✔
4578
                case <-s.quit:
×
4579
                        return
×
4580
                }
4581
        }
4582
        delete(s.peerConnectedListeners, pubStr)
3✔
4583

3✔
4584
        // Since the peer has been fully initialized, now it's time to notify
3✔
4585
        // the RPC about the peer online event.
3✔
4586
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4587
}
4588

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

3✔
4603
        ctx := btclog.WithCtx(
3✔
4604
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4605
        )
3✔
4606

3✔
4607
        p.WaitForDisconnect(ready)
3✔
4608

3✔
4609
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4610

3✔
4611
        // If the server is exiting then we can bail out early ourselves as all
3✔
4612
        // the other sub-systems will already be shutting down.
3✔
4613
        if s.Stopped() {
6✔
4614
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4615
                return
3✔
4616
        }
3✔
4617

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

3✔
4624
        pubKey := p.IdentityKey()
3✔
4625

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

3✔
4630
        // Tell the switch to remove all links associated with this peer.
3✔
4631
        // Passing nil as the target link indicates that all links associated
3✔
4632
        // with this interface should be closed.
3✔
4633
        //
3✔
4634
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4635
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4636
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4637
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4638
        }
×
4639

4640
        for _, link := range links {
6✔
4641
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4642
        }
3✔
4643

4644
        s.mu.Lock()
3✔
4645
        defer s.mu.Unlock()
3✔
4646

3✔
4647
        // If there were any notification requests for when this peer
3✔
4648
        // disconnected, we can trigger them now.
3✔
4649
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4650
        pubStr := string(pubKey.SerializeCompressed())
3✔
4651
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4652
                close(offlineChan)
3✔
4653
        }
3✔
4654
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4655

3✔
4656
        // If the server has already removed this peer, we can short circuit the
3✔
4657
        // peer termination watcher and skip cleanup.
3✔
4658
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4659
                delete(s.ignorePeerTermination, p)
3✔
4660

3✔
4661
                pubKey := p.PubKey()
3✔
4662
                pubStr := string(pubKey[:])
3✔
4663

3✔
4664
                // If a connection callback is present, we'll go ahead and
3✔
4665
                // execute it now that previous peer has fully disconnected. If
3✔
4666
                // the callback is not present, this likely implies the peer was
3✔
4667
                // purposefully disconnected via RPC, and that no reconnect
3✔
4668
                // should be attempted.
3✔
4669
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4670
                if ok {
6✔
4671
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4672
                        connCallback()
3✔
4673
                }
3✔
4674
                return
3✔
4675
        }
4676

4677
        // First, cleanup any remaining state the server has regarding the peer
4678
        // in question.
4679
        s.removePeerUnsafe(ctx, p)
3✔
4680

3✔
4681
        // Next, check to see if this is a persistent peer or not.
3✔
4682
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4683
                return
3✔
4684
        }
3✔
4685

4686
        // Get the last address that we used to connect to the peer.
4687
        addrs := []net.Addr{
3✔
4688
                p.NetAddress().Address,
3✔
4689
        }
3✔
4690

3✔
4691
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4692
        // reconnection purposes.
3✔
4693
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4694
        switch {
3✔
4695
        // We found advertised addresses, so use them.
4696
        case err == nil:
3✔
4697
                addrs = advertisedAddrs
3✔
4698

4699
        // The peer doesn't have an advertised address.
4700
        case err == errNoAdvertisedAddr:
3✔
4701
                // If it is an outbound peer then we fall back to the existing
3✔
4702
                // peer address.
3✔
4703
                if !p.Inbound() {
6✔
4704
                        break
3✔
4705
                }
4706

4707
                // Fall back to the existing peer address if
4708
                // we're not accepting connections over Tor.
4709
                if s.torController == nil {
6✔
4710
                        break
3✔
4711
                }
4712

4713
                // If we are, the peer's address won't be known
4714
                // to us (we'll see a private address, which is
4715
                // the address used by our onion service to dial
4716
                // to lnd), so we don't have enough information
4717
                // to attempt a reconnect.
4718
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4719
                        "to inbound peer without advertised address")
×
4720
                return
×
4721

4722
        // We came across an error retrieving an advertised
4723
        // address, log it, and fall back to the existing peer
4724
        // address.
4725
        default:
3✔
4726
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4727
                        "address for peer", err)
3✔
4728
        }
4729

4730
        // Make an easy lookup map so that we can check if an address
4731
        // is already in the address list that we have stored for this peer.
4732
        existingAddrs := make(map[string]bool)
3✔
4733
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4734
                existingAddrs[addr.String()] = true
3✔
4735
        }
3✔
4736

4737
        // Add any missing addresses for this peer to persistentPeerAddr.
4738
        for _, addr := range addrs {
6✔
4739
                if existingAddrs[addr.String()] {
3✔
4740
                        continue
×
4741
                }
4742

4743
                s.persistentPeerAddrs[pubStr] = append(
3✔
4744
                        s.persistentPeerAddrs[pubStr],
3✔
4745
                        &lnwire.NetAddress{
3✔
4746
                                IdentityKey: p.IdentityKey(),
3✔
4747
                                Address:     addr,
3✔
4748
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4749
                        },
3✔
4750
                )
3✔
4751
        }
4752

4753
        // Record the computed backoff in the backoff map.
4754
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4755
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4756

3✔
4757
        // Initialize a retry canceller for this peer if one does not
3✔
4758
        // exist.
3✔
4759
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4760
        if !ok {
6✔
4761
                cancelChan = make(chan struct{})
3✔
4762
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4763
        }
3✔
4764

4765
        // We choose not to wait group this go routine since the Connect
4766
        // call can stall for arbitrarily long if we shutdown while an
4767
        // outbound connection attempt is being made.
4768
        go func() {
6✔
4769
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4770
                        "re-establishment to persistent peer",
3✔
4771
                        "reconnecting_in", backoff)
3✔
4772

3✔
4773
                select {
3✔
4774
                case <-time.After(backoff):
3✔
4775
                case <-cancelChan:
3✔
4776
                        return
3✔
4777
                case <-s.quit:
3✔
4778
                        return
3✔
4779
                }
4780

4781
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4782
                        "connection")
3✔
4783

3✔
4784
                s.connectToPersistentPeer(pubStr)
3✔
4785
        }()
4786
}
4787

4788
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4789
// to connect to the peer. It creates connection requests if there are
4790
// currently none for a given address and it removes old connection requests
4791
// if the associated address is no longer in the latest address list for the
4792
// peer.
4793
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4794
        s.mu.Lock()
3✔
4795
        defer s.mu.Unlock()
3✔
4796

3✔
4797
        // Create an easy lookup map of the addresses we have stored for the
3✔
4798
        // peer. We will remove entries from this map if we have existing
3✔
4799
        // connection requests for the associated address and then any leftover
3✔
4800
        // entries will indicate which addresses we should create new
3✔
4801
        // connection requests for.
3✔
4802
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4803
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4804
                addrMap[addr.String()] = addr
3✔
4805
        }
3✔
4806

4807
        // Go through each of the existing connection requests and
4808
        // check if they correspond to the latest set of addresses. If
4809
        // there is a connection requests that does not use one of the latest
4810
        // advertised addresses then remove that connection request.
4811
        var updatedConnReqs []*connmgr.ConnReq
3✔
4812
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4813
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4814

3✔
4815
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4816
                // If the existing connection request is using one of the
4817
                // latest advertised addresses for the peer then we add it to
4818
                // updatedConnReqs and remove the associated address from
4819
                // addrMap so that we don't recreate this connReq later on.
4820
                case true:
×
4821
                        updatedConnReqs = append(
×
4822
                                updatedConnReqs, connReq,
×
4823
                        )
×
4824
                        delete(addrMap, lnAddr)
×
4825

4826
                // If the existing connection request is using an address that
4827
                // is not one of the latest advertised addresses for the peer
4828
                // then we remove the connecting request from the connection
4829
                // manager.
4830
                case false:
3✔
4831
                        srvrLog.Info(
3✔
4832
                                "Removing conn req:", connReq.Addr.String(),
3✔
4833
                        )
3✔
4834
                        s.connMgr.Remove(connReq.ID())
3✔
4835
                }
4836
        }
4837

4838
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4839

3✔
4840
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4841
        if !ok {
6✔
4842
                cancelChan = make(chan struct{})
3✔
4843
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4844
        }
3✔
4845

4846
        // Any addresses left in addrMap are new ones that we have not made
4847
        // connection requests for. So create new connection requests for those.
4848
        // If there is more than one address in the address map, stagger the
4849
        // creation of the connection requests for those.
4850
        go func() {
6✔
4851
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4852
                defer ticker.Stop()
3✔
4853

3✔
4854
                for _, addr := range addrMap {
6✔
4855
                        // Send the persistent connection request to the
3✔
4856
                        // connection manager, saving the request itself so we
3✔
4857
                        // can cancel/restart the process as needed.
3✔
4858
                        connReq := &connmgr.ConnReq{
3✔
4859
                                Addr:      addr,
3✔
4860
                                Permanent: true,
3✔
4861
                        }
3✔
4862

3✔
4863
                        s.mu.Lock()
3✔
4864
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4865
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4866
                        )
3✔
4867
                        s.mu.Unlock()
3✔
4868

3✔
4869
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4870
                                "channel peer %v", addr)
3✔
4871

3✔
4872
                        go s.connMgr.Connect(connReq)
3✔
4873

3✔
4874
                        select {
3✔
4875
                        case <-s.quit:
3✔
4876
                                return
3✔
4877
                        case <-cancelChan:
3✔
4878
                                return
3✔
4879
                        case <-ticker.C:
3✔
4880
                        }
4881
                }
4882
        }()
4883
}
4884

4885
// removePeerUnsafe removes the passed peer from the server's state of all
4886
// active peers.
4887
//
4888
// NOTE: Server mutex must be held when calling this function.
4889
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4890
        if p == nil {
3✔
4891
                return
×
4892
        }
×
4893

4894
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4895

3✔
4896
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4897
        // will be disconnected in the server shutdown process.
3✔
4898
        if s.Stopped() {
3✔
4899
                return
×
4900
        }
×
4901

4902
        // Capture the peer's public key and string representation.
4903
        pKey := p.PubKey()
3✔
4904
        pubSer := pKey[:]
3✔
4905
        pubStr := string(pubSer)
3✔
4906

3✔
4907
        delete(s.peersByPub, pubStr)
3✔
4908

3✔
4909
        if p.Inbound() {
6✔
4910
                delete(s.inboundPeers, pubStr)
3✔
4911
        } else {
6✔
4912
                delete(s.outboundPeers, pubStr)
3✔
4913
        }
3✔
4914

4915
        // When removing the peer we make sure to disconnect it asynchronously
4916
        // to avoid blocking the main server goroutine because it is holding the
4917
        // server's mutex. Disconnecting the peer might block and wait until the
4918
        // peer has fully started up. This can happen if an inbound and outbound
4919
        // race condition occurs.
4920
        s.wg.Add(1)
3✔
4921
        go func() {
6✔
4922
                defer s.wg.Done()
3✔
4923

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

3✔
4926
                // If this peer had an active persistent connection request,
3✔
4927
                // remove it.
3✔
4928
                if p.ConnReq() != nil {
6✔
4929
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4930
                }
3✔
4931

4932
                // Remove the peer's access permission from the access manager.
4933
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4934
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4935

3✔
4936
                // Copy the peer's error buffer across to the server if it has
3✔
4937
                // any items in it so that we can restore peer errors across
3✔
4938
                // connections. We need to look up the error after the peer has
3✔
4939
                // been disconnected because we write the error in the
3✔
4940
                // `Disconnect` method.
3✔
4941
                s.mu.Lock()
3✔
4942
                if p.ErrorBuffer().Total() > 0 {
6✔
4943
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4944
                }
3✔
4945
                s.mu.Unlock()
3✔
4946

3✔
4947
                // Inform the peer notifier of a peer offline event so that it
3✔
4948
                // can be reported to clients listening for peer events.
3✔
4949
                var pubKey [33]byte
3✔
4950
                copy(pubKey[:], pubSer)
3✔
4951

3✔
4952
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4953
        }()
4954
}
4955

4956
// ConnectToPeer requests that the server connect to a Lightning Network peer
4957
// at the specified address. This function will *block* until either a
4958
// connection is established, or the initial handshake process fails.
4959
//
4960
// NOTE: This function is safe for concurrent access.
4961
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4962
        perm bool, timeout time.Duration) error {
3✔
4963

3✔
4964
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4965

3✔
4966
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4967
        // better granularity.  In certain conditions, this method requires
3✔
4968
        // making an outbound connection to a remote peer, which requires the
3✔
4969
        // lock to be released, and subsequently reacquired.
3✔
4970
        s.mu.Lock()
3✔
4971

3✔
4972
        // Ensure we're not already connected to this peer.
3✔
4973
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4974

3✔
4975
        // When there's no error it means we already have a connection with this
3✔
4976
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
4977
        // set, we will ignore the existing connection and continue.
3✔
4978
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
4979
                s.mu.Unlock()
3✔
4980
                return &errPeerAlreadyConnected{peer: peer}
3✔
4981
        }
3✔
4982

4983
        // Peer was not found, continue to pursue connection with peer.
4984

4985
        // If there's already a pending connection request for this pubkey,
4986
        // then we ignore this request to ensure we don't create a redundant
4987
        // connection.
4988
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4989
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4990
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4991
        }
3✔
4992

4993
        // If there's not already a pending or active connection to this node,
4994
        // then instruct the connection manager to attempt to establish a
4995
        // persistent connection to the peer.
4996
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4997
        if perm {
6✔
4998
                connReq := &connmgr.ConnReq{
3✔
4999
                        Addr:      addr,
3✔
5000
                        Permanent: true,
3✔
5001
                }
3✔
5002

3✔
5003
                // Since the user requested a permanent connection, we'll set
3✔
5004
                // the entry to true which will tell the server to continue
3✔
5005
                // reconnecting even if the number of channels with this peer is
3✔
5006
                // zero.
3✔
5007
                s.persistentPeers[targetPub] = true
3✔
5008
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5009
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5010
                }
3✔
5011
                s.persistentConnReqs[targetPub] = append(
3✔
5012
                        s.persistentConnReqs[targetPub], connReq,
3✔
5013
                )
3✔
5014
                s.mu.Unlock()
3✔
5015

3✔
5016
                go s.connMgr.Connect(connReq)
3✔
5017

3✔
5018
                return nil
3✔
5019
        }
5020
        s.mu.Unlock()
3✔
5021

3✔
5022
        // If we're not making a persistent connection, then we'll attempt to
3✔
5023
        // connect to the target peer. If the we can't make the connection, or
3✔
5024
        // the crypto negotiation breaks down, then return an error to the
3✔
5025
        // caller.
3✔
5026
        errChan := make(chan error, 1)
3✔
5027
        s.connectToPeer(addr, errChan, timeout)
3✔
5028

3✔
5029
        select {
3✔
5030
        case err := <-errChan:
3✔
5031
                return err
3✔
5032
        case <-s.quit:
×
5033
                return ErrServerShuttingDown
×
5034
        }
5035
}
5036

5037
// connectToPeer establishes a connection to a remote peer. errChan is used to
5038
// notify the caller if the connection attempt has failed. Otherwise, it will be
5039
// closed.
5040
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5041
        errChan chan<- error, timeout time.Duration) {
3✔
5042

3✔
5043
        conn, err := brontide.Dial(
3✔
5044
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5045
        )
3✔
5046
        if err != nil {
6✔
5047
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5048
                select {
3✔
5049
                case errChan <- err:
3✔
5050
                case <-s.quit:
×
5051
                }
5052
                return
3✔
5053
        }
5054

5055
        close(errChan)
3✔
5056

3✔
5057
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5058
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5059

3✔
5060
        s.OutboundPeerConnected(nil, conn)
3✔
5061
}
5062

5063
// DisconnectPeer sends the request to server to close the connection with peer
5064
// identified by public key.
5065
//
5066
// NOTE: This function is safe for concurrent access.
5067
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5068
        pubBytes := pubKey.SerializeCompressed()
3✔
5069
        pubStr := string(pubBytes)
3✔
5070

3✔
5071
        s.mu.Lock()
3✔
5072
        defer s.mu.Unlock()
3✔
5073

3✔
5074
        // Check that were actually connected to this peer. If not, then we'll
3✔
5075
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5076
        // currently connected to.
3✔
5077
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5078
        if err == ErrPeerNotConnected {
6✔
5079
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5080
        }
3✔
5081

5082
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5083

3✔
5084
        s.cancelConnReqs(pubStr, nil)
3✔
5085

3✔
5086
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5087
        // them from this map so we don't attempt to re-connect after we
3✔
5088
        // disconnect.
3✔
5089
        delete(s.persistentPeers, pubStr)
3✔
5090
        delete(s.persistentPeersBackoff, pubStr)
3✔
5091

3✔
5092
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5093
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5094
        //
3✔
5095
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5096
        // goroutine because we might hold the server's mutex.
3✔
5097
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5098

3✔
5099
        return nil
3✔
5100
}
5101

5102
// OpenChannel sends a request to the server to open a channel to the specified
5103
// peer identified by nodeKey with the passed channel funding parameters.
5104
//
5105
// NOTE: This function is safe for concurrent access.
5106
func (s *server) OpenChannel(
5107
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5108

3✔
5109
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5110
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5111
        // not blocked if the caller is not reading the updates.
3✔
5112
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5113
        req.Err = make(chan error, 1)
3✔
5114

3✔
5115
        // First attempt to locate the target peer to open a channel with, if
3✔
5116
        // we're unable to locate the peer then this request will fail.
3✔
5117
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5118
        s.mu.RLock()
3✔
5119
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5120
        if !ok {
3✔
5121
                s.mu.RUnlock()
×
5122

×
5123
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5124
                return req.Updates, req.Err
×
5125
        }
×
5126
        req.Peer = peer
3✔
5127
        s.mu.RUnlock()
3✔
5128

3✔
5129
        // We'll wait until the peer is active before beginning the channel
3✔
5130
        // opening process.
3✔
5131
        select {
3✔
5132
        case <-peer.ActiveSignal():
3✔
5133
        case <-peer.QuitSignal():
×
5134
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5135
                return req.Updates, req.Err
×
5136
        case <-s.quit:
×
5137
                req.Err <- ErrServerShuttingDown
×
5138
                return req.Updates, req.Err
×
5139
        }
5140

5141
        // If the fee rate wasn't specified at this point we fail the funding
5142
        // because of the missing fee rate information. The caller of the
5143
        // `OpenChannel` method needs to make sure that default values for the
5144
        // fee rate are set beforehand.
5145
        if req.FundingFeePerKw == 0 {
3✔
5146
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5147
                        "the channel opening transaction")
×
5148

×
5149
                return req.Updates, req.Err
×
5150
        }
×
5151

5152
        // Spawn a goroutine to send the funding workflow request to the funding
5153
        // manager. This allows the server to continue handling queries instead
5154
        // of blocking on this request which is exported as a synchronous
5155
        // request to the outside world.
5156
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5157

3✔
5158
        return req.Updates, req.Err
3✔
5159
}
5160

5161
// Peers returns a slice of all active peers.
5162
//
5163
// NOTE: This function is safe for concurrent access.
5164
func (s *server) Peers() []*peer.Brontide {
3✔
5165
        s.mu.RLock()
3✔
5166
        defer s.mu.RUnlock()
3✔
5167

3✔
5168
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5169
        for _, peer := range s.peersByPub {
6✔
5170
                peers = append(peers, peer)
3✔
5171
        }
3✔
5172

5173
        return peers
3✔
5174
}
5175

5176
// computeNextBackoff uses a truncated exponential backoff to compute the next
5177
// backoff using the value of the exiting backoff. The returned duration is
5178
// randomized in either direction by 1/20 to prevent tight loops from
5179
// stabilizing.
5180
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5181
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5182
        nextBackoff := 2 * currBackoff
3✔
5183
        if nextBackoff > maxBackoff {
6✔
5184
                nextBackoff = maxBackoff
3✔
5185
        }
3✔
5186

5187
        // Using 1/10 of our duration as a margin, compute a random offset to
5188
        // avoid the nodes entering connection cycles.
5189
        margin := nextBackoff / 10
3✔
5190

3✔
5191
        var wiggle big.Int
3✔
5192
        wiggle.SetUint64(uint64(margin))
3✔
5193
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5194
                // Randomizing is not mission critical, so we'll just return the
×
5195
                // current backoff.
×
5196
                return nextBackoff
×
5197
        }
×
5198

5199
        // Otherwise add in our wiggle, but subtract out half of the margin so
5200
        // that the backoff can tweaked by 1/20 in either direction.
5201
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5202
}
5203

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

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

3✔
5212
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5213
        if err != nil {
3✔
5214
                return nil, err
×
5215
        }
×
5216

5217
        node, err := s.v1Graph.FetchNode(ctx, vertex)
3✔
5218
        if err != nil {
6✔
5219
                return nil, err
3✔
5220
        }
3✔
5221

5222
        if len(node.Addresses) == 0 {
6✔
5223
                return nil, errNoAdvertisedAddr
3✔
5224
        }
3✔
5225

5226
        return node.Addresses, nil
3✔
5227
}
5228

5229
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5230
// channel update for a target channel.
5231
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5232
        *lnwire.ChannelUpdate1, error) {
3✔
5233

3✔
5234
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5235
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5236
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5237
                if err != nil {
6✔
5238
                        return nil, err
3✔
5239
                }
3✔
5240

5241
                return netann.ExtractChannelUpdate(
3✔
5242
                        ourPubKey[:], info, edge1, edge2,
3✔
5243
                )
3✔
5244
        }
5245
}
5246

5247
// applyChannelUpdate applies the channel update to the different sub-systems of
5248
// the server. The useAlias boolean denotes whether or not to send an alias in
5249
// place of the real SCID.
5250
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5251
        op *wire.OutPoint, useAlias bool) error {
3✔
5252

3✔
5253
        var (
3✔
5254
                peerAlias    *lnwire.ShortChannelID
3✔
5255
                defaultAlias lnwire.ShortChannelID
3✔
5256
        )
3✔
5257

3✔
5258
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5259

3✔
5260
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5261
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5262
        if useAlias {
6✔
5263
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5264
                if foundAlias != defaultAlias {
6✔
5265
                        peerAlias = &foundAlias
3✔
5266
                }
3✔
5267
        }
5268

5269
        fut := s.authGossiper.ProcessLocalAnnouncement(
3✔
5270
                update, discovery.RemoteAlias(peerAlias),
3✔
5271
        )
3✔
5272

3✔
5273
        ctx, cancel := lnutils.ContextFromQuit(s.quit)
3✔
5274
        defer cancel()
3✔
5275

3✔
5276
        return discovery.AwaitGossipResult(ctx, fut)
3✔
5277
}
5278

5279
// SendCustomMessage sends a custom message to the peer with the specified
5280
// pubkey.
5281
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5282
        msgType lnwire.MessageType, data []byte) error {
3✔
5283

3✔
5284
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5285
        if err != nil {
6✔
5286
                return err
3✔
5287
        }
3✔
5288

5289
        // We'll wait until the peer is active, but also listen for
5290
        // cancellation.
5291
        select {
3✔
5292
        case <-peer.ActiveSignal():
3✔
5293
        case <-peer.QuitSignal():
×
5294
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5295
        case <-s.quit:
×
5296
                return ErrServerShuttingDown
×
5297
        case <-ctx.Done():
×
5298
                return ctx.Err()
×
5299
        }
5300

5301
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5302
        if err != nil {
6✔
5303
                return err
3✔
5304
        }
3✔
5305

5306
        // Send the message as low-priority. For now we assume that all
5307
        // application-defined message are low priority.
5308
        return peer.SendMessageLazy(true, msg)
3✔
5309
}
5310

5311
// SendOnionMessage sends a custom message to the peer with the specified
5312
// pubkey.
5313
// TODO(gijs): change this message to include path finding.
5314
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5315
        pathKey *btcec.PublicKey, onion []byte) error {
3✔
5316

3✔
5317
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5318
        if err != nil {
3✔
5319
                return err
×
5320
        }
×
5321

5322
        // We'll wait until the peer is active, but also listen for
5323
        // cancellation.
5324
        select {
3✔
5325
        case <-peer.ActiveSignal():
3✔
5326
        case <-peer.QuitSignal():
×
5327
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5328
        case <-s.quit:
×
5329
                return ErrServerShuttingDown
×
5330
        case <-ctx.Done():
×
5331
                return ctx.Err()
×
5332
        }
5333

5334
        msg := lnwire.NewOnionMessage(pathKey, onion)
3✔
5335

3✔
5336
        // Send the message as low-priority. For now we assume that all
3✔
5337
        // application-defined message are low priority.
3✔
5338
        return peer.SendMessageLazy(true, msg)
3✔
5339
}
5340

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

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

5358
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5359
                if err != nil {
3✔
5360
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5361
                }
×
5362

5363
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5364
                        wallet, netParams, addr,
3✔
5365
                )
3✔
5366
                if err != nil {
3✔
5367
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5368
                }
×
5369

5370
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5371
                        DeliveryAddress: addr,
3✔
5372
                        InternalKey:     internalKeyDesc,
3✔
5373
                })
3✔
5374
        }
5375
}
5376

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

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

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

5410
        for _, c := range pendings {
6✔
5411
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5412
                        continue
3✔
5413
                }
5414

5415
                // If the channel is still reported as pending, remove it from
5416
                // the map.
5417
                delete(closedSCIDs, c.ShortChannelID)
×
5418

×
5419
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5420
                        c.ShortChannelID)
×
5421
        }
5422

5423
        return closedSCIDs
3✔
5424
}
5425

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

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

×
5438
                return &chainio.Beat{}, nil
×
5439
        }
×
5440

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

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

3✔
5457
                // Update the current blockbeat.
3✔
5458
                beat = chainio.NewBeat(*bestBlock)
3✔
5459

5460
        case <-s.quit:
×
5461
                srvrLog.Debug("LND shutting down")
×
5462
        }
5463

5464
        return beat, nil
3✔
5465
}
5466

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

3✔
5472
        pubBytes := peerPub.SerializeCompressed()
3✔
5473

3✔
5474
        s.mu.RLock()
3✔
5475
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5476
        s.mu.RUnlock()
3✔
5477
        if !ok {
3✔
5478
                return false
×
5479
        }
×
5480

5481
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5482
}
5483

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

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

5499
        // From the channel, we can now get the pubkey of the peer, then use
5500
        // that to eventually get the chan closer.
5501
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5502

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

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

5520
        return closeUpdates, nil
3✔
5521
}
5522

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

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

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

5549
        return updates, nil
3✔
5550
}
5551

5552
// calculateNodeAnnouncementTimestamp returns the timestamp to use for a node
5553
// announcement, ensuring it's at least one second after the previously
5554
// persisted timestamp. This ensures BOLT-07 compliance, which requires node
5555
// announcements to have strictly increasing timestamps.
5556
func calculateNodeAnnouncementTimestamp(persistedTime,
5557
        currentTime time.Time) time.Time {
12✔
5558

12✔
5559
        if persistedTime.Unix() >= currentTime.Unix() {
21✔
5560
                return persistedTime.Add(time.Second)
9✔
5561
        }
9✔
5562

5563
        return currentTime
6✔
5564
}
5565

5566
// setSelfNode configures and sets the server's self node. It sets the node
5567
// announcement, signs it, and updates the source node in the graph. When
5568
// determining values such as color and alias, the method prioritizes values
5569
// set in the config, then values previously persisted on disk, and finally
5570
// falls back to the defaults.
5571
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5572
        listenAddrs []net.Addr) error {
3✔
5573

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

×
5589
                        listenPorts = append(listenPorts, uint16(port))
×
5590
                }
×
5591

5592
                ips, err := s.configurePortForwarding(listenPorts...)
×
5593
                if err != nil {
×
5594
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5595
                                "forwarding using %s: %v",
×
5596
                                s.natTraversal.Name(), err)
×
5597
                } else {
×
5598
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5599
                                "using %s to advertise external IP",
×
5600
                                s.natTraversal.Name())
×
5601
                        externalIPStrings = append(externalIPStrings, ips...)
×
5602
                }
×
5603
        }
5604

5605
        // Normalize the external IP strings to net.Addr.
5606
        addrs, err := lncfg.NormalizeAddresses(
3✔
5607
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5608
                s.cfg.net.ResolveTCPAddr,
3✔
5609
        )
3✔
5610
        if err != nil {
3✔
5611
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5612
        }
×
5613

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

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

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

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

5646
                // If an alias is not specified in the config, we'll use the
5647
                // source node's alias.
5648
                if alias == "" {
6✔
5649
                        srcNode.Alias.WhenSome(func(s string) {
6✔
5650
                                alias = s
3✔
5651
                        })
3✔
5652
                }
5653

5654
                // If the `externalip` is not specified in the config, it means
5655
                // `addrs` will be empty, we'll use the source node's addresses.
5656
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5657
                        addrs = srcNode.Addresses
3✔
5658
                }
3✔
5659

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

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

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

5679
        // TODO(abdulkbk): potentially find a way to use the source node's
5680
        // features in the self node.
5681
        selfNode := models.NewV1Node(
3✔
5682
                nodePub, &models.NodeV1Fields{
3✔
5683
                        Alias:      nodeAlias.String(),
3✔
5684
                        Color:      nodeColor,
3✔
5685
                        LastUpdate: nodeLastUpdate,
3✔
5686
                        Addresses:  addrs,
3✔
5687
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
3✔
5688
                },
3✔
5689
        )
3✔
5690

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

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

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

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

5723
        s.currentNodeAnn = nodeAnn
3✔
5724

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

© 2026 Coveralls, Inc