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

lightningnetwork / lnd / 16466354971

23 Jul 2025 09:05AM UTC coverage: 57.54% (-9.7%) from 67.201%
16466354971

Pull #9455

github

web-flow
Merge f914ae23c into 90e211684
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

151 of 291 new or added lines in 7 files covered. (51.89%)

28441 existing lines in 456 files now uncovered.

98864 of 171817 relevant lines covered (57.54%)

1.79 hits per line

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

69.6
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

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

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

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

418
        customMessageServer *subscribe.Server
419

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

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

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

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

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

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

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

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

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

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

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

490
                                        s.mu.Lock()
3✔
491

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

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

506
                                        s.mu.Unlock()
3✔
507

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

514
        return nil
3✔
515
}
516

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

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

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

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

550
        // Handle the Onion address type.
551
        if tor.IsOnionHost(host) {
3✔
552
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
553
        }
×
554

555
        // For loopback or IP addresses: Use ResolveTCPAddr to properly
556
        // resolve these through Tor or other proxies, preventing IP leakage.
557
        if lncfg.IsLoopback(host) || isIP(host) || lnwire.IsIPv4Like(host) {
6✔
558
                hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
559
                return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
560
        }
3✔
561

562
        // Attempt to parse as a DNS address. The validation performed by
563
        // NewDNSAddr ensures compliance with BOLT-07 specifications.
564
        addr, err := lnwire.NewDNSAddr(host, port)
3✔
565
        if err != nil {
3✔
NEW
566
                return nil, err
×
NEW
567
        }
×
568

569
        return addr, nil
3✔
570
}
571

572
// parseDNSAddr parses a raw DNS address and returns a properly
573
// formatted lnwire.DNSHostnameAddress or an error.
574
func parseDNSAddr(rawAddress string,
575
        netCfg tor.Net) (*lnwire.DNSAddr, error) {
3✔
576

3✔
577
        addr, err := parseAddr(rawAddress, netCfg)
3✔
578
        if err != nil {
3✔
NEW
579
                return nil, err
×
NEW
580
        }
×
581

582
        // Check if the parsed address is a DNS address.
583
        dnsAddr, ok := addr.(*lnwire.DNSAddr)
3✔
584
        if !ok {
3✔
NEW
585
                return nil, fmt.Errorf("expected DNS hostname address, "+
×
NEW
586
                        "got %T", addr)
×
NEW
587
        }
×
588

589
        return dnsAddr, nil
3✔
590
}
591

592
// isIP checks if the provided host is an IP address (IPv4 or IPv6).
593
func isIP(host string) bool {
3✔
594
        // Try parsing the host as an IP address.
3✔
595
        ip := net.ParseIP(host)
3✔
596
        return ip != nil
3✔
597
}
3✔
598

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

3✔
604
        return func(a net.Addr) (net.Conn, error) {
6✔
605
                lnAddr := a.(*lnwire.NetAddress)
3✔
606
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
607
        }
3✔
608
}
609

610
// newServer creates a new instance of the server which is to listen using the
611
// passed listener address.
612
//
613
//nolint:funlen
614
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
615
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
616
        nodeKeyDesc *keychain.KeyDescriptor,
617
        chansToRestore walletunlocker.ChannelsToRecover,
618
        chanPredicate chanacceptor.ChannelAcceptor,
619
        torController *tor.Controller, tlsManager *TLSManager,
620
        leaderElector cluster.LeaderElector,
621
        implCfg *ImplementationCfg) (*server, error) {
3✔
622

3✔
623
        var (
3✔
624
                err         error
3✔
625
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
626

3✔
627
                // We just derived the full descriptor, so we know the public
3✔
628
                // key is set on it.
3✔
629
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
630
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
631
                )
3✔
632
        )
3✔
633

3✔
634
        var serializedPubKey [33]byte
3✔
635
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
636

3✔
637
        netParams := cfg.ActiveNetParams.Params
3✔
638

3✔
639
        // Initialize the sphinx router.
3✔
640
        replayLog := htlcswitch.NewDecayedLog(
3✔
641
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
642
        )
3✔
643
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
644

3✔
645
        writeBufferPool := pool.NewWriteBuffer(
3✔
646
                pool.DefaultWriteBufferGCInterval,
3✔
647
                pool.DefaultWriteBufferExpiryInterval,
3✔
648
        )
3✔
649

3✔
650
        writePool := pool.NewWrite(
3✔
651
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
652
        )
3✔
653

3✔
654
        readBufferPool := pool.NewReadBuffer(
3✔
655
                pool.DefaultReadBufferGCInterval,
3✔
656
                pool.DefaultReadBufferExpiryInterval,
3✔
657
        )
3✔
658

3✔
659
        readPool := pool.NewRead(
3✔
660
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
661
        )
3✔
662

3✔
663
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
664
        // controller, then we'll exit as this is incompatible.
3✔
665
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
666
                implCfg.AuxFundingController.IsNone() {
3✔
667

×
668
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
669
                        "aux controllers")
×
670
        }
×
671

672
        //nolint:ll
673
        featureMgr, err := feature.NewManager(feature.Config{
3✔
674
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
675
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
676
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
677
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
678
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
679
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
680
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
681
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
682
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
683
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
684
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
685
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
686
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
687
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
688
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
689
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
690
        })
3✔
691
        if err != nil {
3✔
692
                return nil, err
×
693
        }
×
694

695
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
696
        registryConfig := invoices.RegistryConfig{
3✔
697
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
698
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
699
                Clock:                       clock.NewDefaultClock(),
3✔
700
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
701
                AcceptAMP:                   cfg.AcceptAMP,
3✔
702
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
703
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
704
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
705
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
706
        }
3✔
707

3✔
708
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
709

3✔
710
        s := &server{
3✔
711
                cfg:            cfg,
3✔
712
                implCfg:        implCfg,
3✔
713
                graphDB:        dbs.GraphDB,
3✔
714
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
715
                addrSource:     addrSource,
3✔
716
                miscDB:         dbs.ChanStateDB,
3✔
717
                invoicesDB:     dbs.InvoiceDB,
3✔
718
                cc:             cc,
3✔
719
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
720
                writePool:      writePool,
3✔
721
                readPool:       readPool,
3✔
722
                chansToRestore: chansToRestore,
3✔
723

3✔
724
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
725
                        cc.ChainNotifier,
3✔
726
                ),
3✔
727
                channelNotifier: channelnotifier.New(
3✔
728
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
729
                ),
3✔
730

3✔
731
                identityECDH:   nodeKeyECDH,
3✔
732
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
733
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
734

3✔
735
                listenAddrs: listenAddrs,
3✔
736

3✔
737
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
738
                // schedule
3✔
739
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
740

3✔
741
                torController: torController,
3✔
742

3✔
743
                persistentPeers:         make(map[string]bool),
3✔
744
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
745
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
746
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
747
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
748
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
749
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
750
                scheduledPeerConnection: make(map[string]func()),
3✔
751
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
752

3✔
753
                peersByPub:                make(map[string]*peer.Brontide),
3✔
754
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
755
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
756
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
757
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
758

3✔
759
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
760

3✔
761
                customMessageServer: subscribe.NewServer(),
3✔
762

3✔
763
                tlsManager: tlsManager,
3✔
764

3✔
765
                featureMgr: featureMgr,
3✔
766
                quit:       make(chan struct{}),
3✔
767
        }
3✔
768

3✔
769
        // Start the low-level services once they are initialized.
3✔
770
        //
3✔
771
        // TODO(yy): break the server startup into four steps,
3✔
772
        // 1. init the low-level services.
3✔
773
        // 2. start the low-level services.
3✔
774
        // 3. init the high-level services.
3✔
775
        // 4. start the high-level services.
3✔
776
        if err := s.startLowLevelServices(); err != nil {
3✔
777
                return nil, err
×
778
        }
×
779

780
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
781
        if err != nil {
3✔
782
                return nil, err
×
783
        }
×
784

785
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
786
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
787
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
788
        )
3✔
789
        s.invoices = invoices.NewRegistry(
3✔
790
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
791
        )
3✔
792

3✔
793
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
794

3✔
795
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
796
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
797

3✔
798
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
799
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
800
                if err != nil {
3✔
801
                        return err
×
802
                }
×
803

804
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
805

3✔
806
                return nil
3✔
807
        }
808

809
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
810
        if err != nil {
3✔
811
                return nil, err
×
812
        }
×
813

814
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
815
                DB:                   dbs.ChanStateDB,
3✔
816
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
817
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
818
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
819
                LocalChannelClose: func(pubKey []byte,
3✔
820
                        request *htlcswitch.ChanClose) {
6✔
821

3✔
822
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
823
                        if err != nil {
3✔
824
                                srvrLog.Errorf("unable to close channel, peer"+
×
825
                                        " with %v id can't be found: %v",
×
826
                                        pubKey, err,
×
827
                                )
×
828
                                return
×
829
                        }
×
830

831
                        peer.HandleLocalCloseChanReqs(request)
3✔
832
                },
833
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
834
                SwitchPackager:         channeldb.NewSwitchPackager(),
835
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
836
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
837
                Notifier:               s.cc.ChainNotifier,
838
                HtlcNotifier:           s.htlcNotifier,
839
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
840
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
841
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
842
                AllowCircularRoute:     cfg.AllowCircularRoute,
843
                RejectHTLC:             cfg.RejectHTLC,
844
                Clock:                  clock.NewDefaultClock(),
845
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
846
                MaxFeeExposure:         thresholdMSats,
847
                SignAliasUpdate:        s.signAliasUpdate,
848
                IsAlias:                aliasmgr.IsAlias,
849
        }, uint32(currentHeight))
850
        if err != nil {
3✔
851
                return nil, err
×
852
        }
×
853
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
854
                &htlcswitch.InterceptableSwitchConfig{
3✔
855
                        Switch:             s.htlcSwitch,
3✔
856
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
857
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
858
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
859
                        Notifier:           s.cc.ChainNotifier,
3✔
860
                },
3✔
861
        )
3✔
862
        if err != nil {
3✔
863
                return nil, err
×
864
        }
×
865

866
        s.witnessBeacon = newPreimageBeacon(
3✔
867
                dbs.ChanStateDB.NewWitnessCache(),
3✔
868
                s.interceptableSwitch.ForwardPacket,
3✔
869
        )
3✔
870

3✔
871
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
872
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
873
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
874
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
875
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
876
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
877
                MessageSigner:            s.nodeSigner,
3✔
878
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
879
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
880
                DB:                       s.chanStateDB,
3✔
881
                Graph:                    dbs.GraphDB,
3✔
882
        }
3✔
883

3✔
884
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
885
        if err != nil {
3✔
886
                return nil, err
×
887
        }
×
888
        s.chanStatusMgr = chanStatusMgr
3✔
889

3✔
890
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
891
        // port forwarding for users behind a NAT.
3✔
892
        if cfg.NAT {
3✔
893
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
894

×
895
                discoveryTimeout := time.Duration(10 * time.Second)
×
896

×
897
                ctx, cancel := context.WithTimeout(
×
898
                        context.Background(), discoveryTimeout,
×
899
                )
×
900
                defer cancel()
×
901
                upnp, err := nat.DiscoverUPnP(ctx)
×
902
                if err == nil {
×
903
                        s.natTraversal = upnp
×
904
                } else {
×
905
                        // If we were not able to discover a UPnP enabled device
×
906
                        // on the local network, we'll fall back to attempting
×
907
                        // to discover a NAT-PMP enabled device.
×
908
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
909
                                "device on the local network: %v", err)
×
910

×
911
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
912
                                "enabled device")
×
913

×
914
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
915
                        if err != nil {
×
916
                                err := fmt.Errorf("unable to discover a "+
×
917
                                        "NAT-PMP enabled device on the local "+
×
918
                                        "network: %v", err)
×
919
                                srvrLog.Error(err)
×
920
                                return nil, err
×
921
                        }
×
922

923
                        s.natTraversal = pmp
×
924
                }
925
        }
926

927
        // If we were requested to automatically configure port forwarding,
928
        // we'll use the ports that the server will be listening on.
929
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
930
        for idx, ip := range cfg.ExternalIPs {
6✔
931
                externalIPStrings[idx] = ip.String()
3✔
932
        }
3✔
933
        if s.natTraversal != nil {
3✔
934
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
935
                for _, listenAddr := range listenAddrs {
×
936
                        // At this point, the listen addresses should have
×
937
                        // already been normalized, so it's safe to ignore the
×
938
                        // errors.
×
939
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
940
                        port, _ := strconv.Atoi(portStr)
×
941

×
942
                        listenPorts = append(listenPorts, uint16(port))
×
943
                }
×
944

945
                ips, err := s.configurePortForwarding(listenPorts...)
×
946
                if err != nil {
×
947
                        srvrLog.Errorf("Unable to automatically set up port "+
×
948
                                "forwarding using %s: %v",
×
949
                                s.natTraversal.Name(), err)
×
950
                } else {
×
951
                        srvrLog.Infof("Automatically set up port forwarding "+
×
952
                                "using %s to advertise external IP",
×
953
                                s.natTraversal.Name())
×
954
                        externalIPStrings = append(externalIPStrings, ips...)
×
955
                }
×
956
        }
957

958
        // If external IP addresses have been specified, add those to the list
959
        // of this server's addresses.
960
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
961
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
962
                cfg.net.ResolveTCPAddr,
3✔
963
        )
3✔
964
        if err != nil {
3✔
965
                return nil, err
×
966
        }
×
967

968
        addrsLen := len(externalIPs)
3✔
969
        if cfg.ExternalDNSAddress != nil {
6✔
970
                addrsLen++
3✔
971
        }
3✔
972

973
        selfAddrs := make([]net.Addr, 0, addrsLen)
3✔
974
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
975

3✔
976
        if cfg.ExternalDNSAddress != nil {
6✔
977
                selfAddrs = append(selfAddrs, cfg.ExternalDNSAddress)
3✔
978
        }
3✔
979

980
        // We'll now reconstruct a node announcement based on our current
981
        // configuration so we can send it out as a sort of heart beat within
982
        // the network.
983
        //
984
        // We'll start by parsing the node color from configuration.
985
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
986
        if err != nil {
3✔
987
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
988
                return nil, err
×
989
        }
×
990

991
        // If no alias is provided, default to first 10 characters of public
992
        // key.
993
        alias := cfg.Alias
3✔
994
        if alias == "" {
6✔
995
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
996
        }
3✔
997
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
998
        if err != nil {
3✔
999
                return nil, err
×
1000
        }
×
1001

1002
        // TODO(elle): All previously persisted node announcement fields (ie,
1003
        //  not just LastUpdate) should be consulted here to ensure that we
1004
        //  aren't overwriting any fields that may have been set during the
1005
        //  last run of lnd.
1006
        nodeLastUpdate := time.Now()
3✔
1007
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1008
        switch {
3✔
1009
        // If we have a source node persisted in the DB already, then we just
1010
        // need to make sure that the new LastUpdate time is at least one
1011
        // second after the last update time.
1012
        case err == nil:
3✔
1013
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
1014
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
1015
                }
3✔
1016

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

1021
        // If the above cases are not matched, then we have an unhandled non
1022
        // nil error.
1023
        default:
×
1024
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
1025
        }
1026

1027
        selfNode := &models.LightningNode{
3✔
1028
                HaveNodeAnnouncement: true,
3✔
1029
                LastUpdate:           nodeLastUpdate,
3✔
1030
                Addresses:            selfAddrs,
3✔
1031
                Alias:                nodeAlias.String(),
3✔
1032
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
1033
                Color:                color,
3✔
1034
        }
3✔
1035
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1036

3✔
1037
        // Based on the disk representation of the node announcement generated
3✔
1038
        // above, we'll generate a node announcement that can go out on the
3✔
1039
        // network so we can properly sign it.
3✔
1040
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
1041
        if err != nil {
3✔
1042
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
1043
        }
×
1044

1045
        // With the announcement generated, we'll sign it to properly
1046
        // authenticate the message on the network.
1047
        authSig, err := netann.SignAnnouncement(
3✔
1048
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
1049
        )
3✔
1050
        if err != nil {
3✔
1051
                return nil, fmt.Errorf("unable to generate signature for "+
×
1052
                        "self node announcement: %v", err)
×
1053
        }
×
1054
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
1055
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
1056
                selfNode.AuthSigBytes,
3✔
1057
        )
3✔
1058
        if err != nil {
3✔
1059
                return nil, err
×
1060
        }
×
1061

1062
        // Finally, we'll update the representation on disk, and update our
1063
        // cached in-memory version as well.
1064
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
1065
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1066
        }
×
1067
        s.currentNodeAnn = nodeAnn
3✔
1068

3✔
1069
        // The router will get access to the payment ID sequencer, such that it
3✔
1070
        // can generate unique payment IDs.
3✔
1071
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1072
        if err != nil {
3✔
1073
                return nil, err
×
1074
        }
×
1075

1076
        // Instantiate mission control with config from the sub server.
1077
        //
1078
        // TODO(joostjager): When we are further in the process of moving to sub
1079
        // servers, the mission control instance itself can be moved there too.
1080
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1081

3✔
1082
        // We only initialize a probability estimator if there's no custom one.
3✔
1083
        var estimator routing.Estimator
3✔
1084
        if cfg.Estimator != nil {
3✔
1085
                estimator = cfg.Estimator
×
1086
        } else {
3✔
1087
                switch routingConfig.ProbabilityEstimatorType {
3✔
1088
                case routing.AprioriEstimatorName:
3✔
1089
                        aCfg := routingConfig.AprioriConfig
3✔
1090
                        aprioriConfig := routing.AprioriConfig{
3✔
1091
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1092
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1093
                                AprioriWeight:         aCfg.Weight,
3✔
1094
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1095
                        }
3✔
1096

3✔
1097
                        estimator, err = routing.NewAprioriEstimator(
3✔
1098
                                aprioriConfig,
3✔
1099
                        )
3✔
1100
                        if err != nil {
3✔
1101
                                return nil, err
×
1102
                        }
×
1103

1104
                case routing.BimodalEstimatorName:
×
1105
                        bCfg := routingConfig.BimodalConfig
×
1106
                        bimodalConfig := routing.BimodalConfig{
×
1107
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1108
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1109
                                        bCfg.Scale,
×
1110
                                ),
×
1111
                                BimodalDecayTime: bCfg.DecayTime,
×
1112
                        }
×
1113

×
1114
                        estimator, err = routing.NewBimodalEstimator(
×
1115
                                bimodalConfig,
×
1116
                        )
×
1117
                        if err != nil {
×
1118
                                return nil, err
×
1119
                        }
×
1120

1121
                default:
×
1122
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1123
                                routingConfig.ProbabilityEstimatorType)
×
1124
                }
1125
        }
1126

1127
        mcCfg := &routing.MissionControlConfig{
3✔
1128
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1129
                Estimator:               estimator,
3✔
1130
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1131
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1132
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1133
        }
3✔
1134

3✔
1135
        s.missionController, err = routing.NewMissionController(
3✔
1136
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1137
        )
3✔
1138
        if err != nil {
3✔
1139
                return nil, fmt.Errorf("can't create mission control "+
×
1140
                        "manager: %w", err)
×
1141
        }
×
1142
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1143
                routing.DefaultMissionControlNamespace,
3✔
1144
        )
3✔
1145
        if err != nil {
3✔
1146
                return nil, fmt.Errorf("can't create mission control in the "+
×
1147
                        "default namespace: %w", err)
×
1148
        }
×
1149

1150
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1151
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1152
                int64(routingConfig.AttemptCost),
3✔
1153
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1154
                routingConfig.MinRouteProbability)
3✔
1155

3✔
1156
        pathFindingConfig := routing.PathFindingConfig{
3✔
1157
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1158
                        routingConfig.AttemptCost,
3✔
1159
                ),
3✔
1160
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1161
                MinProbability: routingConfig.MinRouteProbability,
3✔
1162
        }
3✔
1163

3✔
1164
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1165
        if err != nil {
3✔
1166
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1167
        }
×
1168
        paymentSessionSource := &routing.SessionSource{
3✔
1169
                GraphSessionFactory: dbs.GraphDB,
3✔
1170
                SourceNode:          sourceNode,
3✔
1171
                MissionControl:      s.defaultMC,
3✔
1172
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1173
                PathFindingConfig:   pathFindingConfig,
3✔
1174
        }
3✔
1175

3✔
1176
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1177

3✔
1178
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1179

3✔
1180
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1181
                cfg.Routing.StrictZombiePruning
3✔
1182

3✔
1183
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1184
                SelfNode:            selfNode.PubKeyBytes,
3✔
1185
                Graph:               dbs.GraphDB,
3✔
1186
                Chain:               cc.ChainIO,
3✔
1187
                ChainView:           cc.ChainView,
3✔
1188
                Notifier:            cc.ChainNotifier,
3✔
1189
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1190
                GraphPruneInterval:  time.Hour,
3✔
1191
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1192
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1193
                StrictZombiePruning: strictPruning,
3✔
1194
                IsAlias:             aliasmgr.IsAlias,
3✔
1195
        })
3✔
1196
        if err != nil {
3✔
1197
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1198
        }
×
1199

1200
        s.chanRouter, err = routing.New(routing.Config{
3✔
1201
                SelfNode:           selfNode.PubKeyBytes,
3✔
1202
                RoutingGraph:       dbs.GraphDB,
3✔
1203
                Chain:              cc.ChainIO,
3✔
1204
                Payer:              s.htlcSwitch,
3✔
1205
                Control:            s.controlTower,
3✔
1206
                MissionControl:     s.defaultMC,
3✔
1207
                SessionSource:      paymentSessionSource,
3✔
1208
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1209
                NextPaymentID:      sequencer.NextID,
3✔
1210
                PathFindingConfig:  pathFindingConfig,
3✔
1211
                Clock:              clock.NewDefaultClock(),
3✔
1212
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1213
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1214
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1215
        })
3✔
1216
        if err != nil {
3✔
1217
                return nil, fmt.Errorf("can't create router: %w", err)
×
1218
        }
×
1219

1220
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1221
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1222
        if err != nil {
3✔
1223
                return nil, err
×
1224
        }
×
1225
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1226
        if err != nil {
3✔
1227
                return nil, err
×
1228
        }
×
1229

1230
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1231

3✔
1232
        s.authGossiper = discovery.New(discovery.Config{
3✔
1233
                Graph:                 s.graphBuilder,
3✔
1234
                ChainIO:               s.cc.ChainIO,
3✔
1235
                Notifier:              s.cc.ChainNotifier,
3✔
1236
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1237
                Broadcast:             s.BroadcastMessage,
3✔
1238
                ChanSeries:            chanSeries,
3✔
1239
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1240
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1241
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1242
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1243
                        error) {
3✔
1244

×
1245
                        return s.genNodeAnnouncement(nil)
×
1246
                },
×
1247
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1248
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1249
                RetransmitTicker:        ticker.New(time.Minute * 30),
1250
                RebroadcastInterval:     time.Hour * 24,
1251
                WaitingProofStore:       waitingProofStore,
1252
                MessageStore:            gossipMessageStore,
1253
                AnnSigner:               s.nodeSigner,
1254
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1255
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1256
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1257
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1258
                MinimumBatchSize:        10,
1259
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1260
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1261
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1262
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1263
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1264
                IsAlias:                 aliasmgr.IsAlias,
1265
                SignAliasUpdate:         s.signAliasUpdate,
1266
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1267
                GetAlias:                s.aliasMgr.GetPeerAlias,
1268
                FindChannel:             s.findChannel,
1269
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1270
                ScidCloser:              scidCloserMan,
1271
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1272
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1273
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1274
        }, nodeKeyDesc)
1275

1276
        accessCfg := &accessManConfig{
3✔
1277
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1278
                        error) {
6✔
1279

3✔
1280
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1281
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1282
                                genesisHash[:],
3✔
1283
                        )
3✔
1284
                },
3✔
1285
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1286
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1287
        }
1288

1289
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1290
        if err != nil {
3✔
1291
                return nil, err
×
1292
        }
×
1293

1294
        s.peerAccessMan = peerAccessMan
3✔
1295

3✔
1296
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1297
        //nolint:ll
3✔
1298
        s.localChanMgr = &localchans.Manager{
3✔
1299
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1300
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1301
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1302
                        cb func(*models.ChannelEdgeInfo,
3✔
1303
                                *models.ChannelEdgePolicy) error,
3✔
1304
                        reset func()) error {
6✔
1305

3✔
1306
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1307
                                func(c *models.ChannelEdgeInfo,
3✔
1308
                                        e *models.ChannelEdgePolicy,
3✔
1309
                                        _ *models.ChannelEdgePolicy) error {
6✔
1310

3✔
1311
                                        // NOTE: The invoked callback here may
3✔
1312
                                        // receive a nil channel policy.
3✔
1313
                                        return cb(c, e)
3✔
1314
                                }, reset,
3✔
1315
                        )
1316
                },
1317
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1318
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1319
                FetchChannel:              s.chanStateDB.FetchChannel,
1320
                AddEdge: func(ctx context.Context,
1321
                        edge *models.ChannelEdgeInfo) error {
×
1322

×
1323
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1324
                },
×
1325
        }
1326

1327
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1328
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1329
        )
3✔
1330
        if err != nil {
3✔
1331
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1332
                return nil, err
×
1333
        }
×
1334

1335
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1336
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1337
        )
3✔
1338
        if err != nil {
3✔
1339
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1340
                return nil, err
×
1341
        }
×
1342

1343
        aggregator := sweep.NewBudgetAggregator(
3✔
1344
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1345
                s.implCfg.AuxSweeper,
3✔
1346
        )
3✔
1347

3✔
1348
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1349
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1350
                Wallet:     cc.Wallet,
3✔
1351
                Estimator:  cc.FeeEstimator,
3✔
1352
                Notifier:   cc.ChainNotifier,
3✔
1353
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1354
        })
3✔
1355

3✔
1356
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1357
                FeeEstimator: cc.FeeEstimator,
3✔
1358
                GenSweepScript: newSweepPkScriptGen(
3✔
1359
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1360
                ),
3✔
1361
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1362
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1363
                Mempool:              cc.MempoolNotifier,
3✔
1364
                Notifier:             cc.ChainNotifier,
3✔
1365
                Store:                sweeperStore,
3✔
1366
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1367
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1368
                Aggregator:           aggregator,
3✔
1369
                Publisher:            s.txPublisher,
3✔
1370
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1371
        })
3✔
1372

3✔
1373
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1374
                ChainIO:             cc.ChainIO,
3✔
1375
                ConfDepth:           1,
3✔
1376
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1377
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1378
                Notifier:            cc.ChainNotifier,
3✔
1379
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1380
                Store:               utxnStore,
3✔
1381
                SweepInput:          s.sweeper.SweepInput,
3✔
1382
                Budget:              s.cfg.Sweeper.Budget,
3✔
1383
        })
3✔
1384

3✔
1385
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1386
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1387
                closureType contractcourt.ChannelCloseType) {
6✔
1388
                // TODO(conner): Properly respect the update and error channels
3✔
1389
                // returned by CloseLink.
3✔
1390

3✔
1391
                // Instruct the switch to close the channel.  Provide no close out
3✔
1392
                // delivery script or target fee per kw because user input is not
3✔
1393
                // available when the remote peer closes the channel.
3✔
1394
                s.htlcSwitch.CloseLink(
3✔
1395
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1396
                )
3✔
1397
        }
3✔
1398

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

3✔
1403
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1404
                &contractcourt.BreachConfig{
3✔
1405
                        CloseLink: closeLink,
3✔
1406
                        DB:        s.chanStateDB,
3✔
1407
                        Estimator: s.cc.FeeEstimator,
3✔
1408
                        GenSweepScript: newSweepPkScriptGen(
3✔
1409
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1410
                        ),
3✔
1411
                        Notifier:           cc.ChainNotifier,
3✔
1412
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1413
                        ContractBreaches:   contractBreaches,
3✔
1414
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1415
                        Store: contractcourt.NewRetributionStore(
3✔
1416
                                dbs.ChanStateDB,
3✔
1417
                        ),
3✔
1418
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1419
                },
3✔
1420
        )
3✔
1421

3✔
1422
        //nolint:ll
3✔
1423
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1424
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1425
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1426
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1427
                NewSweepAddr: func() ([]byte, error) {
3✔
1428
                        addr, err := newSweepPkScriptGen(
×
1429
                                cc.Wallet, netParams,
×
1430
                        )().Unpack()
×
1431
                        if err != nil {
×
1432
                                return nil, err
×
1433
                        }
×
1434

1435
                        return addr.DeliveryAddress, nil
×
1436
                },
1437
                PublishTx: cc.Wallet.PublishTransaction,
1438
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1439
                        for _, msg := range msgs {
6✔
1440
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1441
                                if err != nil {
3✔
1442
                                        return err
×
1443
                                }
×
1444
                        }
1445
                        return nil
3✔
1446
                },
1447
                IncubateOutputs: func(chanPoint wire.OutPoint,
1448
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1449
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1450
                        broadcastHeight uint32,
1451
                        deadlineHeight fn.Option[int32]) error {
3✔
1452

3✔
1453
                        return s.utxoNursery.IncubateOutputs(
3✔
1454
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1455
                                broadcastHeight, deadlineHeight,
3✔
1456
                        )
3✔
1457
                },
3✔
1458
                PreimageDB:   s.witnessBeacon,
1459
                Notifier:     cc.ChainNotifier,
1460
                Mempool:      cc.MempoolNotifier,
1461
                Signer:       cc.Wallet.Cfg.Signer,
1462
                FeeEstimator: cc.FeeEstimator,
1463
                ChainIO:      cc.ChainIO,
1464
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1465
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1466
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1467
                        return nil
3✔
1468
                },
3✔
1469
                IsOurAddress: cc.Wallet.IsOurAddress,
1470
                ContractBreach: func(chanPoint wire.OutPoint,
1471
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1472

3✔
1473
                        // processACK will handle the BreachArbitrator ACKing
3✔
1474
                        // the event.
3✔
1475
                        finalErr := make(chan error, 1)
3✔
1476
                        processACK := func(brarErr error) {
6✔
1477
                                if brarErr != nil {
3✔
1478
                                        finalErr <- brarErr
×
1479
                                        return
×
1480
                                }
×
1481

1482
                                // If the BreachArbitrator successfully handled
1483
                                // the event, we can signal that the handoff
1484
                                // was successful.
1485
                                finalErr <- nil
3✔
1486
                        }
1487

1488
                        event := &contractcourt.ContractBreachEvent{
3✔
1489
                                ChanPoint:         chanPoint,
3✔
1490
                                ProcessACK:        processACK,
3✔
1491
                                BreachRetribution: breachRet,
3✔
1492
                        }
3✔
1493

3✔
1494
                        // Send the contract breach event to the
3✔
1495
                        // BreachArbitrator.
3✔
1496
                        select {
3✔
1497
                        case contractBreaches <- event:
3✔
1498
                        case <-s.quit:
×
1499
                                return ErrServerShuttingDown
×
1500
                        }
1501

1502
                        // We'll wait for a final error to be available from
1503
                        // the BreachArbitrator.
1504
                        select {
3✔
1505
                        case err := <-finalErr:
3✔
1506
                                return err
3✔
1507
                        case <-s.quit:
×
1508
                                return ErrServerShuttingDown
×
1509
                        }
1510
                },
1511
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1512
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1513
                },
3✔
1514
                Sweeper:                       s.sweeper,
1515
                Registry:                      s.invoices,
1516
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1517
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1518
                OnionProcessor:                s.sphinx,
1519
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1520
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1521
                Clock:                         clock.NewDefaultClock(),
1522
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1523
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1524
                HtlcNotifier:                  s.htlcNotifier,
1525
                Budget:                        *s.cfg.Sweeper.Budget,
1526

1527
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1528
                QueryIncomingCircuit: func(
1529
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1530

3✔
1531
                        // Get the circuit map.
3✔
1532
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1533

3✔
1534
                        // Lookup the outgoing circuit.
3✔
1535
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1536
                        if pc == nil {
5✔
1537
                                return nil
2✔
1538
                        }
2✔
1539

1540
                        return &pc.Incoming
3✔
1541
                },
1542
                AuxLeafStore: implCfg.AuxLeafStore,
1543
                AuxSigner:    implCfg.AuxSigner,
1544
                AuxResolver:  implCfg.AuxContractResolver,
1545
        }, dbs.ChanStateDB)
1546

1547
        // Select the configuration and funding parameters for Bitcoin.
1548
        chainCfg := cfg.Bitcoin
3✔
1549
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1550
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1551

3✔
1552
        var chanIDSeed [32]byte
3✔
1553
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1554
                return nil, err
×
1555
        }
×
1556

1557
        // Wrap the DeleteChannelEdges method so that the funding manager can
1558
        // use it without depending on several layers of indirection.
1559
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1560
                *models.ChannelEdgePolicy, error) {
6✔
1561

3✔
1562
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1563
                        scid.ToUint64(),
3✔
1564
                )
3✔
1565
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1566
                        // This is unlikely but there is a slim chance of this
×
1567
                        // being hit if lnd was killed via SIGKILL and the
×
1568
                        // funding manager was stepping through the delete
×
1569
                        // alias edge logic.
×
1570
                        return nil, nil
×
1571
                } else if err != nil {
3✔
1572
                        return nil, err
×
1573
                }
×
1574

1575
                // Grab our key to find our policy.
1576
                var ourKey [33]byte
3✔
1577
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1578

3✔
1579
                var ourPolicy *models.ChannelEdgePolicy
3✔
1580
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1581
                        ourPolicy = e1
3✔
1582
                } else {
6✔
1583
                        ourPolicy = e2
3✔
1584
                }
3✔
1585

1586
                if ourPolicy == nil {
3✔
1587
                        // Something is wrong, so return an error.
×
1588
                        return nil, fmt.Errorf("we don't have an edge")
×
1589
                }
×
1590

1591
                err = s.graphDB.DeleteChannelEdges(
3✔
1592
                        false, false, scid.ToUint64(),
3✔
1593
                )
3✔
1594
                return ourPolicy, err
3✔
1595
        }
1596

1597
        // For the reservationTimeout and the zombieSweeperInterval different
1598
        // values are set in case we are in a dev environment so enhance test
1599
        // capacilities.
1600
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1601
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1602

3✔
1603
        // Get the development config for funding manager. If we are not in
3✔
1604
        // development mode, this would be nil.
3✔
1605
        var devCfg *funding.DevConfig
3✔
1606
        if lncfg.IsDevBuild() {
6✔
1607
                devCfg = &funding.DevConfig{
3✔
1608
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1609
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1610
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1611
                }
3✔
1612

3✔
1613
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1614
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1615

3✔
1616
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1617
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1618
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1619
        }
3✔
1620

1621
        //nolint:ll
1622
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1623
                Dev:                devCfg,
3✔
1624
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1625
                IDKey:              nodeKeyDesc.PubKey,
3✔
1626
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1627
                Wallet:             cc.Wallet,
3✔
1628
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1629
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1630
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1631
                },
3✔
1632
                Notifier:     cc.ChainNotifier,
1633
                ChannelDB:    s.chanStateDB,
1634
                FeeEstimator: cc.FeeEstimator,
1635
                SignMessage:  cc.MsgSigner.SignMessage,
1636
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1637
                        error) {
3✔
1638

3✔
1639
                        return s.genNodeAnnouncement(nil)
3✔
1640
                },
3✔
1641
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1642
                NotifyWhenOnline:     s.NotifyWhenOnline,
1643
                TempChanIDSeed:       chanIDSeed,
1644
                FindChannel:          s.findChannel,
1645
                DefaultRoutingPolicy: cc.RoutingPolicy,
1646
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1647
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1648
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1649
                        // For large channels we increase the number
3✔
1650
                        // of confirmations we require for the
3✔
1651
                        // channel to be considered open. As it is
3✔
1652
                        // always the responder that gets to choose
3✔
1653
                        // value, the pushAmt is value being pushed
3✔
1654
                        // to us. This means we have more to lose
3✔
1655
                        // in the case this gets re-orged out, and
3✔
1656
                        // we will require more confirmations before
3✔
1657
                        // we consider it open.
3✔
1658

3✔
1659
                        // In case the user has explicitly specified
3✔
1660
                        // a default value for the number of
3✔
1661
                        // confirmations, we use it.
3✔
1662
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1663
                        if defaultConf != 0 {
6✔
1664
                                return defaultConf
3✔
1665
                        }
3✔
1666

1667
                        minConf := uint64(3)
×
1668
                        maxConf := uint64(6)
×
1669

×
1670
                        // If this is a wumbo channel, then we'll require the
×
1671
                        // max amount of confirmations.
×
1672
                        if chanAmt > MaxFundingAmount {
×
1673
                                return uint16(maxConf)
×
1674
                        }
×
1675

1676
                        // If not we return a value scaled linearly
1677
                        // between 3 and 6, depending on channel size.
1678
                        // TODO(halseth): Use 1 as minimum?
1679
                        maxChannelSize := uint64(
×
1680
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1681
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1682
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1683
                        if conf < minConf {
×
1684
                                conf = minConf
×
1685
                        }
×
1686
                        if conf > maxConf {
×
1687
                                conf = maxConf
×
1688
                        }
×
1689
                        return uint16(conf)
×
1690
                },
1691
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1692
                        // We scale the remote CSV delay (the time the
3✔
1693
                        // remote have to claim funds in case of a unilateral
3✔
1694
                        // close) linearly from minRemoteDelay blocks
3✔
1695
                        // for small channels, to maxRemoteDelay blocks
3✔
1696
                        // for channels of size MaxFundingAmount.
3✔
1697

3✔
1698
                        // In case the user has explicitly specified
3✔
1699
                        // a default value for the remote delay, we
3✔
1700
                        // use it.
3✔
1701
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1702
                        if defaultDelay > 0 {
6✔
1703
                                return defaultDelay
3✔
1704
                        }
3✔
1705

1706
                        // If this is a wumbo channel, then we'll require the
1707
                        // max value.
1708
                        if chanAmt > MaxFundingAmount {
×
1709
                                return maxRemoteDelay
×
1710
                        }
×
1711

1712
                        // If not we scale according to channel size.
1713
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1714
                                chanAmt / MaxFundingAmount)
×
1715
                        if delay < minRemoteDelay {
×
1716
                                delay = minRemoteDelay
×
1717
                        }
×
1718
                        if delay > maxRemoteDelay {
×
1719
                                delay = maxRemoteDelay
×
1720
                        }
×
1721
                        return delay
×
1722
                },
1723
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1724
                        peerKey *btcec.PublicKey) error {
3✔
1725

3✔
1726
                        // First, we'll mark this new peer as a persistent peer
3✔
1727
                        // for re-connection purposes. If the peer is not yet
3✔
1728
                        // tracked or the user hasn't requested it to be perm,
3✔
1729
                        // we'll set false to prevent the server from continuing
3✔
1730
                        // to connect to this peer even if the number of
3✔
1731
                        // channels with this peer is zero.
3✔
1732
                        s.mu.Lock()
3✔
1733
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1734
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1735
                                s.persistentPeers[pubStr] = false
3✔
1736
                        }
3✔
1737
                        s.mu.Unlock()
3✔
1738

3✔
1739
                        // With that taken care of, we'll send this channel to
3✔
1740
                        // the chain arb so it can react to on-chain events.
3✔
1741
                        return s.chainArb.WatchNewChannel(channel)
3✔
1742
                },
1743
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1744
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1745
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1746
                },
3✔
1747
                RequiredRemoteChanReserve: func(chanAmt,
1748
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1749

3✔
1750
                        // By default, we'll require the remote peer to maintain
3✔
1751
                        // at least 1% of the total channel capacity at all
3✔
1752
                        // times. If this value ends up dipping below the dust
3✔
1753
                        // limit, then we'll use the dust limit itself as the
3✔
1754
                        // reserve as required by BOLT #2.
3✔
1755
                        reserve := chanAmt / 100
3✔
1756
                        if reserve < dustLimit {
6✔
1757
                                reserve = dustLimit
3✔
1758
                        }
3✔
1759

1760
                        return reserve
3✔
1761
                },
1762
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1763
                        // By default, we'll allow the remote peer to fully
3✔
1764
                        // utilize the full bandwidth of the channel, minus our
3✔
1765
                        // required reserve.
3✔
1766
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1767
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1768
                },
3✔
1769
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1770
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1771
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1772
                        }
3✔
1773

1774
                        // By default, we'll permit them to utilize the full
1775
                        // channel bandwidth.
1776
                        return uint16(input.MaxHTLCNumber / 2)
×
1777
                },
1778
                ZombieSweeperInterval:         zombieSweeperInterval,
1779
                ReservationTimeout:            reservationTimeout,
1780
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1781
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1782
                MaxPendingChannels:            cfg.MaxPendingChannels,
1783
                RejectPush:                    cfg.RejectPush,
1784
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1785
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1786
                OpenChannelPredicate:          chanPredicate,
1787
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1788
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1789
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1790
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1791
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1792
                DeleteAliasEdge:      deleteAliasEdge,
1793
                AliasManager:         s.aliasMgr,
1794
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1795
                AuxFundingController: implCfg.AuxFundingController,
1796
                AuxSigner:            implCfg.AuxSigner,
1797
                AuxResolver:          implCfg.AuxContractResolver,
1798
        })
1799
        if err != nil {
3✔
1800
                return nil, err
×
1801
        }
×
1802

1803
        // Next, we'll assemble the sub-system that will maintain an on-disk
1804
        // static backup of the latest channel state.
1805
        chanNotifier := &channelNotifier{
3✔
1806
                chanNotifier: s.channelNotifier,
3✔
1807
                addrs:        s.addrSource,
3✔
1808
        }
3✔
1809
        backupFile := chanbackup.NewMultiFile(
3✔
1810
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1811
        )
3✔
1812
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1813
                ctx, s.chanStateDB, s.addrSource,
3✔
1814
        )
3✔
1815
        if err != nil {
3✔
1816
                return nil, err
×
1817
        }
×
1818
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1819
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1820
        )
3✔
1821
        if err != nil {
3✔
1822
                return nil, err
×
1823
        }
×
1824

1825
        // Assemble a peer notifier which will provide clients with subscriptions
1826
        // to peer online and offline events.
1827
        s.peerNotifier = peernotifier.New()
3✔
1828

3✔
1829
        // Create a channel event store which monitors all open channels.
3✔
1830
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1831
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1832
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1833
                },
3✔
1834
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1835
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1836
                },
3✔
1837
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1838
                Clock:           clock.NewDefaultClock(),
1839
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1840
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1841
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1842
        })
1843

1844
        if cfg.WtClient.Active {
6✔
1845
                policy := wtpolicy.DefaultPolicy()
3✔
1846
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1847

3✔
1848
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1849
                // protocol operations on sat/kw.
3✔
1850
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1851
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1852
                )
3✔
1853

3✔
1854
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1855

3✔
1856
                if err := policy.Validate(); err != nil {
3✔
1857
                        return nil, err
×
1858
                }
×
1859

1860
                // authDial is the wrapper around the btrontide.Dial for the
1861
                // watchtower.
1862
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1863
                        netAddr *lnwire.NetAddress,
3✔
1864
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1865

3✔
1866
                        return brontide.Dial(
3✔
1867
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1868
                        )
3✔
1869
                }
3✔
1870

1871
                // buildBreachRetribution is a call-back that can be used to
1872
                // query the BreachRetribution info and channel type given a
1873
                // channel ID and commitment height.
1874
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1875
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1876
                        channeldb.ChannelType, error) {
6✔
1877

3✔
1878
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1879
                                nil, chanID,
3✔
1880
                        )
3✔
1881
                        if err != nil {
3✔
1882
                                return nil, 0, err
×
1883
                        }
×
1884

1885
                        br, err := lnwallet.NewBreachRetribution(
3✔
1886
                                channel, commitHeight, 0, nil,
3✔
1887
                                implCfg.AuxLeafStore,
3✔
1888
                                implCfg.AuxContractResolver,
3✔
1889
                        )
3✔
1890
                        if err != nil {
3✔
1891
                                return nil, 0, err
×
1892
                        }
×
1893

1894
                        return br, channel.ChanType, nil
3✔
1895
                }
1896

1897
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1898

3✔
1899
                // Copy the policy for legacy channels and set the blob flag
3✔
1900
                // signalling support for anchor channels.
3✔
1901
                anchorPolicy := policy
3✔
1902
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1903

3✔
1904
                // Copy the policy for legacy channels and set the blob flag
3✔
1905
                // signalling support for taproot channels.
3✔
1906
                taprootPolicy := policy
3✔
1907
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1908
                        blob.FlagTaprootChannel,
3✔
1909
                )
3✔
1910

3✔
1911
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1912
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1913
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1914
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1915
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1916
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1917
                                error) {
6✔
1918

3✔
1919
                                return s.channelNotifier.
3✔
1920
                                        SubscribeChannelEvents()
3✔
1921
                        },
3✔
1922
                        Signer: cc.Wallet.Cfg.Signer,
1923
                        NewAddress: func() ([]byte, error) {
3✔
1924
                                addr, err := newSweepPkScriptGen(
3✔
1925
                                        cc.Wallet, netParams,
3✔
1926
                                )().Unpack()
3✔
1927
                                if err != nil {
3✔
1928
                                        return nil, err
×
1929
                                }
×
1930

1931
                                return addr.DeliveryAddress, nil
3✔
1932
                        },
1933
                        SecretKeyRing:      s.cc.KeyRing,
1934
                        Dial:               cfg.net.Dial,
1935
                        AuthDial:           authDial,
1936
                        DB:                 dbs.TowerClientDB,
1937
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1938
                        MinBackoff:         10 * time.Second,
1939
                        MaxBackoff:         5 * time.Minute,
1940
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1941
                }, policy, anchorPolicy, taprootPolicy)
1942
                if err != nil {
3✔
1943
                        return nil, err
×
1944
                }
×
1945
        }
1946

1947
        if len(cfg.ExternalHosts) != 0 {
3✔
1948
                advertisedIPs := make(map[string]struct{})
×
1949
                for _, addr := range s.currentNodeAnn.Addresses {
×
1950
                        advertisedIPs[addr.String()] = struct{}{}
×
1951
                }
×
1952

1953
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1954
                        Hosts:         cfg.ExternalHosts,
×
1955
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1956
                        LookupHost: func(host string) (net.Addr, error) {
×
1957
                                return lncfg.ParseAddressString(
×
1958
                                        host, strconv.Itoa(defaultPeerPort),
×
1959
                                        cfg.net.ResolveTCPAddr,
×
1960
                                )
×
1961
                        },
×
1962
                        AdvertisedIPs: advertisedIPs,
1963
                        AnnounceNewIPs: netann.IPAnnouncer(
1964
                                func(modifier ...netann.NodeAnnModifier) (
1965
                                        lnwire.NodeAnnouncement, error) {
×
1966

×
1967
                                        return s.genNodeAnnouncement(
×
1968
                                                nil, modifier...,
×
1969
                                        )
×
1970
                                }),
×
1971
                })
1972
        }
1973

1974
        // Create liveness monitor.
1975
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1976

3✔
1977
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1978
        for i, listenAddr := range listenAddrs {
6✔
1979
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1980
                // doesn't need to call the general lndResolveTCP function
3✔
1981
                // since we are resolving a local address.
3✔
1982

3✔
1983
                // RESOLVE: We are actually partially accepting inbound
3✔
1984
                // connection requests when we call NewListener.
3✔
1985
                listeners[i], err = brontide.NewListener(
3✔
1986
                        nodeKeyECDH, listenAddr.String(),
3✔
1987
                        // TODO(yy): remove this check and unify the inbound
3✔
1988
                        // connection check inside `InboundPeerConnected`.
3✔
1989
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1990
                )
3✔
1991
                if err != nil {
3✔
1992
                        return nil, err
×
1993
                }
×
1994
        }
1995

1996
        // Create the connection manager which will be responsible for
1997
        // maintaining persistent outbound connections and also accepting new
1998
        // incoming connections
1999
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
2000
                Listeners:      listeners,
3✔
2001
                OnAccept:       s.InboundPeerConnected,
3✔
2002
                RetryDuration:  time.Second * 5,
3✔
2003
                TargetOutbound: 100,
3✔
2004
                Dial: noiseDial(
3✔
2005
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
2006
                ),
3✔
2007
                OnConnection: s.OutboundPeerConnected,
3✔
2008
        })
3✔
2009
        if err != nil {
3✔
2010
                return nil, err
×
2011
        }
×
2012
        s.connMgr = cmgr
3✔
2013

3✔
2014
        // Finally, register the subsystems in blockbeat.
3✔
2015
        s.registerBlockConsumers()
3✔
2016

3✔
2017
        return s, nil
3✔
2018
}
2019

2020
// UpdateRoutingConfig is a callback function to update the routing config
2021
// values in the main cfg.
2022
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
2023
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
2024

3✔
2025
        switch c := cfg.Estimator.Config().(type) {
3✔
2026
        case routing.AprioriConfig:
3✔
2027
                routerCfg.ProbabilityEstimatorType =
3✔
2028
                        routing.AprioriEstimatorName
3✔
2029

3✔
2030
                targetCfg := routerCfg.AprioriConfig
3✔
2031
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
2032
                targetCfg.Weight = c.AprioriWeight
3✔
2033
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
2034
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
2035

2036
        case routing.BimodalConfig:
3✔
2037
                routerCfg.ProbabilityEstimatorType =
3✔
2038
                        routing.BimodalEstimatorName
3✔
2039

3✔
2040
                targetCfg := routerCfg.BimodalConfig
3✔
2041
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
2042
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
2043
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
2044
        }
2045

2046
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2047
}
2048

2049
// registerBlockConsumers registers the subsystems that consume block events.
2050
// By calling `RegisterQueue`, a list of subsystems are registered in the
2051
// blockbeat for block notifications. When a new block arrives, the subsystems
2052
// in the same queue are notified sequentially, and different queues are
2053
// notified concurrently.
2054
//
2055
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2056
// a new `RegisterQueue` call.
2057
func (s *server) registerBlockConsumers() {
3✔
2058
        // In this queue, when a new block arrives, it will be received and
3✔
2059
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
2060
        consumers := []chainio.Consumer{
3✔
2061
                s.chainArb,
3✔
2062
                s.sweeper,
3✔
2063
                s.txPublisher,
3✔
2064
        }
3✔
2065
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
2066
}
3✔
2067

2068
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2069
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2070
// may differ from what is on disk.
2071
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2072
        error) {
3✔
2073

3✔
2074
        data, err := u.DataToSign()
3✔
2075
        if err != nil {
3✔
2076
                return nil, err
×
2077
        }
×
2078

2079
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2080
}
2081

2082
// createLivenessMonitor creates a set of health checks using our configured
2083
// values and uses these checks to create a liveness monitor. Available
2084
// health checks,
2085
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2086
//   - diskCheck
2087
//   - tlsHealthCheck
2088
//   - torController, only created when tor is enabled.
2089
//
2090
// If a health check has been disabled by setting attempts to 0, our monitor
2091
// will not run it.
2092
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2093
        leaderElector cluster.LeaderElector) {
3✔
2094

3✔
2095
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2096
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2097
                srvrLog.Info("Disabling chain backend checks for " +
×
2098
                        "nochainbackend mode")
×
2099

×
2100
                chainBackendAttempts = 0
×
2101
        }
×
2102

2103
        chainHealthCheck := healthcheck.NewObservation(
3✔
2104
                "chain backend",
3✔
2105
                cc.HealthCheck,
3✔
2106
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2107
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2108
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2109
                chainBackendAttempts,
3✔
2110
        )
3✔
2111

3✔
2112
        diskCheck := healthcheck.NewObservation(
3✔
2113
                "disk space",
3✔
2114
                func() error {
3✔
2115
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2116
                                cfg.LndDir,
×
2117
                        )
×
2118
                        if err != nil {
×
2119
                                return err
×
2120
                        }
×
2121

2122
                        // If we have more free space than we require,
2123
                        // we return a nil error.
2124
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2125
                                return nil
×
2126
                        }
×
2127

2128
                        return fmt.Errorf("require: %v free space, got: %v",
×
2129
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2130
                                free)
×
2131
                },
2132
                cfg.HealthChecks.DiskCheck.Interval,
2133
                cfg.HealthChecks.DiskCheck.Timeout,
2134
                cfg.HealthChecks.DiskCheck.Backoff,
2135
                cfg.HealthChecks.DiskCheck.Attempts,
2136
        )
2137

2138
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2139
                "tls",
3✔
2140
                func() error {
3✔
2141
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2142
                                s.cc.KeyRing,
×
2143
                        )
×
2144
                        if err != nil {
×
2145
                                return err
×
2146
                        }
×
2147
                        if expired {
×
2148
                                return fmt.Errorf("TLS certificate is "+
×
2149
                                        "expired as of %v", expTime)
×
2150
                        }
×
2151

2152
                        // If the certificate is not outdated, no error needs
2153
                        // to be returned
2154
                        return nil
×
2155
                },
2156
                cfg.HealthChecks.TLSCheck.Interval,
2157
                cfg.HealthChecks.TLSCheck.Timeout,
2158
                cfg.HealthChecks.TLSCheck.Backoff,
2159
                cfg.HealthChecks.TLSCheck.Attempts,
2160
        )
2161

2162
        checks := []*healthcheck.Observation{
3✔
2163
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2164
        }
3✔
2165

3✔
2166
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2167
        if s.torController != nil {
3✔
2168
                torConnectionCheck := healthcheck.NewObservation(
×
2169
                        "tor connection",
×
2170
                        func() error {
×
2171
                                return healthcheck.CheckTorServiceStatus(
×
2172
                                        s.torController,
×
2173
                                        func() error {
×
2174
                                                return s.createNewHiddenService(
×
2175
                                                        context.TODO(),
×
2176
                                                )
×
2177
                                        },
×
2178
                                )
2179
                        },
2180
                        cfg.HealthChecks.TorConnection.Interval,
2181
                        cfg.HealthChecks.TorConnection.Timeout,
2182
                        cfg.HealthChecks.TorConnection.Backoff,
2183
                        cfg.HealthChecks.TorConnection.Attempts,
2184
                )
2185
                checks = append(checks, torConnectionCheck)
×
2186
        }
2187

2188
        // If remote signing is enabled, add the healthcheck for the remote
2189
        // signing RPC interface.
2190
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2191
                // Because we have two cascading timeouts here, we need to add
3✔
2192
                // some slack to the "outer" one of them in case the "inner"
3✔
2193
                // returns exactly on time.
3✔
2194
                overhead := time.Millisecond * 10
3✔
2195

3✔
2196
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2197
                        "remote signer connection",
3✔
2198
                        rpcwallet.HealthCheck(
3✔
2199
                                s.cfg.RemoteSigner,
3✔
2200

3✔
2201
                                // For the health check we might to be even
3✔
2202
                                // stricter than the initial/normal connect, so
3✔
2203
                                // we use the health check timeout here.
3✔
2204
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2205
                        ),
3✔
2206
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2207
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2208
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2209
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2210
                )
3✔
2211
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2212
        }
3✔
2213

2214
        // If we have a leader elector, we add a health check to ensure we are
2215
        // still the leader. During normal operation, we should always be the
2216
        // leader, but there are circumstances where this may change, such as
2217
        // when we lose network connectivity for long enough expiring out lease.
2218
        if leaderElector != nil {
3✔
2219
                leaderCheck := healthcheck.NewObservation(
×
2220
                        "leader status",
×
2221
                        func() error {
×
2222
                                // Check if we are still the leader. Note that
×
2223
                                // we don't need to use a timeout context here
×
2224
                                // as the healthcheck observer will handle the
×
2225
                                // timeout case for us.
×
2226
                                timeoutCtx, cancel := context.WithTimeout(
×
2227
                                        context.Background(),
×
2228
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2229
                                )
×
2230
                                defer cancel()
×
2231

×
2232
                                leader, err := leaderElector.IsLeader(
×
2233
                                        timeoutCtx,
×
2234
                                )
×
2235
                                if err != nil {
×
2236
                                        return fmt.Errorf("unable to check if "+
×
2237
                                                "still leader: %v", err)
×
2238
                                }
×
2239

2240
                                if !leader {
×
2241
                                        srvrLog.Debug("Not the current leader")
×
2242
                                        return fmt.Errorf("not the current " +
×
2243
                                                "leader")
×
2244
                                }
×
2245

2246
                                return nil
×
2247
                        },
2248
                        cfg.HealthChecks.LeaderCheck.Interval,
2249
                        cfg.HealthChecks.LeaderCheck.Timeout,
2250
                        cfg.HealthChecks.LeaderCheck.Backoff,
2251
                        cfg.HealthChecks.LeaderCheck.Attempts,
2252
                )
2253

2254
                checks = append(checks, leaderCheck)
×
2255
        }
2256

2257
        // If we have not disabled all of our health checks, we create a
2258
        // liveness monitor with our configured checks.
2259
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2260
                &healthcheck.Config{
3✔
2261
                        Checks:   checks,
3✔
2262
                        Shutdown: srvrLog.Criticalf,
3✔
2263
                },
3✔
2264
        )
3✔
2265
}
2266

2267
// Started returns true if the server has been started, and false otherwise.
2268
// NOTE: This function is safe for concurrent access.
2269
func (s *server) Started() bool {
3✔
2270
        return atomic.LoadInt32(&s.active) != 0
3✔
2271
}
3✔
2272

2273
// cleaner is used to aggregate "cleanup" functions during an operation that
2274
// starts several subsystems. In case one of the subsystem fails to start
2275
// and a proper resource cleanup is required, the "run" method achieves this
2276
// by running all these added "cleanup" functions.
2277
type cleaner []func() error
2278

2279
// add is used to add a cleanup function to be called when
2280
// the run function is executed.
2281
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2282
        return append(c, cleanup)
3✔
2283
}
3✔
2284

2285
// run is used to run all the previousely added cleanup functions.
2286
func (c cleaner) run() {
×
2287
        for i := len(c) - 1; i >= 0; i-- {
×
2288
                if err := c[i](); err != nil {
×
2289
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2290
                }
×
2291
        }
2292
}
2293

2294
// startLowLevelServices starts the low-level services of the server. These
2295
// services must be started successfully before running the main server. The
2296
// services are,
2297
// 1. the chain notifier.
2298
//
2299
// TODO(yy): identify and add more low-level services here.
2300
func (s *server) startLowLevelServices() error {
3✔
2301
        var startErr error
3✔
2302

3✔
2303
        cleanup := cleaner{}
3✔
2304

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

2310
        if startErr != nil {
3✔
2311
                cleanup.run()
×
2312
        }
×
2313

2314
        return startErr
3✔
2315
}
2316

2317
// Start starts the main daemon server, all requested listeners, and any helper
2318
// goroutines.
2319
// NOTE: This function is safe for concurrent access.
2320
//
2321
//nolint:funlen
2322
func (s *server) Start(ctx context.Context) error {
3✔
2323
        // Get the current blockbeat.
3✔
2324
        beat, err := s.getStartingBeat()
3✔
2325
        if err != nil {
3✔
2326
                return err
×
2327
        }
×
2328

2329
        var startErr error
3✔
2330

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

3✔
2336
        s.start.Do(func() {
6✔
2337
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2338
                if err := s.customMessageServer.Start(); err != nil {
3✔
2339
                        startErr = err
×
2340
                        return
×
2341
                }
×
2342

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

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

2359
                // Start the notification server. This is used so channel
2360
                // management goroutines can be notified when a funding
2361
                // transaction reaches a sufficient number of confirmations, or
2362
                // when the input for the funding transaction is spent in an
2363
                // attempt at an uncooperative close by the counterparty.
2364
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2365
                if err := s.sigPool.Start(); err != nil {
3✔
2366
                        startErr = err
×
2367
                        return
×
2368
                }
×
2369

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

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

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

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

2394
                cleanup = cleanup.add(func() error {
3✔
2395
                        return s.peerNotifier.Stop()
×
2396
                })
×
2397
                if err := s.peerNotifier.Start(); err != nil {
3✔
2398
                        startErr = err
×
2399
                        return
×
2400
                }
×
2401

2402
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2403
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2404
                        startErr = err
×
2405
                        return
×
2406
                }
×
2407

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

2416
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2417
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

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

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

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

2440
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2441
                if err := s.fundingMgr.Start(); err != nil {
3✔
2442
                        startErr = err
×
2443
                        return
×
2444
                }
×
2445

2446
                // htlcSwitch must be started before chainArb since the latter
2447
                // relies on htlcSwitch to deliver resolution message upon
2448
                // start.
2449
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2450
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2451
                        startErr = err
×
2452
                        return
×
2453
                }
×
2454

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

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

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

2473
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2474
                if err := s.graphDB.Start(); err != nil {
3✔
2475
                        startErr = err
×
2476
                        return
×
2477
                }
×
2478

2479
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2480
                if err := s.graphBuilder.Start(); err != nil {
3✔
2481
                        startErr = err
×
2482
                        return
×
2483
                }
×
2484

2485
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2486
                if err := s.chanRouter.Start(); err != nil {
3✔
2487
                        startErr = err
×
2488
                        return
×
2489
                }
×
2490
                // The authGossiper depends on the chanRouter and therefore
2491
                // should be started after it.
2492
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2493
                if err := s.authGossiper.Start(); err != nil {
3✔
2494
                        startErr = err
×
2495
                        return
×
2496
                }
×
2497

2498
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2499
                if err := s.invoices.Start(); err != nil {
3✔
2500
                        startErr = err
×
2501
                        return
×
2502
                }
×
2503

2504
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2505
                if err := s.sphinx.Start(); err != nil {
3✔
2506
                        startErr = err
×
2507
                        return
×
2508
                }
×
2509

2510
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2511
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2512
                        startErr = err
×
2513
                        return
×
2514
                }
×
2515

2516
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2517
                if err := s.chanEventStore.Start(); err != nil {
3✔
2518
                        startErr = err
×
2519
                        return
×
2520
                }
×
2521

2522
                cleanup.add(func() error {
3✔
2523
                        s.missionController.StopStoreTickers()
×
2524
                        return nil
×
2525
                })
×
2526
                s.missionController.RunStoreTickers()
3✔
2527

3✔
2528
                // Before we start the connMgr, we'll check to see if we have
3✔
2529
                // any backups to recover. We do this now as we want to ensure
3✔
2530
                // that have all the information we need to handle channel
3✔
2531
                // recovery _before_ we even accept connections from any peers.
3✔
2532
                chanRestorer := &chanDBRestorer{
3✔
2533
                        db:         s.chanStateDB,
3✔
2534
                        secretKeys: s.cc.KeyRing,
3✔
2535
                        chainArb:   s.chainArb,
3✔
2536
                }
3✔
2537
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2538
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2539
                                s.chansToRestore.PackedSingleChanBackups,
×
2540
                                s.cc.KeyRing, chanRestorer, s,
×
2541
                        )
×
2542
                        if err != nil {
×
2543
                                startErr = fmt.Errorf("unable to unpack single "+
×
2544
                                        "backups: %v", err)
×
2545
                                return
×
2546
                        }
×
2547
                }
2548
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2549
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2550
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2551
                                s.cc.KeyRing, chanRestorer, s,
3✔
2552
                        )
3✔
2553
                        if err != nil {
3✔
2554
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2555
                                        "backup: %v", err)
×
2556
                                return
×
2557
                        }
×
2558
                }
2559

2560
                // chanSubSwapper must be started after the `channelNotifier`
2561
                // because it depends on channel events as a synchronization
2562
                // point.
2563
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2564
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2565
                        startErr = err
×
2566
                        return
×
2567
                }
×
2568

2569
                if s.torController != nil {
3✔
2570
                        cleanup = cleanup.add(s.torController.Stop)
×
2571
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2572
                                startErr = err
×
2573
                                return
×
2574
                        }
×
2575
                }
2576

2577
                if s.natTraversal != nil {
3✔
2578
                        s.wg.Add(1)
×
2579
                        go s.watchExternalIP()
×
2580
                }
×
2581

2582
                // Start connmgr last to prevent connections before init.
2583
                cleanup = cleanup.add(func() error {
3✔
2584
                        s.connMgr.Stop()
×
2585
                        return nil
×
2586
                })
×
2587

2588
                // RESOLVE: s.connMgr.Start() is called here, but
2589
                // brontide.NewListener() is called in newServer. This means
2590
                // that we are actually listening and partially accepting
2591
                // inbound connections even before the connMgr starts.
2592
                //
2593
                // TODO(yy): move the log into the connMgr's `Start` method.
2594
                srvrLog.Info("connMgr starting...")
3✔
2595
                s.connMgr.Start()
3✔
2596
                srvrLog.Debug("connMgr started")
3✔
2597

3✔
2598
                // If peers are specified as a config option, we'll add those
3✔
2599
                // peers first.
3✔
2600
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2601
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2602
                                peerAddrCfg,
3✔
2603
                        )
3✔
2604
                        if err != nil {
3✔
2605
                                startErr = fmt.Errorf("unable to parse peer "+
×
2606
                                        "pubkey from config: %v", err)
×
2607
                                return
×
2608
                        }
×
2609
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2610
                        if err != nil {
3✔
2611
                                startErr = fmt.Errorf("unable to parse peer "+
×
2612
                                        "address provided as a config option: "+
×
2613
                                        "%v", err)
×
2614
                                return
×
2615
                        }
×
2616

2617
                        peerAddr := &lnwire.NetAddress{
3✔
2618
                                IdentityKey: parsedPubkey,
3✔
2619
                                Address:     addr,
3✔
2620
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2621
                        }
3✔
2622

3✔
2623
                        err = s.ConnectToPeer(
3✔
2624
                                peerAddr, true,
3✔
2625
                                s.cfg.ConnectionTimeout,
3✔
2626
                        )
3✔
2627
                        if err != nil {
3✔
2628
                                startErr = fmt.Errorf("unable to connect to "+
×
2629
                                        "peer address provided as a config "+
×
2630
                                        "option: %v", err)
×
2631
                                return
×
2632
                        }
×
2633
                }
2634

2635
                // Subscribe to NodeAnnouncements that advertise new addresses
2636
                // our persistent peers.
2637
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2638
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2639
                                "addr: %v", err)
×
2640

×
2641
                        startErr = err
×
2642
                        return
×
2643
                }
×
2644

2645
                // With all the relevant sub-systems started, we'll now attempt
2646
                // to establish persistent connections to our direct channel
2647
                // collaborators within the network. Before doing so however,
2648
                // we'll prune our set of link nodes found within the database
2649
                // to ensure we don't reconnect to any nodes we no longer have
2650
                // open channels with.
2651
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2652
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2653

×
2654
                        startErr = err
×
2655
                        return
×
2656
                }
×
2657

2658
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2659
                        srvrLog.Errorf("Failed to establish persistent "+
×
2660
                                "connections: %v", err)
×
2661
                }
×
2662

2663
                // setSeedList is a helper function that turns multiple DNS seed
2664
                // server tuples from the command line or config file into the
2665
                // data structure we need and does a basic formal sanity check
2666
                // in the process.
2667
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2668
                        if len(tuples) == 0 {
×
2669
                                return
×
2670
                        }
×
2671

2672
                        result := make([][2]string, len(tuples))
×
2673
                        for idx, tuple := range tuples {
×
2674
                                tuple = strings.TrimSpace(tuple)
×
2675
                                if len(tuple) == 0 {
×
2676
                                        return
×
2677
                                }
×
2678

2679
                                servers := strings.Split(tuple, ",")
×
2680
                                if len(servers) > 2 || len(servers) == 0 {
×
2681
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2682
                                                "seed tuple: %v", servers)
×
2683
                                        return
×
2684
                                }
×
2685

2686
                                copy(result[idx][:], servers)
×
2687
                        }
2688

2689
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2690
                }
2691

2692
                // Let users overwrite the DNS seed nodes. We only allow them
2693
                // for bitcoin mainnet/testnet/signet.
2694
                if s.cfg.Bitcoin.MainNet {
3✔
2695
                        setSeedList(
×
2696
                                s.cfg.Bitcoin.DNSSeeds,
×
2697
                                chainreg.BitcoinMainnetGenesis,
×
2698
                        )
×
2699
                }
×
2700
                if s.cfg.Bitcoin.TestNet3 {
3✔
2701
                        setSeedList(
×
2702
                                s.cfg.Bitcoin.DNSSeeds,
×
2703
                                chainreg.BitcoinTestnetGenesis,
×
2704
                        )
×
2705
                }
×
2706
                if s.cfg.Bitcoin.TestNet4 {
3✔
2707
                        setSeedList(
×
2708
                                s.cfg.Bitcoin.DNSSeeds,
×
2709
                                chainreg.BitcoinTestnet4Genesis,
×
2710
                        )
×
2711
                }
×
2712
                if s.cfg.Bitcoin.SigNet {
3✔
2713
                        setSeedList(
×
2714
                                s.cfg.Bitcoin.DNSSeeds,
×
2715
                                chainreg.BitcoinSignetGenesis,
×
2716
                        )
×
2717
                }
×
2718

2719
                // If network bootstrapping hasn't been disabled, then we'll
2720
                // configure the set of active bootstrappers, and launch a
2721
                // dedicated goroutine to maintain a set of persistent
2722
                // connections.
2723
                if !s.cfg.NoNetBootstrap {
6✔
2724
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2725
                        if err != nil {
3✔
2726
                                startErr = err
×
2727
                                return
×
2728
                        }
×
2729

2730
                        s.wg.Add(1)
3✔
2731
                        go s.peerBootstrapper(
3✔
2732
                                ctx, defaultMinPeers, bootstrappers,
3✔
2733
                        )
3✔
2734
                } else {
3✔
2735
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2736
                }
3✔
2737

2738
                // Start the blockbeat after all other subsystems have been
2739
                // started so they are ready to receive new blocks.
2740
                cleanup = cleanup.add(func() error {
3✔
2741
                        s.blockbeatDispatcher.Stop()
×
2742
                        return nil
×
2743
                })
×
2744
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2745
                        startErr = err
×
2746
                        return
×
2747
                }
×
2748

2749
                // Set the active flag now that we've completed the full
2750
                // startup.
2751
                atomic.StoreInt32(&s.active, 1)
3✔
2752
        })
2753

2754
        if startErr != nil {
3✔
2755
                cleanup.run()
×
2756
        }
×
2757
        return startErr
3✔
2758
}
2759

2760
// Stop gracefully shutsdown the main daemon server. This function will signal
2761
// any active goroutines, or helper objects to exit, then blocks until they've
2762
// all successfully exited. Additionally, any/all listeners are closed.
2763
// NOTE: This function is safe for concurrent access.
2764
func (s *server) Stop() error {
3✔
2765
        s.stop.Do(func() {
6✔
2766
                atomic.StoreInt32(&s.stopping, 1)
3✔
2767

3✔
2768
                ctx := context.Background()
3✔
2769

3✔
2770
                close(s.quit)
3✔
2771

3✔
2772
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2773
                s.connMgr.Stop()
3✔
2774

3✔
2775
                // Stop dispatching blocks to other systems immediately.
3✔
2776
                s.blockbeatDispatcher.Stop()
3✔
2777

3✔
2778
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2779
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2780
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2781
                }
×
2782
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2783
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2784
                }
×
2785
                if err := s.sphinx.Stop(); err != nil {
3✔
2786
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2787
                }
×
2788
                if err := s.invoices.Stop(); err != nil {
3✔
2789
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2790
                }
×
2791
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2792
                        srvrLog.Warnf("failed to stop interceptable "+
×
2793
                                "switch: %v", err)
×
2794
                }
×
2795
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2796
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2797
                                "modifier: %v", err)
×
2798
                }
×
2799
                if err := s.chanRouter.Stop(); err != nil {
3✔
2800
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2801
                }
×
2802
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2803
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2804
                }
×
2805
                if err := s.graphDB.Stop(); err != nil {
3✔
2806
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2807
                }
×
2808
                if err := s.chainArb.Stop(); err != nil {
3✔
2809
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2810
                }
×
2811
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2812
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2813
                }
×
2814
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2815
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2816
                                err)
×
2817
                }
×
2818
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2819
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2820
                }
×
2821
                if err := s.authGossiper.Stop(); err != nil {
3✔
2822
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2823
                }
×
2824
                if err := s.sweeper.Stop(); err != nil {
3✔
2825
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2826
                }
×
2827
                if err := s.txPublisher.Stop(); err != nil {
3✔
2828
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2829
                }
×
2830
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2831
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2832
                }
×
2833
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2834
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2835
                }
×
2836
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2837
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2838
                }
×
2839

2840
                // Update channel.backup file. Make sure to do it before
2841
                // stopping chanSubSwapper.
2842
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2843
                        ctx, s.chanStateDB, s.addrSource,
3✔
2844
                )
3✔
2845
                if err != nil {
3✔
2846
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2847
                                err)
×
2848
                } else {
3✔
2849
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2850
                        if err != nil {
6✔
2851
                                srvrLog.Warnf("Manual update of channel "+
3✔
2852
                                        "backup failed: %v", err)
3✔
2853
                        }
3✔
2854
                }
2855

2856
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2857
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2858
                }
×
2859
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2860
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2861
                }
×
2862
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2863
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2864
                                err)
×
2865
                }
×
2866
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2867
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2868
                                err)
×
2869
                }
×
2870
                s.missionController.StopStoreTickers()
3✔
2871

3✔
2872
                // Disconnect from each active peers to ensure that
3✔
2873
                // peerTerminationWatchers signal completion to each peer.
3✔
2874
                for _, peer := range s.Peers() {
6✔
2875
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2876
                        if err != nil {
3✔
2877
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2878
                                        "received error: %v", peer.IdentityKey(),
×
2879
                                        err,
×
2880
                                )
×
2881
                        }
×
2882
                }
2883

2884
                // Now that all connections have been torn down, stop the tower
2885
                // client which will reliably flush all queued states to the
2886
                // tower. If this is halted for any reason, the force quit timer
2887
                // will kick in and abort to allow this method to return.
2888
                if s.towerClientMgr != nil {
6✔
2889
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2890
                                srvrLog.Warnf("Unable to shut down tower "+
×
2891
                                        "client manager: %v", err)
×
2892
                        }
×
2893
                }
2894

2895
                if s.hostAnn != nil {
3✔
2896
                        if err := s.hostAnn.Stop(); err != nil {
×
2897
                                srvrLog.Warnf("unable to shut down host "+
×
2898
                                        "annoucner: %v", err)
×
2899
                        }
×
2900
                }
2901

2902
                if s.livenessMonitor != nil {
6✔
2903
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2904
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2905
                                        "monitor: %v", err)
×
2906
                        }
×
2907
                }
2908

2909
                // Wait for all lingering goroutines to quit.
2910
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2911
                s.wg.Wait()
3✔
2912

3✔
2913
                srvrLog.Debug("Stopping buffer pools...")
3✔
2914
                s.sigPool.Stop()
3✔
2915
                s.writePool.Stop()
3✔
2916
                s.readPool.Stop()
3✔
2917
        })
2918

2919
        return nil
3✔
2920
}
2921

2922
// Stopped returns true if the server has been instructed to shutdown.
2923
// NOTE: This function is safe for concurrent access.
2924
func (s *server) Stopped() bool {
3✔
2925
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2926
}
3✔
2927

2928
// configurePortForwarding attempts to set up port forwarding for the different
2929
// ports that the server will be listening on.
2930
//
2931
// NOTE: This should only be used when using some kind of NAT traversal to
2932
// automatically set up forwarding rules.
2933
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2934
        ip, err := s.natTraversal.ExternalIP()
×
2935
        if err != nil {
×
2936
                return nil, err
×
2937
        }
×
2938
        s.lastDetectedIP = ip
×
2939

×
2940
        externalIPs := make([]string, 0, len(ports))
×
2941
        for _, port := range ports {
×
2942
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2943
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2944
                        continue
×
2945
                }
2946

2947
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2948
                externalIPs = append(externalIPs, hostIP)
×
2949
        }
2950

2951
        return externalIPs, nil
×
2952
}
2953

2954
// removePortForwarding attempts to clear the forwarding rules for the different
2955
// ports the server is currently listening on.
2956
//
2957
// NOTE: This should only be used when using some kind of NAT traversal to
2958
// automatically set up forwarding rules.
2959
func (s *server) removePortForwarding() {
×
2960
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2961
        for _, port := range forwardedPorts {
×
2962
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2963
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2964
                                "port %d: %v", port, err)
×
2965
                }
×
2966
        }
2967
}
2968

2969
// watchExternalIP continuously checks for an updated external IP address every
2970
// 15 minutes. Once a new IP address has been detected, it will automatically
2971
// handle port forwarding rules and send updated node announcements to the
2972
// currently connected peers.
2973
//
2974
// NOTE: This MUST be run as a goroutine.
2975
func (s *server) watchExternalIP() {
×
2976
        defer s.wg.Done()
×
2977

×
2978
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2979
        // up by the server.
×
2980
        defer s.removePortForwarding()
×
2981

×
2982
        // Keep track of the external IPs set by the user to avoid replacing
×
2983
        // them when detecting a new IP.
×
2984
        ipsSetByUser := make(map[string]struct{})
×
2985
        for _, ip := range s.cfg.ExternalIPs {
×
2986
                ipsSetByUser[ip.String()] = struct{}{}
×
2987
        }
×
2988

2989
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2990

×
2991
        ticker := time.NewTicker(15 * time.Minute)
×
2992
        defer ticker.Stop()
×
2993
out:
×
2994
        for {
×
2995
                select {
×
2996
                case <-ticker.C:
×
2997
                        // We'll start off by making sure a new IP address has
×
2998
                        // been detected.
×
2999
                        ip, err := s.natTraversal.ExternalIP()
×
3000
                        if err != nil {
×
3001
                                srvrLog.Debugf("Unable to retrieve the "+
×
3002
                                        "external IP address: %v", err)
×
3003
                                continue
×
3004
                        }
3005

3006
                        // Periodically renew the NAT port forwarding.
3007
                        for _, port := range forwardedPorts {
×
3008
                                err := s.natTraversal.AddPortMapping(port)
×
3009
                                if err != nil {
×
3010
                                        srvrLog.Warnf("Unable to automatically "+
×
3011
                                                "re-create port forwarding using %s: %v",
×
3012
                                                s.natTraversal.Name(), err)
×
3013
                                } else {
×
3014
                                        srvrLog.Debugf("Automatically re-created "+
×
3015
                                                "forwarding for port %d using %s to "+
×
3016
                                                "advertise external IP",
×
3017
                                                port, s.natTraversal.Name())
×
3018
                                }
×
3019
                        }
3020

3021
                        if ip.Equal(s.lastDetectedIP) {
×
3022
                                continue
×
3023
                        }
3024

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

×
3027
                        // Next, we'll craft the new addresses that will be
×
3028
                        // included in the new node announcement and advertised
×
3029
                        // to the network. Each address will consist of the new
×
3030
                        // IP detected and one of the currently advertised
×
3031
                        // ports.
×
3032
                        var newAddrs []net.Addr
×
3033
                        for _, port := range forwardedPorts {
×
3034
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
3035
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
3036
                                if err != nil {
×
3037
                                        srvrLog.Debugf("Unable to resolve "+
×
3038
                                                "host %v: %v", addr, err)
×
3039
                                        continue
×
3040
                                }
3041

3042
                                newAddrs = append(newAddrs, addr)
×
3043
                        }
3044

3045
                        // Skip the update if we weren't able to resolve any of
3046
                        // the new addresses.
3047
                        if len(newAddrs) == 0 {
×
3048
                                srvrLog.Debug("Skipping node announcement " +
×
3049
                                        "update due to not being able to " +
×
3050
                                        "resolve any new addresses")
×
3051
                                continue
×
3052
                        }
3053

3054
                        // Now, we'll need to update the addresses in our node's
3055
                        // announcement in order to propagate the update
3056
                        // throughout the network. We'll only include addresses
3057
                        // that have a different IP from the previous one, as
3058
                        // the previous IP is no longer valid.
3059
                        currentNodeAnn := s.getNodeAnnouncement()
×
3060

×
3061
                        for _, addr := range currentNodeAnn.Addresses {
×
3062
                                host, _, err := net.SplitHostPort(addr.String())
×
3063
                                if err != nil {
×
3064
                                        srvrLog.Debugf("Unable to determine "+
×
3065
                                                "host from address %v: %v",
×
3066
                                                addr, err)
×
3067
                                        continue
×
3068
                                }
3069

3070
                                // We'll also make sure to include external IPs
3071
                                // set manually by the user.
3072
                                _, setByUser := ipsSetByUser[addr.String()]
×
3073
                                if setByUser || host != s.lastDetectedIP.String() {
×
3074
                                        newAddrs = append(newAddrs, addr)
×
3075
                                }
×
3076
                        }
3077

3078
                        // Then, we'll generate a new timestamped node
3079
                        // announcement with the updated addresses and broadcast
3080
                        // it to our peers.
3081
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3082
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3083
                        )
×
3084
                        if err != nil {
×
3085
                                srvrLog.Debugf("Unable to generate new node "+
×
3086
                                        "announcement: %v", err)
×
3087
                                continue
×
3088
                        }
3089

3090
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3091
                        if err != nil {
×
3092
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3093
                                        "announcement to peers: %v", err)
×
3094
                                continue
×
3095
                        }
3096

3097
                        // Finally, update the last IP seen to the current one.
3098
                        s.lastDetectedIP = ip
×
3099
                case <-s.quit:
×
3100
                        break out
×
3101
                }
3102
        }
3103
}
3104

3105
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3106
// based on the server, and currently active bootstrap mechanisms as defined
3107
// within the current configuration.
3108
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3109
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3110

3✔
3111
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3112

3✔
3113
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3114
        // this can be used by default if we've already partially seeded the
3✔
3115
        // network.
3✔
3116
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3117
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3118
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3119
        )
3✔
3120
        if err != nil {
3✔
3121
                return nil, err
×
3122
        }
×
3123
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3124

3✔
3125
        // If this isn't using simnet or regtest mode, then one of our
3✔
3126
        // additional bootstrapping sources will be the set of running DNS
3✔
3127
        // seeds.
3✔
3128
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
3129
                //nolint:ll
×
3130
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3131

×
3132
                // If we have a set of DNS seeds for this chain, then we'll add
×
3133
                // it as an additional bootstrapping source.
×
3134
                if ok {
×
3135
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3136
                                "seeds: %v", dnsSeeds)
×
3137

×
3138
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3139
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3140
                        )
×
3141
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3142
                }
×
3143
        }
3144

3145
        return bootStrappers, nil
3✔
3146
}
3147

3148
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3149
// needs to ignore, which is made of three parts,
3150
//   - the node itself needs to be skipped as it doesn't make sense to connect
3151
//     to itself.
3152
//   - the peers that already have connections with, as in s.peersByPub.
3153
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3154
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3155
        s.mu.RLock()
3✔
3156
        defer s.mu.RUnlock()
3✔
3157

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

3✔
3160
        // We should ignore ourselves from bootstrapping.
3✔
3161
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3162
        ignore[selfKey] = struct{}{}
3✔
3163

3✔
3164
        // Ignore all connected peers.
3✔
3165
        for _, peer := range s.peersByPub {
3✔
3166
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3167
                ignore[nID] = struct{}{}
×
3168
        }
×
3169

3170
        // Ignore all persistent peers as they have a dedicated reconnecting
3171
        // process.
3172
        for pubKeyStr := range s.persistentPeers {
3✔
3173
                var nID autopilot.NodeID
×
3174
                copy(nID[:], []byte(pubKeyStr))
×
3175
                ignore[nID] = struct{}{}
×
3176
        }
×
3177

3178
        return ignore
3✔
3179
}
3180

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

3✔
3189
        defer s.wg.Done()
3✔
3190

3✔
3191
        // Before we continue, init the ignore peers map.
3✔
3192
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3193

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

3✔
3198
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3199
        // peers.
3✔
3200
        //
3✔
3201
        // We'll use a 15 second backoff, and double the time every time an
3✔
3202
        // epoch fails up to a ceiling.
3✔
3203
        backOff := time.Second * 15
3✔
3204

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

3✔
3210
        // We'll use the number of attempts and errors to determine if we need
3✔
3211
        // to increase the time between discovery epochs.
3✔
3212
        var epochErrors uint32 // To be used atomically.
3✔
3213
        var epochAttempts uint32
3✔
3214

3✔
3215
        for {
6✔
3216
                select {
3✔
3217
                // The ticker has just woken us up, so we'll need to check if
3218
                // we need to attempt to connect our to any more peers.
3219
                case <-sampleTicker.C:
×
3220
                        // Obtain the current number of peers, so we can gauge
×
3221
                        // if we need to sample more peers or not.
×
3222
                        s.mu.RLock()
×
3223
                        numActivePeers := uint32(len(s.peersByPub))
×
3224
                        s.mu.RUnlock()
×
3225

×
3226
                        // If we have enough peers, then we can loop back
×
3227
                        // around to the next round as we're done here.
×
3228
                        if numActivePeers >= numTargetPeers {
×
3229
                                continue
×
3230
                        }
3231

3232
                        // If all of our attempts failed during this last back
3233
                        // off period, then will increase our backoff to 5
3234
                        // minute ceiling to avoid an excessive number of
3235
                        // queries
3236
                        //
3237
                        // TODO(roasbeef): add reverse policy too?
3238

3239
                        if epochAttempts > 0 &&
×
3240
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3241

×
3242
                                sampleTicker.Stop()
×
3243

×
3244
                                backOff *= 2
×
3245
                                if backOff > bootstrapBackOffCeiling {
×
3246
                                        backOff = bootstrapBackOffCeiling
×
3247
                                }
×
3248

3249
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3250
                                        "%v", backOff)
×
3251
                                sampleTicker = time.NewTicker(backOff)
×
3252
                                continue
×
3253
                        }
3254

3255
                        atomic.StoreUint32(&epochErrors, 0)
×
3256
                        epochAttempts = 0
×
3257

×
3258
                        // Since we know need more peers, we'll compute the
×
3259
                        // exact number we need to reach our threshold.
×
3260
                        numNeeded := numTargetPeers - numActivePeers
×
3261

×
3262
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3263
                                "peers", numNeeded)
×
3264

×
3265
                        // With the number of peers we need calculated, we'll
×
3266
                        // query the network bootstrappers to sample a set of
×
3267
                        // random addrs for us.
×
3268
                        //
×
3269
                        // Before we continue, get a copy of the ignore peers
×
3270
                        // map.
×
3271
                        ignoreList = s.createBootstrapIgnorePeers()
×
3272

×
3273
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3274
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3275
                        )
×
3276
                        if err != nil {
×
3277
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3278
                                        "peers: %v", err)
×
3279
                                continue
×
3280
                        }
3281

3282
                        // Finally, we'll launch a new goroutine for each
3283
                        // prospective peer candidates.
3284
                        for _, addr := range peerAddrs {
×
3285
                                epochAttempts++
×
3286

×
3287
                                go func(a *lnwire.NetAddress) {
×
3288
                                        // TODO(roasbeef): can do AS, subnet,
×
3289
                                        // country diversity, etc
×
3290
                                        errChan := make(chan error, 1)
×
3291
                                        s.connectToPeer(
×
3292
                                                a, errChan,
×
3293
                                                s.cfg.ConnectionTimeout,
×
3294
                                        )
×
3295
                                        select {
×
3296
                                        case err := <-errChan:
×
3297
                                                if err == nil {
×
3298
                                                        return
×
3299
                                                }
×
3300

3301
                                                srvrLog.Errorf("Unable to "+
×
3302
                                                        "connect to %v: %v",
×
3303
                                                        a, err)
×
3304
                                                atomic.AddUint32(&epochErrors, 1)
×
3305
                                        case <-s.quit:
×
3306
                                        }
3307
                                }(addr)
3308
                        }
3309
                case <-s.quit:
3✔
3310
                        return
3✔
3311
                }
3312
        }
3313
}
3314

3315
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3316
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3317
// query back off each time we encounter a failure.
3318
const bootstrapBackOffCeiling = time.Minute * 5
3319

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

3✔
3327
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3328
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3329

3✔
3330
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3331
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3332
        var delaySignal <-chan time.Time
3✔
3333
        delayTime := time.Second * 2
3✔
3334

3✔
3335
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3336
        // then the main peer bootstrap logic.
3✔
3337
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3338

3✔
3339
        for attempts := 0; ; attempts++ {
6✔
3340
                // Check if the server has been requested to shut down in order
3✔
3341
                // to prevent blocking.
3✔
3342
                if s.Stopped() {
3✔
3343
                        return
×
3344
                }
×
3345

3346
                // We can exit our aggressive initial peer bootstrapping stage
3347
                // if we've reached out target number of peers.
3348
                s.mu.RLock()
3✔
3349
                numActivePeers := uint32(len(s.peersByPub))
3✔
3350
                s.mu.RUnlock()
3✔
3351

3✔
3352
                if numActivePeers >= numTargetPeers {
6✔
3353
                        return
3✔
3354
                }
3✔
3355

3356
                if attempts > 0 {
3✔
3357
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3358
                                "bootstrap peers (attempt #%v)", delayTime,
×
3359
                                attempts)
×
3360

×
3361
                        // We've completed at least one iterating and haven't
×
3362
                        // finished, so we'll start to insert a delay period
×
3363
                        // between each attempt.
×
3364
                        delaySignal = time.After(delayTime)
×
3365
                        select {
×
3366
                        case <-delaySignal:
×
3367
                        case <-s.quit:
×
3368
                                return
×
3369
                        }
3370

3371
                        // After our delay, we'll double the time we wait up to
3372
                        // the max back off period.
3373
                        delayTime *= 2
×
3374
                        if delayTime > backOffCeiling {
×
3375
                                delayTime = backOffCeiling
×
3376
                        }
×
3377
                }
3378

3379
                // Otherwise, we'll request for the remaining number of peers
3380
                // in order to reach our target.
3381
                peersNeeded := numTargetPeers - numActivePeers
3✔
3382
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3383
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3384
                )
3✔
3385
                if err != nil {
3✔
3386
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3387
                                "peers: %v", err)
×
3388
                        continue
×
3389
                }
3390

3391
                // Then, we'll attempt to establish a connection to the
3392
                // different peer addresses retrieved by our bootstrappers.
3393
                var wg sync.WaitGroup
3✔
3394
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3395
                        wg.Add(1)
3✔
3396
                        go func(addr *lnwire.NetAddress) {
6✔
3397
                                defer wg.Done()
3✔
3398

3✔
3399
                                errChan := make(chan error, 1)
3✔
3400
                                go s.connectToPeer(
3✔
3401
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3402
                                )
3✔
3403

3✔
3404
                                // We'll only allow this connection attempt to
3✔
3405
                                // take up to 3 seconds. This allows us to move
3✔
3406
                                // quickly by discarding peers that are slowing
3✔
3407
                                // us down.
3✔
3408
                                select {
3✔
3409
                                case err := <-errChan:
3✔
3410
                                        if err == nil {
6✔
3411
                                                return
3✔
3412
                                        }
3✔
3413
                                        srvrLog.Errorf("Unable to connect to "+
×
3414
                                                "%v: %v", addr, err)
×
3415
                                // TODO: tune timeout? 3 seconds might be *too*
3416
                                // aggressive but works well.
3417
                                case <-time.After(3 * time.Second):
×
3418
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3419
                                                "to not establishing a "+
×
3420
                                                "connection within 3 seconds",
×
3421
                                                addr)
×
3422
                                case <-s.quit:
×
3423
                                }
3424
                        }(bootstrapAddr)
3425
                }
3426

3427
                wg.Wait()
3✔
3428
        }
3429
}
3430

3431
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3432
// order to listen for inbound connections over Tor.
3433
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3434
        // Determine the different ports the server is listening on. The onion
×
3435
        // service's virtual port will map to these ports and one will be picked
×
3436
        // at random when the onion service is being accessed.
×
3437
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3438
        for _, listenAddr := range s.listenAddrs {
×
3439
                port := listenAddr.(*net.TCPAddr).Port
×
3440
                listenPorts = append(listenPorts, port)
×
3441
        }
×
3442

3443
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3444
        if err != nil {
×
3445
                return err
×
3446
        }
×
3447

3448
        // Once the port mapping has been set, we can go ahead and automatically
3449
        // create our onion service. The service's private key will be saved to
3450
        // disk in order to regain access to this service when restarting `lnd`.
3451
        onionCfg := tor.AddOnionConfig{
×
3452
                VirtualPort: defaultPeerPort,
×
3453
                TargetPorts: listenPorts,
×
3454
                Store: tor.NewOnionFile(
×
3455
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3456
                        encrypter,
×
3457
                ),
×
3458
        }
×
3459

×
3460
        switch {
×
3461
        case s.cfg.Tor.V2:
×
3462
                onionCfg.Type = tor.V2
×
3463
        case s.cfg.Tor.V3:
×
3464
                onionCfg.Type = tor.V3
×
3465
        }
3466

3467
        addr, err := s.torController.AddOnion(onionCfg)
×
3468
        if err != nil {
×
3469
                return err
×
3470
        }
×
3471

3472
        // Now that the onion service has been created, we'll add the onion
3473
        // address it can be reached at to our list of advertised addresses.
3474
        newNodeAnn, err := s.genNodeAnnouncement(
×
3475
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3476
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3477
                },
×
3478
        )
3479
        if err != nil {
×
3480
                return fmt.Errorf("unable to generate new node "+
×
3481
                        "announcement: %v", err)
×
3482
        }
×
3483

3484
        // Finally, we'll update the on-disk version of our announcement so it
3485
        // will eventually propagate to nodes in the network.
3486
        selfNode := &models.LightningNode{
×
3487
                HaveNodeAnnouncement: true,
×
3488
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3489
                Addresses:            newNodeAnn.Addresses,
×
3490
                Alias:                newNodeAnn.Alias.String(),
×
3491
                Features: lnwire.NewFeatureVector(
×
3492
                        newNodeAnn.Features, lnwire.Features,
×
3493
                ),
×
3494
                Color:        newNodeAnn.RGBColor,
×
3495
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3496
        }
×
3497
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3498
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3499
                return fmt.Errorf("can't set self node: %w", err)
×
3500
        }
×
3501

3502
        return nil
×
3503
}
3504

3505
// findChannel finds a channel given a public key and ChannelID. It is an
3506
// optimization that is quicker than seeking for a channel given only the
3507
// ChannelID.
3508
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3509
        *channeldb.OpenChannel, error) {
3✔
3510

3✔
3511
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3512
        if err != nil {
3✔
3513
                return nil, err
×
3514
        }
×
3515

3516
        for _, channel := range nodeChans {
6✔
3517
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3518
                        return channel, nil
3✔
3519
                }
3✔
3520
        }
3521

3522
        return nil, fmt.Errorf("unable to find channel")
3✔
3523
}
3524

3525
// getNodeAnnouncement fetches the current, fully signed node announcement.
3526
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3527
        s.mu.Lock()
3✔
3528
        defer s.mu.Unlock()
3✔
3529

3✔
3530
        return *s.currentNodeAnn
3✔
3531
}
3✔
3532

3533
// genNodeAnnouncement generates and returns the current fully signed node
3534
// announcement. The time stamp of the announcement will be updated in order
3535
// to ensure it propagates through the network.
3536
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3537
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3538

3✔
3539
        s.mu.Lock()
3✔
3540
        defer s.mu.Unlock()
3✔
3541

3✔
3542
        // Create a shallow copy of the current node announcement to work on.
3✔
3543
        // This ensures the original announcement remains unchanged
3✔
3544
        // until the new announcement is fully signed and valid.
3✔
3545
        newNodeAnn := *s.currentNodeAnn
3✔
3546

3✔
3547
        // First, try to update our feature manager with the updated set of
3✔
3548
        // features.
3✔
3549
        if features != nil {
6✔
3550
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3551
                        feature.SetNodeAnn: features,
3✔
3552
                }
3✔
3553
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3554
                if err != nil {
6✔
3555
                        return lnwire.NodeAnnouncement{}, err
3✔
3556
                }
3✔
3557

3558
                // If we could successfully update our feature manager, add
3559
                // an update modifier to include these new features to our
3560
                // set.
3561
                modifiers = append(
3✔
3562
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3563
                )
3✔
3564
        }
3565

3566
        // Always update the timestamp when refreshing to ensure the update
3567
        // propagates.
3568
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3569

3✔
3570
        // Apply the requested changes to the node announcement.
3✔
3571
        for _, modifier := range modifiers {
6✔
3572
                modifier(&newNodeAnn)
3✔
3573
        }
3✔
3574

3575
        // Sign a new update after applying all of the passed modifiers.
3576
        err := netann.SignNodeAnnouncement(
3✔
3577
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3578
        )
3✔
3579
        if err != nil {
6✔
3580
                return lnwire.NodeAnnouncement{}, err
3✔
3581
        }
3✔
3582

3583
        // If signing succeeds, update the current announcement.
3584
        *s.currentNodeAnn = newNodeAnn
3✔
3585

3✔
3586
        return *s.currentNodeAnn, nil
3✔
3587
}
3588

3589
// updateAndBroadcastSelfNode generates a new node announcement
3590
// applying the giving modifiers and updating the time stamp
3591
// to ensure it propagates through the network. Then it broadcasts
3592
// it to the network.
3593
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3594
        features *lnwire.RawFeatureVector,
3595
        modifiers ...netann.NodeAnnModifier) error {
3✔
3596

3✔
3597
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3598
        if err != nil {
6✔
3599
                return fmt.Errorf("unable to generate new node "+
3✔
3600
                        "announcement: %v", err)
3✔
3601
        }
3✔
3602

3603
        // Update the on-disk version of our announcement.
3604
        // Load and modify self node istead of creating anew instance so we
3605
        // don't risk overwriting any existing values.
3606
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3607
        if err != nil {
3✔
3608
                return fmt.Errorf("unable to get current source node: %w", err)
×
3609
        }
×
3610

3611
        selfNode.HaveNodeAnnouncement = true
3✔
3612
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3613
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3614
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3615
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3616
        selfNode.Color = newNodeAnn.RGBColor
3✔
3617
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3618

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

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

3625
        // Finally, propagate it to the nodes in the network.
3626
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3627
        if err != nil {
3✔
3628
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3629
                        "announcement to peers: %v", err)
×
3630
                return err
×
3631
        }
×
3632

3633
        return nil
3✔
3634
}
3635

3636
type nodeAddresses struct {
3637
        pubKey    *btcec.PublicKey
3638
        addresses []net.Addr
3639
}
3640

3641
// establishPersistentConnections attempts to establish persistent connections
3642
// to all our direct channel collaborators. In order to promote liveness of our
3643
// active channels, we instruct the connection manager to attempt to establish
3644
// and maintain persistent connections to all our direct channel counterparties.
3645
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3646
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3647
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3648
        // since other PubKey forms can't be compared.
3✔
3649
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3650

3✔
3651
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3652
        // attempt to connect to based on our set of previous connections. Set
3✔
3653
        // the reconnection port to the default peer port.
3✔
3654
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3655
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3656
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3657
        }
×
3658

3659
        for _, node := range linkNodes {
6✔
3660
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3661
                nodeAddrs := &nodeAddresses{
3✔
3662
                        pubKey:    node.IdentityPub,
3✔
3663
                        addresses: node.Addresses,
3✔
3664
                }
3✔
3665
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3666
        }
3✔
3667

3668
        // After checking our previous connections for addresses to connect to,
3669
        // iterate through the nodes in our channel graph to find addresses
3670
        // that have been added via NodeAnnouncement messages.
3671
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3672
        // each of the nodes.
3673
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3674
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3675
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3676

3✔
3677
                // If the remote party has announced the channel to us, but we
3✔
3678
                // haven't yet, then we won't have a policy. However, we don't
3✔
3679
                // need this to connect to the peer, so we'll log it and move on.
3✔
3680
                if !havePolicy {
3✔
3681
                        srvrLog.Warnf("No channel policy found for "+
×
3682
                                "ChannelPoint(%v): ", chanPoint)
×
3683
                }
×
3684

3685
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3686

3✔
3687
                // Add all unique addresses from channel
3✔
3688
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3689
                // connect to for this peer.
3✔
3690
                addrSet := make(map[string]net.Addr)
3✔
3691
                for _, addr := range channelPeer.Addresses {
6✔
3692
                        switch addr.(type) {
3✔
3693
                        case *net.TCPAddr:
3✔
3694
                                addrSet[addr.String()] = addr
3✔
3695

3696
                        // We'll only attempt to connect to Tor addresses if Tor
3697
                        // outbound support is enabled.
3698
                        case *tor.OnionAddr:
×
3699
                                if s.cfg.Tor.Active {
×
3700
                                        addrSet[addr.String()] = addr
×
3701
                                }
×
3702
                        }
3703
                }
3704

3705
                // If this peer is also recorded as a link node, we'll add any
3706
                // additional addresses that have not already been selected.
3707
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3708
                if ok {
6✔
3709
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3710
                                switch lnAddress.(type) {
3✔
3711
                                case *net.TCPAddr:
3✔
3712
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3713

3714
                                // We'll only attempt to connect to Tor
3715
                                // addresses if Tor outbound support is enabled.
3716
                                case *tor.OnionAddr:
×
3717
                                        if s.cfg.Tor.Active {
×
3718
                                                //nolint:ll
×
3719
                                                addrSet[lnAddress.String()] = lnAddress
×
3720
                                        }
×
3721
                                }
3722
                        }
3723
                }
3724

3725
                // Construct a slice of the deduped addresses.
3726
                var addrs []net.Addr
3✔
3727
                for _, addr := range addrSet {
6✔
3728
                        addrs = append(addrs, addr)
3✔
3729
                }
3✔
3730

3731
                n := &nodeAddresses{
3✔
3732
                        addresses: addrs,
3✔
3733
                }
3✔
3734
                n.pubKey, err = channelPeer.PubKey()
3✔
3735
                if err != nil {
3✔
3736
                        return err
×
3737
                }
×
3738

3739
                graphAddrs[pubStr] = n
3✔
3740
                return nil
3✔
3741
        }
3742
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3743
                ctx, forEachSrcNodeChan, func() {
6✔
3744
                        clear(graphAddrs)
3✔
3745
                },
3✔
3746
        )
3747
        if err != nil {
3✔
3748
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3749
                        "%v", err)
×
3750

×
3751
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3752
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3753

×
3754
                        return err
×
3755
                }
×
3756
        }
3757

3758
        // Combine the addresses from the link nodes and the channel graph.
3759
        for pubStr, nodeAddr := range graphAddrs {
6✔
3760
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3761
        }
3✔
3762

3763
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3764
                len(nodeAddrsMap))
3✔
3765

3✔
3766
        // Acquire and hold server lock until all persistent connection requests
3✔
3767
        // have been recorded and sent to the connection manager.
3✔
3768
        s.mu.Lock()
3✔
3769
        defer s.mu.Unlock()
3✔
3770

3✔
3771
        // Iterate through the combined list of addresses from prior links and
3✔
3772
        // node announcements and attempt to reconnect to each node.
3✔
3773
        var numOutboundConns int
3✔
3774
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3775
                // Add this peer to the set of peers we should maintain a
3✔
3776
                // persistent connection with. We set the value to false to
3✔
3777
                // indicate that we should not continue to reconnect if the
3✔
3778
                // number of channels returns to zero, since this peer has not
3✔
3779
                // been requested as perm by the user.
3✔
3780
                s.persistentPeers[pubStr] = false
3✔
3781
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3782
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3783
                }
3✔
3784

3785
                for _, address := range nodeAddr.addresses {
6✔
3786
                        // Create a wrapper address which couples the IP and
3✔
3787
                        // the pubkey so the brontide authenticated connection
3✔
3788
                        // can be established.
3✔
3789
                        lnAddr := &lnwire.NetAddress{
3✔
3790
                                IdentityKey: nodeAddr.pubKey,
3✔
3791
                                Address:     address,
3✔
3792
                        }
3✔
3793

3✔
3794
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3795
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3796
                }
3✔
3797

3798
                // We'll connect to the first 10 peers immediately, then
3799
                // randomly stagger any remaining connections if the
3800
                // stagger initial reconnect flag is set. This ensures
3801
                // that mobile nodes or nodes with a small number of
3802
                // channels obtain connectivity quickly, but larger
3803
                // nodes are able to disperse the costs of connecting to
3804
                // all peers at once.
3805
                if numOutboundConns < numInstantInitReconnect ||
3✔
3806
                        !s.cfg.StaggerInitialReconnect {
6✔
3807

3✔
3808
                        go s.connectToPersistentPeer(pubStr)
3✔
3809
                } else {
3✔
3810
                        go s.delayInitialReconnect(pubStr)
×
3811
                }
×
3812

3813
                numOutboundConns++
3✔
3814
        }
3815

3816
        return nil
3✔
3817
}
3818

3819
// delayInitialReconnect will attempt a reconnection to the given peer after
3820
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3821
//
3822
// NOTE: This method MUST be run as a goroutine.
3823
func (s *server) delayInitialReconnect(pubStr string) {
×
3824
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3825
        select {
×
3826
        case <-time.After(delay):
×
3827
                s.connectToPersistentPeer(pubStr)
×
3828
        case <-s.quit:
×
3829
        }
3830
}
3831

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

3✔
3838
        s.mu.Lock()
3✔
3839
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3840
                delete(s.persistentPeers, pubKeyStr)
3✔
3841
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3842
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3843
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3844
                s.mu.Unlock()
3✔
3845

3✔
3846
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3847
                        "peer has no open channels", compressedPubKey)
3✔
3848

3✔
3849
                return
3✔
3850
        }
3✔
3851
        s.mu.Unlock()
3✔
3852
}
3853

3854
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3855
// is instead used to remove persistent peer state for a peer that has been
3856
// disconnected for good cause by the server. Currently, a gossip ban from
3857
// sending garbage and the server running out of restricted-access
3858
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3859
// future, this function may expand when more ban criteria is added.
3860
//
3861
// NOTE: The server's write lock MUST be held when this is called.
3862
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3863
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3864
                delete(s.persistentPeers, remotePub)
×
3865
                delete(s.persistentPeersBackoff, remotePub)
×
3866
                delete(s.persistentPeerAddrs, remotePub)
×
3867
                s.cancelConnReqs(remotePub, nil)
×
3868
        }
×
3869
}
3870

3871
// BroadcastMessage sends a request to the server to broadcast a set of
3872
// messages to all peers other than the one specified by the `skips` parameter.
3873
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3874
// the target peers.
3875
//
3876
// NOTE: This function is safe for concurrent access.
3877
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3878
        msgs ...lnwire.Message) error {
3✔
3879

3✔
3880
        // Filter out peers found in the skips map. We synchronize access to
3✔
3881
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3882
        // exact set of peers present at the time of invocation.
3✔
3883
        s.mu.RLock()
3✔
3884
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3885
        for pubStr, sPeer := range s.peersByPub {
6✔
3886
                if skips != nil {
6✔
3887
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3888
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3889
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3890
                                continue
3✔
3891
                        }
3892
                }
3893

3894
                peers = append(peers, sPeer)
3✔
3895
        }
3896
        s.mu.RUnlock()
3✔
3897

3✔
3898
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3899
        // all messages to each of peers.
3✔
3900
        var wg sync.WaitGroup
3✔
3901
        for _, sPeer := range peers {
6✔
3902
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3903
                        sPeer.PubKey())
3✔
3904

3✔
3905
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3906
                wg.Add(1)
3✔
3907
                s.wg.Add(1)
3✔
3908
                go func(p lnpeer.Peer) {
6✔
3909
                        defer s.wg.Done()
3✔
3910
                        defer wg.Done()
3✔
3911

3✔
3912
                        p.SendMessageLazy(false, msgs...)
3✔
3913
                }(sPeer)
3✔
3914
        }
3915

3916
        // Wait for all messages to have been dispatched before returning to
3917
        // caller.
3918
        wg.Wait()
3✔
3919

3✔
3920
        return nil
3✔
3921
}
3922

3923
// NotifyWhenOnline can be called by other subsystems to get notified when a
3924
// particular peer comes online. The peer itself is sent across the peerChan.
3925
//
3926
// NOTE: This function is safe for concurrent access.
3927
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3928
        peerChan chan<- lnpeer.Peer) {
3✔
3929

3✔
3930
        s.mu.Lock()
3✔
3931

3✔
3932
        // Compute the target peer's identifier.
3✔
3933
        pubStr := string(peerKey[:])
3✔
3934

3✔
3935
        // Check if peer is connected.
3✔
3936
        peer, ok := s.peersByPub[pubStr]
3✔
3937
        if ok {
6✔
3938
                // Unlock here so that the mutex isn't held while we are
3✔
3939
                // waiting for the peer to become active.
3✔
3940
                s.mu.Unlock()
3✔
3941

3✔
3942
                // Wait until the peer signals that it is actually active
3✔
3943
                // rather than only in the server's maps.
3✔
3944
                select {
3✔
3945
                case <-peer.ActiveSignal():
3✔
3946
                case <-peer.QuitSignal():
×
3947
                        // The peer quit, so we'll add the channel to the slice
×
3948
                        // and return.
×
3949
                        s.mu.Lock()
×
3950
                        s.peerConnectedListeners[pubStr] = append(
×
3951
                                s.peerConnectedListeners[pubStr], peerChan,
×
3952
                        )
×
3953
                        s.mu.Unlock()
×
3954
                        return
×
3955
                }
3956

3957
                // Connected, can return early.
3958
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3959

3✔
3960
                select {
3✔
3961
                case peerChan <- peer:
3✔
3962
                case <-s.quit:
×
3963
                }
3964

3965
                return
3✔
3966
        }
3967

3968
        // Not connected, store this listener such that it can be notified when
3969
        // the peer comes online.
3970
        s.peerConnectedListeners[pubStr] = append(
3✔
3971
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3972
        )
3✔
3973
        s.mu.Unlock()
3✔
3974
}
3975

3976
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3977
// the given public key has been disconnected. The notification is signaled by
3978
// closing the channel returned.
3979
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3980
        s.mu.Lock()
3✔
3981
        defer s.mu.Unlock()
3✔
3982

3✔
3983
        c := make(chan struct{})
3✔
3984

3✔
3985
        // If the peer is already offline, we can immediately trigger the
3✔
3986
        // notification.
3✔
3987
        peerPubKeyStr := string(peerPubKey[:])
3✔
3988
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3989
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3990
                close(c)
×
3991
                return c
×
3992
        }
×
3993

3994
        // Otherwise, the peer is online, so we'll keep track of the channel to
3995
        // trigger the notification once the server detects the peer
3996
        // disconnects.
3997
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3998
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3999
        )
3✔
4000

3✔
4001
        return c
3✔
4002
}
4003

4004
// FindPeer will return the peer that corresponds to the passed in public key.
4005
// This function is used by the funding manager, allowing it to update the
4006
// daemon's local representation of the remote peer.
4007
//
4008
// NOTE: This function is safe for concurrent access.
4009
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
4010
        s.mu.RLock()
3✔
4011
        defer s.mu.RUnlock()
3✔
4012

3✔
4013
        pubStr := string(peerKey.SerializeCompressed())
3✔
4014

3✔
4015
        return s.findPeerByPubStr(pubStr)
3✔
4016
}
3✔
4017

4018
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
4019
// which should be a string representation of the peer's serialized, compressed
4020
// public key.
4021
//
4022
// NOTE: This function is safe for concurrent access.
4023
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
4024
        s.mu.RLock()
3✔
4025
        defer s.mu.RUnlock()
3✔
4026

3✔
4027
        return s.findPeerByPubStr(pubStr)
3✔
4028
}
3✔
4029

4030
// findPeerByPubStr is an internal method that retrieves the specified peer from
4031
// the server's internal state using.
4032
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
4033
        peer, ok := s.peersByPub[pubStr]
3✔
4034
        if !ok {
6✔
4035
                return nil, ErrPeerNotConnected
3✔
4036
        }
3✔
4037

4038
        return peer, nil
3✔
4039
}
4040

4041
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
4042
// exponential backoff. If no previous backoff was known, the default is
4043
// returned.
4044
func (s *server) nextPeerBackoff(pubStr string,
4045
        startTime time.Time) time.Duration {
3✔
4046

3✔
4047
        // Now, determine the appropriate backoff to use for the retry.
3✔
4048
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
4049
        if !ok {
6✔
4050
                // If an existing backoff was unknown, use the default.
3✔
4051
                return s.cfg.MinBackoff
3✔
4052
        }
3✔
4053

4054
        // If the peer failed to start properly, we'll just use the previous
4055
        // backoff to compute the subsequent randomized exponential backoff
4056
        // duration. This will roughly double on average.
4057
        if startTime.IsZero() {
4✔
4058
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
1✔
4059
        }
1✔
4060

4061
        // The peer succeeded in starting. If the connection didn't last long
4062
        // enough to be considered stable, we'll continue to back off retries
4063
        // with this peer.
4064
        connDuration := time.Since(startTime)
3✔
4065
        if connDuration < defaultStableConnDuration {
6✔
4066
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4067
        }
3✔
4068

4069
        // The peer succeed in starting and this was stable peer, so we'll
4070
        // reduce the timeout duration by the length of the connection after
4071
        // applying randomized exponential backoff. We'll only apply this in the
4072
        // case that:
4073
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4074
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4075
        if relaxedBackoff > s.cfg.MinBackoff {
×
4076
                return relaxedBackoff
×
4077
        }
×
4078

4079
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4080
        // the stable connection lasted much longer than our previous backoff.
4081
        // To reward such good behavior, we'll reconnect after the default
4082
        // timeout.
4083
        return s.cfg.MinBackoff
×
4084
}
4085

4086
// shouldDropLocalConnection determines if our local connection to a remote peer
4087
// should be dropped in the case of concurrent connection establishment. In
4088
// order to deterministically decide which connection should be dropped, we'll
4089
// utilize the ordering of the local and remote public key. If we didn't use
4090
// such a tie breaker, then we risk _both_ connections erroneously being
4091
// dropped.
4092
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4093
        localPubBytes := local.SerializeCompressed()
×
4094
        remotePubPbytes := remote.SerializeCompressed()
×
4095

×
4096
        // The connection that comes from the node with a "smaller" pubkey
×
4097
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4098
        // should drop our established connection.
×
4099
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4100
}
×
4101

4102
// InboundPeerConnected initializes a new peer in response to a new inbound
4103
// connection.
4104
//
4105
// NOTE: This function is safe for concurrent access.
4106
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4107
        // Exit early if we have already been instructed to shutdown, this
3✔
4108
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4109
        if s.Stopped() {
3✔
4110
                return
×
4111
        }
×
4112

4113
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4114
        pubSer := nodePub.SerializeCompressed()
3✔
4115
        pubStr := string(pubSer)
3✔
4116

3✔
4117
        var pubBytes [33]byte
3✔
4118
        copy(pubBytes[:], pubSer)
3✔
4119

3✔
4120
        s.mu.Lock()
3✔
4121
        defer s.mu.Unlock()
3✔
4122

3✔
4123
        // If we already have an outbound connection to this peer, then ignore
3✔
4124
        // this new connection.
3✔
4125
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4126
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4127
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4128
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4129

3✔
4130
                conn.Close()
3✔
4131
                return
3✔
4132
        }
3✔
4133

4134
        // If we already have a valid connection that is scheduled to take
4135
        // precedence once the prior peer has finished disconnecting, we'll
4136
        // ignore this connection.
4137
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4138
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4139
                        "scheduled", conn.RemoteAddr(), p)
×
4140
                conn.Close()
×
4141
                return
×
4142
        }
×
4143

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

3✔
4146
        // Check to see if we already have a connection with this peer. If so,
3✔
4147
        // we may need to drop our existing connection. This prevents us from
3✔
4148
        // having duplicate connections to the same peer. We forgo adding a
3✔
4149
        // default case as we expect these to be the only error values returned
3✔
4150
        // from findPeerByPubStr.
3✔
4151
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4152
        switch err {
3✔
4153
        case ErrPeerNotConnected:
3✔
4154
                // We were unable to locate an existing connection with the
3✔
4155
                // target peer, proceed to connect.
3✔
4156
                s.cancelConnReqs(pubStr, nil)
3✔
4157
                s.peerConnected(conn, nil, true)
3✔
4158

4159
        case nil:
3✔
4160
                ctx := btclog.WithCtx(
3✔
4161
                        context.TODO(),
3✔
4162
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4163
                )
3✔
4164

3✔
4165
                // We already have a connection with the incoming peer. If the
3✔
4166
                // connection we've already established should be kept and is
3✔
4167
                // not of the same type of the new connection (inbound), then
3✔
4168
                // we'll close out the new connection s.t there's only a single
3✔
4169
                // connection between us.
3✔
4170
                localPub := s.identityECDH.PubKey()
3✔
4171
                if !connectedPeer.Inbound() &&
3✔
4172
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4173

×
4174
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4175
                                "peer, but already have outbound "+
×
4176
                                "connection, dropping conn",
×
4177
                                fmt.Errorf("already have outbound conn"))
×
4178
                        conn.Close()
×
4179
                        return
×
4180
                }
×
4181

4182
                // Otherwise, if we should drop the connection, then we'll
4183
                // disconnect our already connected peer.
4184
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4185

3✔
4186
                s.cancelConnReqs(pubStr, nil)
3✔
4187

3✔
4188
                // Remove the current peer from the server's internal state and
3✔
4189
                // signal that the peer termination watcher does not need to
3✔
4190
                // execute for this peer.
3✔
4191
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4192
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4193
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4194
                        s.peerConnected(conn, nil, true)
3✔
4195
                }
3✔
4196
        }
4197
}
4198

4199
// OutboundPeerConnected initializes a new peer in response to a new outbound
4200
// connection.
4201
// NOTE: This function is safe for concurrent access.
4202
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4203
        // Exit early if we have already been instructed to shutdown, this
3✔
4204
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4205
        if s.Stopped() {
3✔
4206
                return
×
4207
        }
×
4208

4209
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4210
        pubSer := nodePub.SerializeCompressed()
3✔
4211
        pubStr := string(pubSer)
3✔
4212

3✔
4213
        var pubBytes [33]byte
3✔
4214
        copy(pubBytes[:], pubSer)
3✔
4215

3✔
4216
        s.mu.Lock()
3✔
4217
        defer s.mu.Unlock()
3✔
4218

3✔
4219
        // If we already have an inbound connection to this peer, then ignore
3✔
4220
        // this new connection.
3✔
4221
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4222
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4223
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4224
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4225

3✔
4226
                if connReq != nil {
6✔
4227
                        s.connMgr.Remove(connReq.ID())
3✔
4228
                }
3✔
4229
                conn.Close()
3✔
4230
                return
3✔
4231
        }
4232
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4233
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4234
                s.connMgr.Remove(connReq.ID())
×
4235
                conn.Close()
×
4236
                return
×
4237
        }
×
4238

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

×
4245
                if connReq != nil {
×
4246
                        s.connMgr.Remove(connReq.ID())
×
4247
                }
×
4248

4249
                conn.Close()
×
4250
                return
×
4251
        }
4252

4253
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4254
                conn.RemoteAddr())
3✔
4255

3✔
4256
        if connReq != nil {
6✔
4257
                // A successful connection was returned by the connmgr.
3✔
4258
                // Immediately cancel all pending requests, excluding the
3✔
4259
                // outbound connection we just established.
3✔
4260
                ignore := connReq.ID()
3✔
4261
                s.cancelConnReqs(pubStr, &ignore)
3✔
4262
        } else {
6✔
4263
                // This was a successful connection made by some other
3✔
4264
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4265
                s.cancelConnReqs(pubStr, nil)
3✔
4266
        }
3✔
4267

4268
        // If we already have a connection with this peer, decide whether or not
4269
        // we need to drop the stale connection. We forgo adding a default case
4270
        // as we expect these to be the only error values returned from
4271
        // findPeerByPubStr.
4272
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4273
        switch err {
3✔
4274
        case ErrPeerNotConnected:
3✔
4275
                // We were unable to locate an existing connection with the
3✔
4276
                // target peer, proceed to connect.
3✔
4277
                s.peerConnected(conn, connReq, false)
3✔
4278

4279
        case nil:
3✔
4280
                ctx := btclog.WithCtx(
3✔
4281
                        context.TODO(),
3✔
4282
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4283
                )
3✔
4284

3✔
4285
                // We already have a connection with the incoming peer. If the
3✔
4286
                // connection we've already established should be kept and is
3✔
4287
                // not of the same type of the new connection (outbound), then
3✔
4288
                // we'll close out the new connection s.t there's only a single
3✔
4289
                // connection between us.
3✔
4290
                localPub := s.identityECDH.PubKey()
3✔
4291
                if connectedPeer.Inbound() &&
3✔
4292
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4293

×
4294
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4295
                                "to peer, but already have inbound "+
×
4296
                                "connection, dropping conn",
×
4297
                                fmt.Errorf("already have inbound conn"))
×
4298
                        if connReq != nil {
×
4299
                                s.connMgr.Remove(connReq.ID())
×
4300
                        }
×
4301
                        conn.Close()
×
4302
                        return
×
4303
                }
4304

4305
                // Otherwise, _their_ connection should be dropped. So we'll
4306
                // disconnect the peer and send the now obsolete peer to the
4307
                // server for garbage collection.
4308
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4309

3✔
4310
                // Remove the current peer from the server's internal state and
3✔
4311
                // signal that the peer termination watcher does not need to
3✔
4312
                // execute for this peer.
3✔
4313
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4314
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4315
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4316
                        s.peerConnected(conn, connReq, false)
3✔
4317
                }
3✔
4318
        }
4319
}
4320

4321
// UnassignedConnID is the default connection ID that a request can have before
4322
// it actually is submitted to the connmgr.
4323
// TODO(conner): move into connmgr package, or better, add connmgr method for
4324
// generating atomic IDs
4325
const UnassignedConnID uint64 = 0
4326

4327
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4328
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4329
// Afterwards, each connection request removed from the connmgr. The caller can
4330
// optionally specify a connection ID to ignore, which prevents us from
4331
// canceling a successful request. All persistent connreqs for the provided
4332
// pubkey are discarded after the operationjw.
4333
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4334
        // First, cancel any lingering persistent retry attempts, which will
3✔
4335
        // prevent retries for any with backoffs that are still maturing.
3✔
4336
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4337
                close(cancelChan)
3✔
4338
                delete(s.persistentRetryCancels, pubStr)
3✔
4339
        }
3✔
4340

4341
        // Next, check to see if we have any outstanding persistent connection
4342
        // requests to this peer. If so, then we'll remove all of these
4343
        // connection requests, and also delete the entry from the map.
4344
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4345
        if !ok {
6✔
4346
                return
3✔
4347
        }
3✔
4348

4349
        for _, connReq := range connReqs {
6✔
4350
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4351

3✔
4352
                // Atomically capture the current request identifier.
3✔
4353
                connID := connReq.ID()
3✔
4354

3✔
4355
                // Skip any zero IDs, this indicates the request has not
3✔
4356
                // yet been schedule.
3✔
4357
                if connID == UnassignedConnID {
3✔
4358
                        continue
×
4359
                }
4360

4361
                // Skip a particular connection ID if instructed.
4362
                if skip != nil && connID == *skip {
6✔
4363
                        continue
3✔
4364
                }
4365

4366
                s.connMgr.Remove(connID)
3✔
4367
        }
4368

4369
        delete(s.persistentConnReqs, pubStr)
3✔
4370
}
4371

4372
// handleCustomMessage dispatches an incoming custom peers message to
4373
// subscribers.
4374
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4375
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4376
                peer, msg.Type)
3✔
4377

3✔
4378
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4379
                Peer: peer,
3✔
4380
                Msg:  msg,
3✔
4381
        })
3✔
4382
}
3✔
4383

4384
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4385
// messages.
4386
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4387
        return s.customMessageServer.Subscribe()
3✔
4388
}
3✔
4389

4390
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4391
// the channelNotifier's NotifyOpenChannelEvent.
4392
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4393
        remotePub *btcec.PublicKey) {
3✔
4394

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

4401
        // Notify subscribers about this open channel event.
4402
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4403
}
4404

4405
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4406
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4407
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4408
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4409

3✔
4410
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4411
        // peer.
3✔
4412
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4413
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4414
                        "channel[%v] pending open",
×
4415
                        remotePub.SerializeCompressed(), op)
×
4416
        }
×
4417

4418
        // Notify subscribers about this event.
4419
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4420
}
4421

4422
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4423
// calls the channelNotifier's NotifyFundingTimeout.
4424
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4425
        remotePub *btcec.PublicKey) {
3✔
4426

3✔
4427
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4428
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4429
        if err != nil {
3✔
4430
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4431
                        "channel[%v] pending close",
×
4432
                        remotePub.SerializeCompressed(), op)
×
4433
        }
×
4434

4435
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4436
                // If we encounter an error while attempting to disconnect the
×
4437
                // peer, log the error.
×
4438
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4439
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4440
                }
×
4441
        }
4442

4443
        // Notify subscribers about this event.
4444
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4445
}
4446

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

3✔
4454
        brontideConn := conn.(*brontide.Conn)
3✔
4455
        addr := conn.RemoteAddr()
3✔
4456
        pubKey := brontideConn.RemotePub()
3✔
4457

3✔
4458
        // Only restrict access for inbound connections, which means if the
3✔
4459
        // remote node's public key is banned or the restricted slots are used
3✔
4460
        // up, we will drop the connection.
3✔
4461
        //
3✔
4462
        // TODO(yy): Consider perform this check in
3✔
4463
        // `peerAccessMan.addPeerAccess`.
3✔
4464
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4465
        if inbound && err != nil {
3✔
4466
                pubSer := pubKey.SerializeCompressed()
×
4467

×
4468
                // Clean up the persistent peer maps if we're dropping this
×
4469
                // connection.
×
4470
                s.bannedPersistentPeerConnection(string(pubSer))
×
4471

×
4472
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4473
                        "of restricted-access connection slots: %v.", pubSer,
×
4474
                        err)
×
4475

×
4476
                conn.Close()
×
4477

×
4478
                return
×
4479
        }
×
4480

4481
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4482
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4483

3✔
4484
        peerAddr := &lnwire.NetAddress{
3✔
4485
                IdentityKey: pubKey,
3✔
4486
                Address:     addr,
3✔
4487
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4488
        }
3✔
4489

3✔
4490
        // With the brontide connection established, we'll now craft the feature
3✔
4491
        // vectors to advertise to the remote node.
3✔
4492
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4493
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4494

3✔
4495
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4496
        // found, create a fresh buffer.
3✔
4497
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4498
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4499
        if !ok {
6✔
4500
                var err error
3✔
4501
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4502
                if err != nil {
3✔
4503
                        srvrLog.Errorf("unable to create peer %v", err)
×
4504
                        return
×
4505
                }
×
4506
        }
4507

4508
        // If we directly set the peer.Config TowerClient member to the
4509
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4510
        // the peer.Config's TowerClient member will not evaluate to nil even
4511
        // though the underlying value is nil. To avoid this gotcha which can
4512
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4513
        // TowerClient if needed.
4514
        var towerClient wtclient.ClientManager
3✔
4515
        if s.towerClientMgr != nil {
6✔
4516
                towerClient = s.towerClientMgr
3✔
4517
        }
3✔
4518

4519
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4520
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4521

3✔
4522
        // Now that we've established a connection, create a peer, and it to the
3✔
4523
        // set of currently active peers. Configure the peer with the incoming
3✔
4524
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4525
        // offered that would trigger channel closure. In case of outgoing
3✔
4526
        // htlcs, an extra block is added to prevent the channel from being
3✔
4527
        // closed when the htlc is outstanding and a new block comes in.
3✔
4528
        pCfg := peer.Config{
3✔
4529
                Conn:                    brontideConn,
3✔
4530
                ConnReq:                 connReq,
3✔
4531
                Addr:                    peerAddr,
3✔
4532
                Inbound:                 inbound,
3✔
4533
                Features:                initFeatures,
3✔
4534
                LegacyFeatures:          legacyFeatures,
3✔
4535
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4536
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4537
                ErrorBuffer:             errBuffer,
3✔
4538
                WritePool:               s.writePool,
3✔
4539
                ReadPool:                s.readPool,
3✔
4540
                Switch:                  s.htlcSwitch,
3✔
4541
                InterceptSwitch:         s.interceptableSwitch,
3✔
4542
                ChannelDB:               s.chanStateDB,
3✔
4543
                ChannelGraph:            s.graphDB,
3✔
4544
                ChainArb:                s.chainArb,
3✔
4545
                AuthGossiper:            s.authGossiper,
3✔
4546
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4547
                ChainIO:                 s.cc.ChainIO,
3✔
4548
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4549
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4550
                SigPool:                 s.sigPool,
3✔
4551
                Wallet:                  s.cc.Wallet,
3✔
4552
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4553
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4554
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4555
                Sphinx:                  s.sphinx,
3✔
4556
                WitnessBeacon:           s.witnessBeacon,
3✔
4557
                Invoices:                s.invoices,
3✔
4558
                ChannelNotifier:         s.channelNotifier,
3✔
4559
                HtlcNotifier:            s.htlcNotifier,
3✔
4560
                TowerClient:             towerClient,
3✔
4561
                DisconnectPeer:          s.DisconnectPeer,
3✔
4562
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4563
                        lnwire.NodeAnnouncement, error) {
6✔
4564

3✔
4565
                        return s.genNodeAnnouncement(nil)
3✔
4566
                },
3✔
4567

4568
                PongBuf: s.pongBuf,
4569

4570
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4571

4572
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4573

4574
                FundingManager: s.fundingMgr,
4575

4576
                Hodl:                    s.cfg.Hodl,
4577
                UnsafeReplay:            s.cfg.UnsafeReplay,
4578
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4579
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4580
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4581
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4582
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4583
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4584
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4585
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4586
                HandleCustomMessage:    s.handleCustomMessage,
4587
                GetAliases:             s.aliasMgr.GetAliases,
4588
                RequestAlias:           s.aliasMgr.RequestAlias,
4589
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4590
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4591
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4592
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4593
                MaxFeeExposure:         thresholdMSats,
4594
                Quit:                   s.quit,
4595
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4596
                AuxSigner:              s.implCfg.AuxSigner,
4597
                MsgRouter:              s.implCfg.MsgRouter,
4598
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4599
                AuxResolver:            s.implCfg.AuxContractResolver,
4600
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4601
                ShouldFwdExpEndorsement: func() bool {
3✔
4602
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4603
                                return false
3✔
4604
                        }
3✔
4605

4606
                        return clock.NewDefaultClock().Now().Before(
3✔
4607
                                EndorsementExperimentEnd,
3✔
4608
                        )
3✔
4609
                },
4610
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4611
        }
4612

4613
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4614
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4615

3✔
4616
        p := peer.NewBrontide(pCfg)
3✔
4617

3✔
4618
        // Update the access manager with the access permission for this peer.
3✔
4619
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4620

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

3✔
4624
        s.addPeer(p)
3✔
4625

3✔
4626
        // Once we have successfully added the peer to the server, we can
3✔
4627
        // delete the previous error buffer from the server's map of error
3✔
4628
        // buffers.
3✔
4629
        delete(s.peerErrors, pkStr)
3✔
4630

3✔
4631
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4632
        // includes sending and receiving Init messages, which would be a DOS
3✔
4633
        // vector if we held the server's mutex throughout the procedure.
3✔
4634
        s.wg.Add(1)
3✔
4635
        go s.peerInitializer(p)
3✔
4636
}
4637

4638
// addPeer adds the passed peer to the server's global state of all active
4639
// peers.
4640
func (s *server) addPeer(p *peer.Brontide) {
3✔
4641
        if p == nil {
3✔
4642
                return
×
4643
        }
×
4644

4645
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4646

3✔
4647
        // Ignore new peers if we're shutting down.
3✔
4648
        if s.Stopped() {
3✔
4649
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4650
                        pubBytes)
×
4651
                p.Disconnect(ErrServerShuttingDown)
×
4652

×
4653
                return
×
4654
        }
×
4655

4656
        // Track the new peer in our indexes so we can quickly look it up either
4657
        // according to its public key, or its peer ID.
4658
        // TODO(roasbeef): pipe all requests through to the
4659
        // queryHandler/peerManager
4660

4661
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4662
        // be human-readable.
4663
        pubStr := string(pubBytes)
3✔
4664

3✔
4665
        s.peersByPub[pubStr] = p
3✔
4666

3✔
4667
        if p.Inbound() {
6✔
4668
                s.inboundPeers[pubStr] = p
3✔
4669
        } else {
6✔
4670
                s.outboundPeers[pubStr] = p
3✔
4671
        }
3✔
4672

4673
        // Inform the peer notifier of a peer online event so that it can be reported
4674
        // to clients listening for peer events.
4675
        var pubKey [33]byte
3✔
4676
        copy(pubKey[:], pubBytes)
3✔
4677
}
4678

4679
// peerInitializer asynchronously starts a newly connected peer after it has
4680
// been added to the server's peer map. This method sets up a
4681
// peerTerminationWatcher for the given peer, and ensures that it executes even
4682
// if the peer failed to start. In the event of a successful connection, this
4683
// method reads the negotiated, local feature-bits and spawns the appropriate
4684
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4685
// be signaled of the new peer once the method returns.
4686
//
4687
// NOTE: This MUST be launched as a goroutine.
4688
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4689
        defer s.wg.Done()
3✔
4690

3✔
4691
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4692

3✔
4693
        // Avoid initializing peers while the server is exiting.
3✔
4694
        if s.Stopped() {
3✔
4695
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4696
                        pubBytes)
×
4697
                return
×
4698
        }
×
4699

4700
        // Create a channel that will be used to signal a successful start of
4701
        // the link. This prevents the peer termination watcher from beginning
4702
        // its duty too early.
4703
        ready := make(chan struct{})
3✔
4704

3✔
4705
        // Before starting the peer, launch a goroutine to watch for the
3✔
4706
        // unexpected termination of this peer, which will ensure all resources
3✔
4707
        // are properly cleaned up, and re-establish persistent connections when
3✔
4708
        // necessary. The peer termination watcher will be short circuited if
3✔
4709
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4710
        // that the server has already handled the removal of this peer.
3✔
4711
        s.wg.Add(1)
3✔
4712
        go s.peerTerminationWatcher(p, ready)
3✔
4713

3✔
4714
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4715
        // will unblock the peerTerminationWatcher.
3✔
4716
        if err := p.Start(); err != nil {
6✔
4717
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4718

3✔
4719
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4720
                return
3✔
4721
        }
3✔
4722

4723
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4724
        // was successful, and to begin watching the peer's wait group.
4725
        close(ready)
3✔
4726

3✔
4727
        s.mu.Lock()
3✔
4728
        defer s.mu.Unlock()
3✔
4729

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

3✔
4733
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4734
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4735
        pubStr := string(pubBytes)
3✔
4736
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4737
                select {
3✔
4738
                case peerChan <- p:
3✔
4739
                case <-s.quit:
×
4740
                        return
×
4741
                }
4742
        }
4743
        delete(s.peerConnectedListeners, pubStr)
3✔
4744

3✔
4745
        // Since the peer has been fully initialized, now it's time to notify
3✔
4746
        // the RPC about the peer online event.
3✔
4747
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4748
}
4749

4750
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4751
// and then cleans up all resources allocated to the peer, notifies relevant
4752
// sub-systems of its demise, and finally handles re-connecting to the peer if
4753
// it's persistent. If the server intentionally disconnects a peer, it should
4754
// have a corresponding entry in the ignorePeerTermination map which will cause
4755
// the cleanup routine to exit early. The passed `ready` chan is used to
4756
// synchronize when WaitForDisconnect should begin watching on the peer's
4757
// waitgroup. The ready chan should only be signaled if the peer starts
4758
// successfully, otherwise the peer should be disconnected instead.
4759
//
4760
// NOTE: This MUST be launched as a goroutine.
4761
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4762
        defer s.wg.Done()
3✔
4763

3✔
4764
        ctx := btclog.WithCtx(
3✔
4765
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4766
        )
3✔
4767

3✔
4768
        p.WaitForDisconnect(ready)
3✔
4769

3✔
4770
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4771

3✔
4772
        // If the server is exiting then we can bail out early ourselves as all
3✔
4773
        // the other sub-systems will already be shutting down.
3✔
4774
        if s.Stopped() {
6✔
4775
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4776
                return
3✔
4777
        }
3✔
4778

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

3✔
4785
        pubKey := p.IdentityKey()
3✔
4786

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

3✔
4791
        // Tell the switch to remove all links associated with this peer.
3✔
4792
        // Passing nil as the target link indicates that all links associated
3✔
4793
        // with this interface should be closed.
3✔
4794
        //
3✔
4795
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4796
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4797
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4798
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4799
        }
×
4800

4801
        for _, link := range links {
6✔
4802
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4803
        }
3✔
4804

4805
        s.mu.Lock()
3✔
4806
        defer s.mu.Unlock()
3✔
4807

3✔
4808
        // If there were any notification requests for when this peer
3✔
4809
        // disconnected, we can trigger them now.
3✔
4810
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4811
        pubStr := string(pubKey.SerializeCompressed())
3✔
4812
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4813
                close(offlineChan)
3✔
4814
        }
3✔
4815
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4816

3✔
4817
        // If the server has already removed this peer, we can short circuit the
3✔
4818
        // peer termination watcher and skip cleanup.
3✔
4819
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4820
                delete(s.ignorePeerTermination, p)
3✔
4821

3✔
4822
                pubKey := p.PubKey()
3✔
4823
                pubStr := string(pubKey[:])
3✔
4824

3✔
4825
                // If a connection callback is present, we'll go ahead and
3✔
4826
                // execute it now that previous peer has fully disconnected. If
3✔
4827
                // the callback is not present, this likely implies the peer was
3✔
4828
                // purposefully disconnected via RPC, and that no reconnect
3✔
4829
                // should be attempted.
3✔
4830
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4831
                if ok {
6✔
4832
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4833
                        connCallback()
3✔
4834
                }
3✔
4835
                return
3✔
4836
        }
4837

4838
        // First, cleanup any remaining state the server has regarding the peer
4839
        // in question.
4840
        s.removePeerUnsafe(ctx, p)
3✔
4841

3✔
4842
        // Next, check to see if this is a persistent peer or not.
3✔
4843
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4844
                return
3✔
4845
        }
3✔
4846

4847
        // Get the last address that we used to connect to the peer.
4848
        addrs := []net.Addr{
3✔
4849
                p.NetAddress().Address,
3✔
4850
        }
3✔
4851

3✔
4852
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4853
        // reconnection purposes.
3✔
4854
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4855
        switch {
3✔
4856
        // We found advertised addresses, so use them.
4857
        case err == nil:
3✔
4858
                addrs = advertisedAddrs
3✔
4859

4860
        // The peer doesn't have an advertised address.
4861
        case err == errNoAdvertisedAddr:
3✔
4862
                // If it is an outbound peer then we fall back to the existing
3✔
4863
                // peer address.
3✔
4864
                if !p.Inbound() {
6✔
4865
                        break
3✔
4866
                }
4867

4868
                // Fall back to the existing peer address if
4869
                // we're not accepting connections over Tor.
4870
                if s.torController == nil {
6✔
4871
                        break
3✔
4872
                }
4873

4874
                // If we are, the peer's address won't be known
4875
                // to us (we'll see a private address, which is
4876
                // the address used by our onion service to dial
4877
                // to lnd), so we don't have enough information
4878
                // to attempt a reconnect.
4879
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4880
                        "to inbound peer without advertised address")
×
4881
                return
×
4882

4883
        // We came across an error retrieving an advertised
4884
        // address, log it, and fall back to the existing peer
4885
        // address.
4886
        default:
3✔
4887
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4888
                        "address for peer", err)
3✔
4889
        }
4890

4891
        // Make an easy lookup map so that we can check if an address
4892
        // is already in the address list that we have stored for this peer.
4893
        existingAddrs := make(map[string]bool)
3✔
4894
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4895
                existingAddrs[addr.String()] = true
3✔
4896
        }
3✔
4897

4898
        // Add any missing addresses for this peer to persistentPeerAddr.
4899
        for _, addr := range addrs {
6✔
4900
                if existingAddrs[addr.String()] {
3✔
4901
                        continue
×
4902
                }
4903

4904
                s.persistentPeerAddrs[pubStr] = append(
3✔
4905
                        s.persistentPeerAddrs[pubStr],
3✔
4906
                        &lnwire.NetAddress{
3✔
4907
                                IdentityKey: p.IdentityKey(),
3✔
4908
                                Address:     addr,
3✔
4909
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4910
                        },
3✔
4911
                )
3✔
4912
        }
4913

4914
        // Record the computed backoff in the backoff map.
4915
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4916
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4917

3✔
4918
        // Initialize a retry canceller for this peer if one does not
3✔
4919
        // exist.
3✔
4920
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4921
        if !ok {
6✔
4922
                cancelChan = make(chan struct{})
3✔
4923
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4924
        }
3✔
4925

4926
        // We choose not to wait group this go routine since the Connect
4927
        // call can stall for arbitrarily long if we shutdown while an
4928
        // outbound connection attempt is being made.
4929
        go func() {
6✔
4930
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4931
                        "re-establishment to persistent peer",
3✔
4932
                        "reconnecting_in", backoff)
3✔
4933

3✔
4934
                select {
3✔
4935
                case <-time.After(backoff):
3✔
4936
                case <-cancelChan:
3✔
4937
                        return
3✔
4938
                case <-s.quit:
3✔
4939
                        return
3✔
4940
                }
4941

4942
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4943
                        "connection")
3✔
4944

3✔
4945
                s.connectToPersistentPeer(pubStr)
3✔
4946
        }()
4947
}
4948

4949
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4950
// to connect to the peer. It creates connection requests if there are
4951
// currently none for a given address and it removes old connection requests
4952
// if the associated address is no longer in the latest address list for the
4953
// peer.
4954
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4955
        s.mu.Lock()
3✔
4956
        defer s.mu.Unlock()
3✔
4957

3✔
4958
        // Create an easy lookup map of the addresses we have stored for the
3✔
4959
        // peer. We will remove entries from this map if we have existing
3✔
4960
        // connection requests for the associated address and then any leftover
3✔
4961
        // entries will indicate which addresses we should create new
3✔
4962
        // connection requests for.
3✔
4963
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4964
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4965
                addrMap[addr.String()] = addr
3✔
4966
        }
3✔
4967

4968
        // Go through each of the existing connection requests and
4969
        // check if they correspond to the latest set of addresses. If
4970
        // there is a connection requests that does not use one of the latest
4971
        // advertised addresses then remove that connection request.
4972
        var updatedConnReqs []*connmgr.ConnReq
3✔
4973
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4974
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4975

3✔
4976
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4977
                // If the existing connection request is using one of the
4978
                // latest advertised addresses for the peer then we add it to
4979
                // updatedConnReqs and remove the associated address from
4980
                // addrMap so that we don't recreate this connReq later on.
4981
                case true:
×
4982
                        updatedConnReqs = append(
×
4983
                                updatedConnReqs, connReq,
×
4984
                        )
×
4985
                        delete(addrMap, lnAddr)
×
4986

4987
                // If the existing connection request is using an address that
4988
                // is not one of the latest advertised addresses for the peer
4989
                // then we remove the connecting request from the connection
4990
                // manager.
4991
                case false:
3✔
4992
                        srvrLog.Info(
3✔
4993
                                "Removing conn req:", connReq.Addr.String(),
3✔
4994
                        )
3✔
4995
                        s.connMgr.Remove(connReq.ID())
3✔
4996
                }
4997
        }
4998

4999
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
5000

3✔
5001
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
5002
        if !ok {
6✔
5003
                cancelChan = make(chan struct{})
3✔
5004
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
5005
        }
3✔
5006

5007
        // Any addresses left in addrMap are new ones that we have not made
5008
        // connection requests for. So create new connection requests for those.
5009
        // If there is more than one address in the address map, stagger the
5010
        // creation of the connection requests for those.
5011
        go func() {
6✔
5012
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
5013
                defer ticker.Stop()
3✔
5014

3✔
5015
                for _, addr := range addrMap {
6✔
5016
                        // Send the persistent connection request to the
3✔
5017
                        // connection manager, saving the request itself so we
3✔
5018
                        // can cancel/restart the process as needed.
3✔
5019
                        connReq := &connmgr.ConnReq{
3✔
5020
                                Addr:      addr,
3✔
5021
                                Permanent: true,
3✔
5022
                        }
3✔
5023

3✔
5024
                        s.mu.Lock()
3✔
5025
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
5026
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
5027
                        )
3✔
5028
                        s.mu.Unlock()
3✔
5029

3✔
5030
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
5031
                                "channel peer %v", addr)
3✔
5032

3✔
5033
                        go s.connMgr.Connect(connReq)
3✔
5034

3✔
5035
                        select {
3✔
5036
                        case <-s.quit:
3✔
5037
                                return
3✔
5038
                        case <-cancelChan:
3✔
5039
                                return
3✔
5040
                        case <-ticker.C:
3✔
5041
                        }
5042
                }
5043
        }()
5044
}
5045

5046
// removePeerUnsafe removes the passed peer from the server's state of all
5047
// active peers.
5048
//
5049
// NOTE: Server mutex must be held when calling this function.
5050
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
5051
        if p == nil {
3✔
5052
                return
×
5053
        }
×
5054

5055
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5056

3✔
5057
        // Exit early if we have already been instructed to shutdown, the peers
3✔
5058
        // will be disconnected in the server shutdown process.
3✔
5059
        if s.Stopped() {
3✔
5060
                return
×
5061
        }
×
5062

5063
        // Capture the peer's public key and string representation.
5064
        pKey := p.PubKey()
3✔
5065
        pubSer := pKey[:]
3✔
5066
        pubStr := string(pubSer)
3✔
5067

3✔
5068
        delete(s.peersByPub, pubStr)
3✔
5069

3✔
5070
        if p.Inbound() {
6✔
5071
                delete(s.inboundPeers, pubStr)
3✔
5072
        } else {
6✔
5073
                delete(s.outboundPeers, pubStr)
3✔
5074
        }
3✔
5075

5076
        // When removing the peer we make sure to disconnect it asynchronously
5077
        // to avoid blocking the main server goroutine because it is holding the
5078
        // server's mutex. Disconnecting the peer might block and wait until the
5079
        // peer has fully started up. This can happen if an inbound and outbound
5080
        // race condition occurs.
5081
        s.wg.Add(1)
3✔
5082
        go func() {
6✔
5083
                defer s.wg.Done()
3✔
5084

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

3✔
5087
                // If this peer had an active persistent connection request,
3✔
5088
                // remove it.
3✔
5089
                if p.ConnReq() != nil {
6✔
5090
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5091
                }
3✔
5092

5093
                // Remove the peer's access permission from the access manager.
5094
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5095
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5096

3✔
5097
                // Copy the peer's error buffer across to the server if it has
3✔
5098
                // any items in it so that we can restore peer errors across
3✔
5099
                // connections. We need to look up the error after the peer has
3✔
5100
                // been disconnected because we write the error in the
3✔
5101
                // `Disconnect` method.
3✔
5102
                s.mu.Lock()
3✔
5103
                if p.ErrorBuffer().Total() > 0 {
6✔
5104
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5105
                }
3✔
5106
                s.mu.Unlock()
3✔
5107

3✔
5108
                // Inform the peer notifier of a peer offline event so that it
3✔
5109
                // can be reported to clients listening for peer events.
3✔
5110
                var pubKey [33]byte
3✔
5111
                copy(pubKey[:], pubSer)
3✔
5112

3✔
5113
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5114
        }()
5115
}
5116

5117
// ConnectToPeer requests that the server connect to a Lightning Network peer
5118
// at the specified address. This function will *block* until either a
5119
// connection is established, or the initial handshake process fails.
5120
//
5121
// NOTE: This function is safe for concurrent access.
5122
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5123
        perm bool, timeout time.Duration) error {
3✔
5124

3✔
5125
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5126

3✔
5127
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5128
        // better granularity.  In certain conditions, this method requires
3✔
5129
        // making an outbound connection to a remote peer, which requires the
3✔
5130
        // lock to be released, and subsequently reacquired.
3✔
5131
        s.mu.Lock()
3✔
5132

3✔
5133
        // Ensure we're not already connected to this peer.
3✔
5134
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5135

3✔
5136
        // When there's no error it means we already have a connection with this
3✔
5137
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5138
        // set, we will ignore the existing connection and continue.
3✔
5139
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5140
                s.mu.Unlock()
3✔
5141
                return &errPeerAlreadyConnected{peer: peer}
3✔
5142
        }
3✔
5143

5144
        // Peer was not found, continue to pursue connection with peer.
5145

5146
        // If there's already a pending connection request for this pubkey,
5147
        // then we ignore this request to ensure we don't create a redundant
5148
        // connection.
5149
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5150
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5151
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5152
        }
3✔
5153

5154
        // If there's not already a pending or active connection to this node,
5155
        // then instruct the connection manager to attempt to establish a
5156
        // persistent connection to the peer.
5157
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5158
        if perm {
6✔
5159
                connReq := &connmgr.ConnReq{
3✔
5160
                        Addr:      addr,
3✔
5161
                        Permanent: true,
3✔
5162
                }
3✔
5163

3✔
5164
                // Since the user requested a permanent connection, we'll set
3✔
5165
                // the entry to true which will tell the server to continue
3✔
5166
                // reconnecting even if the number of channels with this peer is
3✔
5167
                // zero.
3✔
5168
                s.persistentPeers[targetPub] = true
3✔
5169
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5170
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5171
                }
3✔
5172
                s.persistentConnReqs[targetPub] = append(
3✔
5173
                        s.persistentConnReqs[targetPub], connReq,
3✔
5174
                )
3✔
5175
                s.mu.Unlock()
3✔
5176

3✔
5177
                go s.connMgr.Connect(connReq)
3✔
5178

3✔
5179
                return nil
3✔
5180
        }
5181
        s.mu.Unlock()
3✔
5182

3✔
5183
        // If we're not making a persistent connection, then we'll attempt to
3✔
5184
        // connect to the target peer. If the we can't make the connection, or
3✔
5185
        // the crypto negotiation breaks down, then return an error to the
3✔
5186
        // caller.
3✔
5187
        errChan := make(chan error, 1)
3✔
5188
        s.connectToPeer(addr, errChan, timeout)
3✔
5189

3✔
5190
        select {
3✔
5191
        case err := <-errChan:
3✔
5192
                return err
3✔
5193
        case <-s.quit:
×
5194
                return ErrServerShuttingDown
×
5195
        }
5196
}
5197

5198
// connectToPeer establishes a connection to a remote peer. errChan is used to
5199
// notify the caller if the connection attempt has failed. Otherwise, it will be
5200
// closed.
5201
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5202
        errChan chan<- error, timeout time.Duration) {
3✔
5203

3✔
5204
        conn, err := brontide.Dial(
3✔
5205
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5206
        )
3✔
5207
        if err != nil {
6✔
5208
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5209
                select {
3✔
5210
                case errChan <- err:
3✔
5211
                case <-s.quit:
×
5212
                }
5213
                return
3✔
5214
        }
5215

5216
        close(errChan)
3✔
5217

3✔
5218
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5219
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5220

3✔
5221
        s.OutboundPeerConnected(nil, conn)
3✔
5222
}
5223

5224
// DisconnectPeer sends the request to server to close the connection with peer
5225
// identified by public key.
5226
//
5227
// NOTE: This function is safe for concurrent access.
5228
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5229
        pubBytes := pubKey.SerializeCompressed()
3✔
5230
        pubStr := string(pubBytes)
3✔
5231

3✔
5232
        s.mu.Lock()
3✔
5233
        defer s.mu.Unlock()
3✔
5234

3✔
5235
        // Check that were actually connected to this peer. If not, then we'll
3✔
5236
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5237
        // currently connected to.
3✔
5238
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5239
        if err == ErrPeerNotConnected {
6✔
5240
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5241
        }
3✔
5242

5243
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5244

3✔
5245
        s.cancelConnReqs(pubStr, nil)
3✔
5246

3✔
5247
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5248
        // them from this map so we don't attempt to re-connect after we
3✔
5249
        // disconnect.
3✔
5250
        delete(s.persistentPeers, pubStr)
3✔
5251
        delete(s.persistentPeersBackoff, pubStr)
3✔
5252

3✔
5253
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5254
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5255
        //
3✔
5256
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5257
        // goroutine because we might hold the server's mutex.
3✔
5258
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5259

3✔
5260
        return nil
3✔
5261
}
5262

5263
// OpenChannel sends a request to the server to open a channel to the specified
5264
// peer identified by nodeKey with the passed channel funding parameters.
5265
//
5266
// NOTE: This function is safe for concurrent access.
5267
func (s *server) OpenChannel(
5268
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5269

3✔
5270
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5271
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5272
        // not blocked if the caller is not reading the updates.
3✔
5273
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5274
        req.Err = make(chan error, 1)
3✔
5275

3✔
5276
        // First attempt to locate the target peer to open a channel with, if
3✔
5277
        // we're unable to locate the peer then this request will fail.
3✔
5278
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5279
        s.mu.RLock()
3✔
5280
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5281
        if !ok {
3✔
5282
                s.mu.RUnlock()
×
5283

×
5284
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5285
                return req.Updates, req.Err
×
5286
        }
×
5287
        req.Peer = peer
3✔
5288
        s.mu.RUnlock()
3✔
5289

3✔
5290
        // We'll wait until the peer is active before beginning the channel
3✔
5291
        // opening process.
3✔
5292
        select {
3✔
5293
        case <-peer.ActiveSignal():
3✔
5294
        case <-peer.QuitSignal():
×
5295
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5296
                return req.Updates, req.Err
×
5297
        case <-s.quit:
×
5298
                req.Err <- ErrServerShuttingDown
×
5299
                return req.Updates, req.Err
×
5300
        }
5301

5302
        // If the fee rate wasn't specified at this point we fail the funding
5303
        // because of the missing fee rate information. The caller of the
5304
        // `OpenChannel` method needs to make sure that default values for the
5305
        // fee rate are set beforehand.
5306
        if req.FundingFeePerKw == 0 {
3✔
5307
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5308
                        "the channel opening transaction")
×
5309

×
5310
                return req.Updates, req.Err
×
5311
        }
×
5312

5313
        // Spawn a goroutine to send the funding workflow request to the funding
5314
        // manager. This allows the server to continue handling queries instead
5315
        // of blocking on this request which is exported as a synchronous
5316
        // request to the outside world.
5317
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5318

3✔
5319
        return req.Updates, req.Err
3✔
5320
}
5321

5322
// Peers returns a slice of all active peers.
5323
//
5324
// NOTE: This function is safe for concurrent access.
5325
func (s *server) Peers() []*peer.Brontide {
3✔
5326
        s.mu.RLock()
3✔
5327
        defer s.mu.RUnlock()
3✔
5328

3✔
5329
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5330
        for _, peer := range s.peersByPub {
6✔
5331
                peers = append(peers, peer)
3✔
5332
        }
3✔
5333

5334
        return peers
3✔
5335
}
5336

5337
// computeNextBackoff uses a truncated exponential backoff to compute the next
5338
// backoff using the value of the exiting backoff. The returned duration is
5339
// randomized in either direction by 1/20 to prevent tight loops from
5340
// stabilizing.
5341
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5342
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5343
        nextBackoff := 2 * currBackoff
3✔
5344
        if nextBackoff > maxBackoff {
6✔
5345
                nextBackoff = maxBackoff
3✔
5346
        }
3✔
5347

5348
        // Using 1/10 of our duration as a margin, compute a random offset to
5349
        // avoid the nodes entering connection cycles.
5350
        margin := nextBackoff / 10
3✔
5351

3✔
5352
        var wiggle big.Int
3✔
5353
        wiggle.SetUint64(uint64(margin))
3✔
5354
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5355
                // Randomizing is not mission critical, so we'll just return the
×
5356
                // current backoff.
×
5357
                return nextBackoff
×
5358
        }
×
5359

5360
        // Otherwise add in our wiggle, but subtract out half of the margin so
5361
        // that the backoff can tweaked by 1/20 in either direction.
5362
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5363
}
5364

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

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

3✔
5373
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5374
        if err != nil {
3✔
5375
                return nil, err
×
5376
        }
×
5377

5378
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5379
        if err != nil {
6✔
5380
                return nil, err
3✔
5381
        }
3✔
5382

5383
        if len(node.Addresses) == 0 {
6✔
5384
                return nil, errNoAdvertisedAddr
3✔
5385
        }
3✔
5386

5387
        return node.Addresses, nil
3✔
5388
}
5389

5390
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5391
// channel update for a target channel.
5392
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5393
        *lnwire.ChannelUpdate1, error) {
3✔
5394

3✔
5395
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5396
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5397
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5398
                if err != nil {
6✔
5399
                        return nil, err
3✔
5400
                }
3✔
5401

5402
                return netann.ExtractChannelUpdate(
3✔
5403
                        ourPubKey[:], info, edge1, edge2,
3✔
5404
                )
3✔
5405
        }
5406
}
5407

5408
// applyChannelUpdate applies the channel update to the different sub-systems of
5409
// the server. The useAlias boolean denotes whether or not to send an alias in
5410
// place of the real SCID.
5411
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5412
        op *wire.OutPoint, useAlias bool) error {
3✔
5413

3✔
5414
        var (
3✔
5415
                peerAlias    *lnwire.ShortChannelID
3✔
5416
                defaultAlias lnwire.ShortChannelID
3✔
5417
        )
3✔
5418

3✔
5419
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5420

3✔
5421
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5422
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5423
        if useAlias {
6✔
5424
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5425
                if foundAlias != defaultAlias {
6✔
5426
                        peerAlias = &foundAlias
3✔
5427
                }
3✔
5428
        }
5429

5430
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5431
                update, discovery.RemoteAlias(peerAlias),
3✔
5432
        )
3✔
5433
        select {
3✔
5434
        case err := <-errChan:
3✔
5435
                return err
3✔
5436
        case <-s.quit:
×
5437
                return ErrServerShuttingDown
×
5438
        }
5439
}
5440

5441
// SendCustomMessage sends a custom message to the peer with the specified
5442
// pubkey.
5443
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5444
        data []byte) error {
3✔
5445

3✔
5446
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5447
        if err != nil {
6✔
5448
                return err
3✔
5449
        }
3✔
5450

5451
        // We'll wait until the peer is active.
5452
        select {
3✔
5453
        case <-peer.ActiveSignal():
3✔
5454
        case <-peer.QuitSignal():
×
5455
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5456
        case <-s.quit:
×
5457
                return ErrServerShuttingDown
×
5458
        }
5459

5460
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5461
        if err != nil {
6✔
5462
                return err
3✔
5463
        }
3✔
5464

5465
        // Send the message as low-priority. For now we assume that all
5466
        // application-defined message are low priority.
5467
        return peer.SendMessageLazy(true, msg)
3✔
5468
}
5469

5470
// newSweepPkScriptGen creates closure that generates a new public key script
5471
// which should be used to sweep any funds into the on-chain wallet.
5472
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5473
// (p2wkh) output.
5474
func newSweepPkScriptGen(
5475
        wallet lnwallet.WalletController,
5476
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5477

3✔
5478
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5479
                sweepAddr, err := wallet.NewAddress(
3✔
5480
                        lnwallet.TaprootPubkey, false,
3✔
5481
                        lnwallet.DefaultAccountName,
3✔
5482
                )
3✔
5483
                if err != nil {
3✔
5484
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5485
                }
×
5486

5487
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5488
                if err != nil {
3✔
5489
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5490
                }
×
5491

5492
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5493
                        wallet, netParams, addr,
3✔
5494
                )
3✔
5495
                if err != nil {
3✔
5496
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5497
                }
×
5498

5499
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5500
                        DeliveryAddress: addr,
3✔
5501
                        InternalKey:     internalKeyDesc,
3✔
5502
                })
3✔
5503
        }
5504
}
5505

5506
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5507
// finished.
5508
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5509
        // Get a list of closed channels.
3✔
5510
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5511
        if err != nil {
3✔
5512
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5513
                return nil
×
5514
        }
×
5515

5516
        // Save the SCIDs in a map.
5517
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5518
        for _, c := range channels {
6✔
5519
                // If the channel is not pending, its FC has been finalized.
3✔
5520
                if !c.IsPending {
6✔
5521
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5522
                }
3✔
5523
        }
5524

5525
        // Double check whether the reported closed channel has indeed finished
5526
        // closing.
5527
        //
5528
        // NOTE: There are misalignments regarding when a channel's FC is
5529
        // marked as finalized. We double check the pending channels to make
5530
        // sure the returned SCIDs are indeed terminated.
5531
        //
5532
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5533
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5534
        if err != nil {
3✔
5535
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5536
                return nil
×
5537
        }
×
5538

5539
        for _, c := range pendings {
6✔
5540
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5541
                        continue
3✔
5542
                }
5543

5544
                // If the channel is still reported as pending, remove it from
5545
                // the map.
5546
                delete(closedSCIDs, c.ShortChannelID)
×
5547

×
5548
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5549
                        c.ShortChannelID)
×
5550
        }
5551

5552
        return closedSCIDs
3✔
5553
}
5554

5555
// getStartingBeat returns the current beat. This is used during the startup to
5556
// initialize blockbeat consumers.
5557
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5558
        // beat is the current blockbeat.
3✔
5559
        var beat *chainio.Beat
3✔
5560

3✔
5561
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5562
        // we will skip fetching the best block.
3✔
5563
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5564
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5565
                        "mode")
×
5566

×
5567
                return &chainio.Beat{}, nil
×
5568
        }
×
5569

5570
        // We should get a notification with the current best block immediately
5571
        // by passing a nil block.
5572
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5573
        if err != nil {
3✔
5574
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5575
        }
×
5576
        defer blockEpochs.Cancel()
3✔
5577

3✔
5578
        // We registered for the block epochs with a nil request. The notifier
3✔
5579
        // should send us the current best block immediately. So we need to
3✔
5580
        // wait for it here because we need to know the current best height.
3✔
5581
        select {
3✔
5582
        case bestBlock := <-blockEpochs.Epochs:
3✔
5583
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5584
                        bestBlock.Hash, bestBlock.Height)
3✔
5585

3✔
5586
                // Update the current blockbeat.
3✔
5587
                beat = chainio.NewBeat(*bestBlock)
3✔
5588

5589
        case <-s.quit:
×
5590
                srvrLog.Debug("LND shutting down")
×
5591
        }
5592

5593
        return beat, nil
3✔
5594
}
5595

5596
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5597
// point has an active RBF chan closer.
5598
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5599
        chanPoint wire.OutPoint) bool {
3✔
5600

3✔
5601
        pubBytes := peerPub.SerializeCompressed()
3✔
5602

3✔
5603
        s.mu.RLock()
3✔
5604
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5605
        s.mu.RUnlock()
3✔
5606
        if !ok {
3✔
5607
                return false
×
5608
        }
×
5609

5610
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5611
}
5612

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

3✔
5621
        // First, we'll attempt to look up the channel based on it's
3✔
5622
        // ChannelPoint.
3✔
5623
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5624
        if err != nil {
3✔
5625
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5626
        }
×
5627

5628
        // From the channel, we can now get the pubkey of the peer, then use
5629
        // that to eventually get the chan closer.
5630
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5631

3✔
5632
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5633
        s.mu.RLock()
3✔
5634
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5635
        s.mu.RUnlock()
3✔
5636
        if !ok {
3✔
5637
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5638
                        "not online", chanPoint)
×
5639
        }
×
5640

5641
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5642
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5643
        )
3✔
5644
        if err != nil {
3✔
5645
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5646
                        "%w", err)
×
5647
        }
×
5648

5649
        return closeUpdates, nil
3✔
5650
}
5651

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

3✔
5660
        // If the channel is present in the switch, then the request should flow
3✔
5661
        // through the switch instead.
3✔
5662
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5663
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5664
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5665
                        "invalid request", chanPoint)
×
5666
        }
×
5667

5668
        // At this point, we know that the channel isn't present in the link, so
5669
        // we'll check to see if we have an entry in the active chan closer map.
5670
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5671
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5672
        )
3✔
5673
        if err != nil {
3✔
5674
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5675
                        "ChannelPoint(%v)", chanPoint)
×
5676
        }
×
5677

5678
        return updates, nil
3✔
5679
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc