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

lightningnetwork / lnd / 16569502135

28 Jul 2025 12:50PM UTC coverage: 67.251% (+0.02%) from 67.227%
16569502135

Pull #9455

github

web-flow
Merge b3899c4fd into 2e36f9b8b
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

179 of 208 new or added lines in 6 files covered. (86.06%)

105 existing lines in 23 files now uncovered.

135676 of 201746 relevant lines covered (67.25%)

21711.59 hits per line

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

69.58
/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) {
17✔
528
        var (
17✔
529
                host string
17✔
530
                port int
17✔
531
        )
17✔
532

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

550
        // Handle the Onion address type.
551
        if tor.IsOnionHost(host) {
19✔
552
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
2✔
553
        }
2✔
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) {
25✔
558
                hostPort := net.JoinHostPort(host, strconv.Itoa(port))
10✔
559
                return netCfg.ResolveTCPAddr("tcp", hostPort)
10✔
560
        }
10✔
561

562
        // Attempt to parse as a DNS address.
563
        addr, err := lnwire.NewDNSAddr(host, port)
8✔
564
        if err != nil {
8✔
NEW
565
                return nil, err
×
NEW
566
        }
×
567

568
        // Validate DNS address accordin to BOLT-07 specifications.
569
        if err := addr.Validate(); err != nil {
11✔
570
                return nil, err
3✔
571
        }
3✔
572

573
        // Check if that DNS address resolve to any TCP addresses.
574
        if _, err = netCfg.ResolveTCPAddr("tcp", addr.String()); err != nil {
5✔
NEW
575
                return nil, err
×
NEW
576
        }
×
577

578
        return addr, nil
5✔
579
}
580

581
// isIP checks if the provided host is an IP address (IPv4 or IPv6).
582
func isIP(host string) bool {
15✔
583
        // Try parsing the host as an IP address.
15✔
584
        ip := net.ParseIP(host)
15✔
585
        return ip != nil
15✔
586
}
15✔
587

588
// parseDNSAddr parses a raw DNS addressand assert it of type DNSAddr.
589
func parseDNSAddr(rawAddress string, netCfg tor.Net) (*lnwire.DNSAddr, error) {
3✔
590
        addr, err := parseAddr(rawAddress, netCfg)
3✔
591
        if err != nil {
3✔
NEW
592
                return nil, err
×
NEW
593
        }
×
594

595
        // Check if the parsed address is a DNS address.
596
        dnsAddr, ok := addr.(*lnwire.DNSAddr)
3✔
597
        if !ok {
3✔
NEW
598
                return nil, fmt.Errorf("expected DNS hostname address, got "+
×
NEW
599
                        "%T", addr)
×
NEW
600
        }
×
601

602
        return dnsAddr, nil
3✔
603
}
604

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

3✔
610
        return func(a net.Addr) (net.Conn, error) {
6✔
611
                lnAddr := a.(*lnwire.NetAddress)
3✔
612
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
613
        }
3✔
614
}
615

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

3✔
629
        var (
3✔
630
                err         error
3✔
631
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
632

3✔
633
                // We just derived the full descriptor, so we know the public
3✔
634
                // key is set on it.
3✔
635
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
636
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
637
                )
3✔
638
        )
3✔
639

3✔
640
        var serializedPubKey [33]byte
3✔
641
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
642

3✔
643
        netParams := cfg.ActiveNetParams.Params
3✔
644

3✔
645
        // Initialize the sphinx router.
3✔
646
        replayLog := htlcswitch.NewDecayedLog(
3✔
647
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
648
        )
3✔
649
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
650

3✔
651
        writeBufferPool := pool.NewWriteBuffer(
3✔
652
                pool.DefaultWriteBufferGCInterval,
3✔
653
                pool.DefaultWriteBufferExpiryInterval,
3✔
654
        )
3✔
655

3✔
656
        writePool := pool.NewWrite(
3✔
657
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
658
        )
3✔
659

3✔
660
        readBufferPool := pool.NewReadBuffer(
3✔
661
                pool.DefaultReadBufferGCInterval,
3✔
662
                pool.DefaultReadBufferExpiryInterval,
3✔
663
        )
3✔
664

3✔
665
        readPool := pool.NewRead(
3✔
666
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
667
        )
3✔
668

3✔
669
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
670
        // controller, then we'll exit as this is incompatible.
3✔
671
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
672
                implCfg.AuxFundingController.IsNone() {
3✔
673

×
674
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
675
                        "aux controllers")
×
676
        }
×
677

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

701
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
702
        registryConfig := invoices.RegistryConfig{
3✔
703
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
704
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
705
                Clock:                       clock.NewDefaultClock(),
3✔
706
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
707
                AcceptAMP:                   cfg.AcceptAMP,
3✔
708
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
709
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
710
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
711
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
712
        }
3✔
713

3✔
714
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
715

3✔
716
        s := &server{
3✔
717
                cfg:            cfg,
3✔
718
                implCfg:        implCfg,
3✔
719
                graphDB:        dbs.GraphDB,
3✔
720
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
721
                addrSource:     addrSource,
3✔
722
                miscDB:         dbs.ChanStateDB,
3✔
723
                invoicesDB:     dbs.InvoiceDB,
3✔
724
                cc:             cc,
3✔
725
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
726
                writePool:      writePool,
3✔
727
                readPool:       readPool,
3✔
728
                chansToRestore: chansToRestore,
3✔
729

3✔
730
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
731
                        cc.ChainNotifier,
3✔
732
                ),
3✔
733
                channelNotifier: channelnotifier.New(
3✔
734
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
735
                ),
3✔
736

3✔
737
                identityECDH:   nodeKeyECDH,
3✔
738
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
739
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
740

3✔
741
                listenAddrs: listenAddrs,
3✔
742

3✔
743
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
744
                // schedule
3✔
745
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
746

3✔
747
                torController: torController,
3✔
748

3✔
749
                persistentPeers:         make(map[string]bool),
3✔
750
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
751
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
752
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
753
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
754
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
755
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
756
                scheduledPeerConnection: make(map[string]func()),
3✔
757
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
758

3✔
759
                peersByPub:                make(map[string]*peer.Brontide),
3✔
760
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
761
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
762
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
763
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
764

3✔
765
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
766

3✔
767
                customMessageServer: subscribe.NewServer(),
3✔
768

3✔
769
                tlsManager: tlsManager,
3✔
770

3✔
771
                featureMgr: featureMgr,
3✔
772
                quit:       make(chan struct{}),
3✔
773
        }
3✔
774

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

786
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
787
        if err != nil {
3✔
788
                return nil, err
×
789
        }
×
790

791
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
792
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
793
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
794
        )
3✔
795
        s.invoices = invoices.NewRegistry(
3✔
796
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
797
        )
3✔
798

3✔
799
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
800

3✔
801
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
802
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
803

3✔
804
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
805
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
806
                if err != nil {
3✔
807
                        return err
×
808
                }
×
809

810
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
811

3✔
812
                return nil
3✔
813
        }
814

815
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
816
        if err != nil {
3✔
817
                return nil, err
×
818
        }
×
819

820
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
821
                DB:                   dbs.ChanStateDB,
3✔
822
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
823
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
824
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
825
                LocalChannelClose: func(pubKey []byte,
3✔
826
                        request *htlcswitch.ChanClose) {
6✔
827

3✔
828
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
829
                        if err != nil {
3✔
830
                                srvrLog.Errorf("unable to close channel, peer"+
×
831
                                        " with %v id can't be found: %v",
×
832
                                        pubKey, err,
×
833
                                )
×
834
                                return
×
835
                        }
×
836

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

872
        s.witnessBeacon = newPreimageBeacon(
3✔
873
                dbs.ChanStateDB.NewWitnessCache(),
3✔
874
                s.interceptableSwitch.ForwardPacket,
3✔
875
        )
3✔
876

3✔
877
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
878
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
879
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
880
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
881
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
882
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
883
                MessageSigner:            s.nodeSigner,
3✔
884
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
885
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
886
                DB:                       s.chanStateDB,
3✔
887
                Graph:                    dbs.GraphDB,
3✔
888
        }
3✔
889

3✔
890
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
891
        if err != nil {
3✔
892
                return nil, err
×
893
        }
×
894
        s.chanStatusMgr = chanStatusMgr
3✔
895

3✔
896
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
897
        // port forwarding for users behind a NAT.
3✔
898
        if cfg.NAT {
3✔
899
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
900

×
901
                discoveryTimeout := time.Duration(10 * time.Second)
×
902

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

×
917
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
918
                                "enabled device")
×
919

×
920
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
921
                        if err != nil {
×
922
                                err := fmt.Errorf("unable to discover a "+
×
923
                                        "NAT-PMP enabled device on the local "+
×
924
                                        "network: %v", err)
×
925
                                srvrLog.Error(err)
×
926
                                return nil, err
×
927
                        }
×
928

929
                        s.natTraversal = pmp
×
930
                }
931
        }
932

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

×
948
                        listenPorts = append(listenPorts, uint16(port))
×
949
                }
×
950

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

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

974
        // Determine the length of network addresses taking into the
975
        // consideration the external DNS address if exists.
976
        addrsLen := len(externalIPs)
3✔
977
        if cfg.ExternalDNSAddress != nil {
6✔
978
                addrsLen++
3✔
979
        }
3✔
980

981
        selfAddrs := make([]net.Addr, 0, addrsLen)
3✔
982
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
983

3✔
984
        if cfg.ExternalDNSAddress != nil {
6✔
985
                selfAddrs = append(selfAddrs, cfg.ExternalDNSAddress)
3✔
986
        }
3✔
987

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

999
        // If no alias is provided, default to first 10 characters of public
1000
        // key.
1001
        alias := cfg.Alias
3✔
1002
        if alias == "" {
6✔
1003
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
1004
        }
3✔
1005
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
1006
        if err != nil {
3✔
1007
                return nil, err
×
1008
        }
×
1009

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

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

1029
        // If the above cases are not matched, then we have an unhandled non
1030
        // nil error.
1031
        default:
×
1032
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
1033
        }
1034

1035
        selfNode := &models.LightningNode{
3✔
1036
                HaveNodeAnnouncement: true,
3✔
1037
                LastUpdate:           nodeLastUpdate,
3✔
1038
                Addresses:            selfAddrs,
3✔
1039
                Alias:                nodeAlias.String(),
3✔
1040
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
1041
                Color:                color,
3✔
1042
        }
3✔
1043
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1044

3✔
1045
        // Based on the disk representation of the node announcement generated
3✔
1046
        // above, we'll generate a node announcement that can go out on the
3✔
1047
        // network so we can properly sign it.
3✔
1048
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
1049
        if err != nil {
3✔
1050
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
1051
        }
×
1052

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

1070
        // Finally, we'll update the representation on disk, and update our
1071
        // cached in-memory version as well.
1072
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
1073
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1074
        }
×
1075
        s.currentNodeAnn = nodeAnn
3✔
1076

3✔
1077
        // The router will get access to the payment ID sequencer, such that it
3✔
1078
        // can generate unique payment IDs.
3✔
1079
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1080
        if err != nil {
3✔
1081
                return nil, err
×
1082
        }
×
1083

1084
        // Instantiate mission control with config from the sub server.
1085
        //
1086
        // TODO(joostjager): When we are further in the process of moving to sub
1087
        // servers, the mission control instance itself can be moved there too.
1088
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1089

3✔
1090
        // We only initialize a probability estimator if there's no custom one.
3✔
1091
        var estimator routing.Estimator
3✔
1092
        if cfg.Estimator != nil {
3✔
1093
                estimator = cfg.Estimator
×
1094
        } else {
3✔
1095
                switch routingConfig.ProbabilityEstimatorType {
3✔
1096
                case routing.AprioriEstimatorName:
3✔
1097
                        aCfg := routingConfig.AprioriConfig
3✔
1098
                        aprioriConfig := routing.AprioriConfig{
3✔
1099
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1100
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1101
                                AprioriWeight:         aCfg.Weight,
3✔
1102
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1103
                        }
3✔
1104

3✔
1105
                        estimator, err = routing.NewAprioriEstimator(
3✔
1106
                                aprioriConfig,
3✔
1107
                        )
3✔
1108
                        if err != nil {
3✔
1109
                                return nil, err
×
1110
                        }
×
1111

1112
                case routing.BimodalEstimatorName:
×
1113
                        bCfg := routingConfig.BimodalConfig
×
1114
                        bimodalConfig := routing.BimodalConfig{
×
1115
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1116
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1117
                                        bCfg.Scale,
×
1118
                                ),
×
1119
                                BimodalDecayTime: bCfg.DecayTime,
×
1120
                        }
×
1121

×
1122
                        estimator, err = routing.NewBimodalEstimator(
×
1123
                                bimodalConfig,
×
1124
                        )
×
1125
                        if err != nil {
×
1126
                                return nil, err
×
1127
                        }
×
1128

1129
                default:
×
1130
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1131
                                routingConfig.ProbabilityEstimatorType)
×
1132
                }
1133
        }
1134

1135
        mcCfg := &routing.MissionControlConfig{
3✔
1136
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1137
                Estimator:               estimator,
3✔
1138
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1139
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1140
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1141
        }
3✔
1142

3✔
1143
        s.missionController, err = routing.NewMissionController(
3✔
1144
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1145
        )
3✔
1146
        if err != nil {
3✔
1147
                return nil, fmt.Errorf("can't create mission control "+
×
1148
                        "manager: %w", err)
×
1149
        }
×
1150
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1151
                routing.DefaultMissionControlNamespace,
3✔
1152
        )
3✔
1153
        if err != nil {
3✔
1154
                return nil, fmt.Errorf("can't create mission control in the "+
×
1155
                        "default namespace: %w", err)
×
1156
        }
×
1157

1158
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1159
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1160
                int64(routingConfig.AttemptCost),
3✔
1161
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1162
                routingConfig.MinRouteProbability)
3✔
1163

3✔
1164
        pathFindingConfig := routing.PathFindingConfig{
3✔
1165
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1166
                        routingConfig.AttemptCost,
3✔
1167
                ),
3✔
1168
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1169
                MinProbability: routingConfig.MinRouteProbability,
3✔
1170
        }
3✔
1171

3✔
1172
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1173
        if err != nil {
3✔
1174
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1175
        }
×
1176
        paymentSessionSource := &routing.SessionSource{
3✔
1177
                GraphSessionFactory: dbs.GraphDB,
3✔
1178
                SourceNode:          sourceNode,
3✔
1179
                MissionControl:      s.defaultMC,
3✔
1180
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1181
                PathFindingConfig:   pathFindingConfig,
3✔
1182
        }
3✔
1183

3✔
1184
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1185

3✔
1186
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1187

3✔
1188
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1189
                cfg.Routing.StrictZombiePruning
3✔
1190

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

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

1228
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1229
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1230
        if err != nil {
3✔
1231
                return nil, err
×
1232
        }
×
1233
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1234
        if err != nil {
3✔
1235
                return nil, err
×
1236
        }
×
1237

1238
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1239

3✔
1240
        s.authGossiper = discovery.New(discovery.Config{
3✔
1241
                Graph:                 s.graphBuilder,
3✔
1242
                ChainIO:               s.cc.ChainIO,
3✔
1243
                Notifier:              s.cc.ChainNotifier,
3✔
1244
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1245
                Broadcast:             s.BroadcastMessage,
3✔
1246
                ChanSeries:            chanSeries,
3✔
1247
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1248
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1249
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1250
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1251
                        error) {
3✔
1252

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

1284
        accessCfg := &accessManConfig{
3✔
1285
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1286
                        error) {
6✔
1287

3✔
1288
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1289
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1290
                                genesisHash[:],
3✔
1291
                        )
3✔
1292
                },
3✔
1293
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1294
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1295
        }
1296

1297
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1298
        if err != nil {
3✔
1299
                return nil, err
×
1300
        }
×
1301

1302
        s.peerAccessMan = peerAccessMan
3✔
1303

3✔
1304
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1305
        //nolint:ll
3✔
1306
        s.localChanMgr = &localchans.Manager{
3✔
1307
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1308
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1309
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1310
                        cb func(*models.ChannelEdgeInfo,
3✔
1311
                                *models.ChannelEdgePolicy) error,
3✔
1312
                        reset func()) error {
6✔
1313

3✔
1314
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1315
                                func(c *models.ChannelEdgeInfo,
3✔
1316
                                        e *models.ChannelEdgePolicy,
3✔
1317
                                        _ *models.ChannelEdgePolicy) error {
6✔
1318

3✔
1319
                                        // NOTE: The invoked callback here may
3✔
1320
                                        // receive a nil channel policy.
3✔
1321
                                        return cb(c, e)
3✔
1322
                                }, reset,
3✔
1323
                        )
1324
                },
1325
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1326
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1327
                FetchChannel:              s.chanStateDB.FetchChannel,
1328
                AddEdge: func(ctx context.Context,
1329
                        edge *models.ChannelEdgeInfo) error {
×
1330

×
1331
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1332
                },
×
1333
        }
1334

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

1343
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1344
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1345
        )
3✔
1346
        if err != nil {
3✔
1347
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1348
                return nil, err
×
1349
        }
×
1350

1351
        aggregator := sweep.NewBudgetAggregator(
3✔
1352
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1353
                s.implCfg.AuxSweeper,
3✔
1354
        )
3✔
1355

3✔
1356
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1357
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1358
                Wallet:     cc.Wallet,
3✔
1359
                Estimator:  cc.FeeEstimator,
3✔
1360
                Notifier:   cc.ChainNotifier,
3✔
1361
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1362
        })
3✔
1363

3✔
1364
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1365
                FeeEstimator: cc.FeeEstimator,
3✔
1366
                GenSweepScript: newSweepPkScriptGen(
3✔
1367
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1368
                ),
3✔
1369
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1370
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1371
                Mempool:              cc.MempoolNotifier,
3✔
1372
                Notifier:             cc.ChainNotifier,
3✔
1373
                Store:                sweeperStore,
3✔
1374
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1375
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1376
                Aggregator:           aggregator,
3✔
1377
                Publisher:            s.txPublisher,
3✔
1378
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1379
        })
3✔
1380

3✔
1381
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1382
                ChainIO:             cc.ChainIO,
3✔
1383
                ConfDepth:           1,
3✔
1384
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1385
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1386
                Notifier:            cc.ChainNotifier,
3✔
1387
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1388
                Store:               utxnStore,
3✔
1389
                SweepInput:          s.sweeper.SweepInput,
3✔
1390
                Budget:              s.cfg.Sweeper.Budget,
3✔
1391
        })
3✔
1392

3✔
1393
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1394
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1395
                closureType contractcourt.ChannelCloseType) {
6✔
1396
                // TODO(conner): Properly respect the update and error channels
3✔
1397
                // returned by CloseLink.
3✔
1398

3✔
1399
                // Instruct the switch to close the channel.  Provide no close out
3✔
1400
                // delivery script or target fee per kw because user input is not
3✔
1401
                // available when the remote peer closes the channel.
3✔
1402
                s.htlcSwitch.CloseLink(
3✔
1403
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1404
                )
3✔
1405
        }
3✔
1406

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

3✔
1411
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1412
                &contractcourt.BreachConfig{
3✔
1413
                        CloseLink: closeLink,
3✔
1414
                        DB:        s.chanStateDB,
3✔
1415
                        Estimator: s.cc.FeeEstimator,
3✔
1416
                        GenSweepScript: newSweepPkScriptGen(
3✔
1417
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1418
                        ),
3✔
1419
                        Notifier:           cc.ChainNotifier,
3✔
1420
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1421
                        ContractBreaches:   contractBreaches,
3✔
1422
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1423
                        Store: contractcourt.NewRetributionStore(
3✔
1424
                                dbs.ChanStateDB,
3✔
1425
                        ),
3✔
1426
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1427
                },
3✔
1428
        )
3✔
1429

3✔
1430
        //nolint:ll
3✔
1431
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1432
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1433
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1434
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1435
                NewSweepAddr: func() ([]byte, error) {
3✔
1436
                        addr, err := newSweepPkScriptGen(
×
1437
                                cc.Wallet, netParams,
×
1438
                        )().Unpack()
×
1439
                        if err != nil {
×
1440
                                return nil, err
×
1441
                        }
×
1442

1443
                        return addr.DeliveryAddress, nil
×
1444
                },
1445
                PublishTx: cc.Wallet.PublishTransaction,
1446
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1447
                        for _, msg := range msgs {
6✔
1448
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1449
                                if err != nil {
3✔
1450
                                        return err
×
1451
                                }
×
1452
                        }
1453
                        return nil
3✔
1454
                },
1455
                IncubateOutputs: func(chanPoint wire.OutPoint,
1456
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1457
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1458
                        broadcastHeight uint32,
1459
                        deadlineHeight fn.Option[int32]) error {
3✔
1460

3✔
1461
                        return s.utxoNursery.IncubateOutputs(
3✔
1462
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1463
                                broadcastHeight, deadlineHeight,
3✔
1464
                        )
3✔
1465
                },
3✔
1466
                PreimageDB:   s.witnessBeacon,
1467
                Notifier:     cc.ChainNotifier,
1468
                Mempool:      cc.MempoolNotifier,
1469
                Signer:       cc.Wallet.Cfg.Signer,
1470
                FeeEstimator: cc.FeeEstimator,
1471
                ChainIO:      cc.ChainIO,
1472
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1473
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1474
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1475
                        return nil
3✔
1476
                },
3✔
1477
                IsOurAddress: cc.Wallet.IsOurAddress,
1478
                ContractBreach: func(chanPoint wire.OutPoint,
1479
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1480

3✔
1481
                        // processACK will handle the BreachArbitrator ACKing
3✔
1482
                        // the event.
3✔
1483
                        finalErr := make(chan error, 1)
3✔
1484
                        processACK := func(brarErr error) {
6✔
1485
                                if brarErr != nil {
3✔
1486
                                        finalErr <- brarErr
×
1487
                                        return
×
1488
                                }
×
1489

1490
                                // If the BreachArbitrator successfully handled
1491
                                // the event, we can signal that the handoff
1492
                                // was successful.
1493
                                finalErr <- nil
3✔
1494
                        }
1495

1496
                        event := &contractcourt.ContractBreachEvent{
3✔
1497
                                ChanPoint:         chanPoint,
3✔
1498
                                ProcessACK:        processACK,
3✔
1499
                                BreachRetribution: breachRet,
3✔
1500
                        }
3✔
1501

3✔
1502
                        // Send the contract breach event to the
3✔
1503
                        // BreachArbitrator.
3✔
1504
                        select {
3✔
1505
                        case contractBreaches <- event:
3✔
1506
                        case <-s.quit:
×
1507
                                return ErrServerShuttingDown
×
1508
                        }
1509

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

1535
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1536
                QueryIncomingCircuit: func(
1537
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1538

3✔
1539
                        // Get the circuit map.
3✔
1540
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1541

3✔
1542
                        // Lookup the outgoing circuit.
3✔
1543
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1544
                        if pc == nil {
5✔
1545
                                return nil
2✔
1546
                        }
2✔
1547

1548
                        return &pc.Incoming
3✔
1549
                },
1550
                AuxLeafStore: implCfg.AuxLeafStore,
1551
                AuxSigner:    implCfg.AuxSigner,
1552
                AuxResolver:  implCfg.AuxContractResolver,
1553
        }, dbs.ChanStateDB)
1554

1555
        // Select the configuration and funding parameters for Bitcoin.
1556
        chainCfg := cfg.Bitcoin
3✔
1557
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1558
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1559

3✔
1560
        var chanIDSeed [32]byte
3✔
1561
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1562
                return nil, err
×
1563
        }
×
1564

1565
        // Wrap the DeleteChannelEdges method so that the funding manager can
1566
        // use it without depending on several layers of indirection.
1567
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1568
                *models.ChannelEdgePolicy, error) {
6✔
1569

3✔
1570
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1571
                        scid.ToUint64(),
3✔
1572
                )
3✔
1573
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1574
                        // This is unlikely but there is a slim chance of this
×
1575
                        // being hit if lnd was killed via SIGKILL and the
×
1576
                        // funding manager was stepping through the delete
×
1577
                        // alias edge logic.
×
1578
                        return nil, nil
×
1579
                } else if err != nil {
3✔
1580
                        return nil, err
×
1581
                }
×
1582

1583
                // Grab our key to find our policy.
1584
                var ourKey [33]byte
3✔
1585
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1586

3✔
1587
                var ourPolicy *models.ChannelEdgePolicy
3✔
1588
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1589
                        ourPolicy = e1
3✔
1590
                } else {
6✔
1591
                        ourPolicy = e2
3✔
1592
                }
3✔
1593

1594
                if ourPolicy == nil {
3✔
1595
                        // Something is wrong, so return an error.
×
1596
                        return nil, fmt.Errorf("we don't have an edge")
×
1597
                }
×
1598

1599
                err = s.graphDB.DeleteChannelEdges(
3✔
1600
                        false, false, scid.ToUint64(),
3✔
1601
                )
3✔
1602
                return ourPolicy, err
3✔
1603
        }
1604

1605
        // For the reservationTimeout and the zombieSweeperInterval different
1606
        // values are set in case we are in a dev environment so enhance test
1607
        // capacilities.
1608
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1609
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1610

3✔
1611
        // Get the development config for funding manager. If we are not in
3✔
1612
        // development mode, this would be nil.
3✔
1613
        var devCfg *funding.DevConfig
3✔
1614
        if lncfg.IsDevBuild() {
6✔
1615
                devCfg = &funding.DevConfig{
3✔
1616
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1617
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1618
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1619
                }
3✔
1620

3✔
1621
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1622
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1623

3✔
1624
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1625
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1626
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1627
        }
3✔
1628

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

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

3✔
1667
                        // In case the user has explicitly specified
3✔
1668
                        // a default value for the number of
3✔
1669
                        // confirmations, we use it.
3✔
1670
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1671
                        if defaultConf != 0 {
6✔
1672
                                return defaultConf
3✔
1673
                        }
3✔
1674

1675
                        minConf := uint64(3)
×
1676
                        maxConf := uint64(6)
×
1677

×
1678
                        // If this is a wumbo channel, then we'll require the
×
1679
                        // max amount of confirmations.
×
1680
                        if chanAmt > MaxFundingAmount {
×
1681
                                return uint16(maxConf)
×
1682
                        }
×
1683

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

3✔
1706
                        // In case the user has explicitly specified
3✔
1707
                        // a default value for the remote delay, we
3✔
1708
                        // use it.
3✔
1709
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1710
                        if defaultDelay > 0 {
6✔
1711
                                return defaultDelay
3✔
1712
                        }
3✔
1713

1714
                        // If this is a wumbo channel, then we'll require the
1715
                        // max value.
1716
                        if chanAmt > MaxFundingAmount {
×
1717
                                return maxRemoteDelay
×
1718
                        }
×
1719

1720
                        // If not we scale according to channel size.
1721
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1722
                                chanAmt / MaxFundingAmount)
×
1723
                        if delay < minRemoteDelay {
×
1724
                                delay = minRemoteDelay
×
1725
                        }
×
1726
                        if delay > maxRemoteDelay {
×
1727
                                delay = maxRemoteDelay
×
1728
                        }
×
1729
                        return delay
×
1730
                },
1731
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1732
                        peerKey *btcec.PublicKey) error {
3✔
1733

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

3✔
1747
                        // With that taken care of, we'll send this channel to
3✔
1748
                        // the chain arb so it can react to on-chain events.
3✔
1749
                        return s.chainArb.WatchNewChannel(channel)
3✔
1750
                },
1751
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1752
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1753
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1754
                },
3✔
1755
                RequiredRemoteChanReserve: func(chanAmt,
1756
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1757

3✔
1758
                        // By default, we'll require the remote peer to maintain
3✔
1759
                        // at least 1% of the total channel capacity at all
3✔
1760
                        // times. If this value ends up dipping below the dust
3✔
1761
                        // limit, then we'll use the dust limit itself as the
3✔
1762
                        // reserve as required by BOLT #2.
3✔
1763
                        reserve := chanAmt / 100
3✔
1764
                        if reserve < dustLimit {
6✔
1765
                                reserve = dustLimit
3✔
1766
                        }
3✔
1767

1768
                        return reserve
3✔
1769
                },
1770
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1771
                        // By default, we'll allow the remote peer to fully
3✔
1772
                        // utilize the full bandwidth of the channel, minus our
3✔
1773
                        // required reserve.
3✔
1774
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1775
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1776
                },
3✔
1777
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1778
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1779
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1780
                        }
3✔
1781

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

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

1833
        // Assemble a peer notifier which will provide clients with subscriptions
1834
        // to peer online and offline events.
1835
        s.peerNotifier = peernotifier.New()
3✔
1836

3✔
1837
        // Create a channel event store which monitors all open channels.
3✔
1838
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1839
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1840
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1841
                },
3✔
1842
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1843
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1844
                },
3✔
1845
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1846
                Clock:           clock.NewDefaultClock(),
1847
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1848
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1849
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1850
        })
1851

1852
        if cfg.WtClient.Active {
6✔
1853
                policy := wtpolicy.DefaultPolicy()
3✔
1854
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1855

3✔
1856
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1857
                // protocol operations on sat/kw.
3✔
1858
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1859
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1860
                )
3✔
1861

3✔
1862
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1863

3✔
1864
                if err := policy.Validate(); err != nil {
3✔
1865
                        return nil, err
×
1866
                }
×
1867

1868
                // authDial is the wrapper around the btrontide.Dial for the
1869
                // watchtower.
1870
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1871
                        netAddr *lnwire.NetAddress,
3✔
1872
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1873

3✔
1874
                        return brontide.Dial(
3✔
1875
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1876
                        )
3✔
1877
                }
3✔
1878

1879
                // buildBreachRetribution is a call-back that can be used to
1880
                // query the BreachRetribution info and channel type given a
1881
                // channel ID and commitment height.
1882
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1883
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1884
                        channeldb.ChannelType, error) {
6✔
1885

3✔
1886
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1887
                                nil, chanID,
3✔
1888
                        )
3✔
1889
                        if err != nil {
3✔
1890
                                return nil, 0, err
×
1891
                        }
×
1892

1893
                        br, err := lnwallet.NewBreachRetribution(
3✔
1894
                                channel, commitHeight, 0, nil,
3✔
1895
                                implCfg.AuxLeafStore,
3✔
1896
                                implCfg.AuxContractResolver,
3✔
1897
                        )
3✔
1898
                        if err != nil {
3✔
1899
                                return nil, 0, err
×
1900
                        }
×
1901

1902
                        return br, channel.ChanType, nil
3✔
1903
                }
1904

1905
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1906

3✔
1907
                // Copy the policy for legacy channels and set the blob flag
3✔
1908
                // signalling support for anchor channels.
3✔
1909
                anchorPolicy := policy
3✔
1910
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1911

3✔
1912
                // Copy the policy for legacy channels and set the blob flag
3✔
1913
                // signalling support for taproot channels.
3✔
1914
                taprootPolicy := policy
3✔
1915
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1916
                        blob.FlagTaprootChannel,
3✔
1917
                )
3✔
1918

3✔
1919
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1920
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1921
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1922
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1923
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1924
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1925
                                error) {
6✔
1926

3✔
1927
                                return s.channelNotifier.
3✔
1928
                                        SubscribeChannelEvents()
3✔
1929
                        },
3✔
1930
                        Signer: cc.Wallet.Cfg.Signer,
1931
                        NewAddress: func() ([]byte, error) {
3✔
1932
                                addr, err := newSweepPkScriptGen(
3✔
1933
                                        cc.Wallet, netParams,
3✔
1934
                                )().Unpack()
3✔
1935
                                if err != nil {
3✔
1936
                                        return nil, err
×
1937
                                }
×
1938

1939
                                return addr.DeliveryAddress, nil
3✔
1940
                        },
1941
                        SecretKeyRing:      s.cc.KeyRing,
1942
                        Dial:               cfg.net.Dial,
1943
                        AuthDial:           authDial,
1944
                        DB:                 dbs.TowerClientDB,
1945
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1946
                        MinBackoff:         10 * time.Second,
1947
                        MaxBackoff:         5 * time.Minute,
1948
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1949
                }, policy, anchorPolicy, taprootPolicy)
1950
                if err != nil {
3✔
1951
                        return nil, err
×
1952
                }
×
1953
        }
1954

1955
        if len(cfg.ExternalHosts) != 0 {
3✔
1956
                advertisedIPs := make(map[string]struct{})
×
1957
                for _, addr := range s.currentNodeAnn.Addresses {
×
1958
                        advertisedIPs[addr.String()] = struct{}{}
×
1959
                }
×
1960

1961
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1962
                        Hosts:         cfg.ExternalHosts,
×
1963
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1964
                        LookupHost: func(host string) (net.Addr, error) {
×
1965
                                return lncfg.ParseAddressString(
×
1966
                                        host, strconv.Itoa(defaultPeerPort),
×
1967
                                        cfg.net.ResolveTCPAddr,
×
1968
                                )
×
1969
                        },
×
1970
                        AdvertisedIPs: advertisedIPs,
1971
                        AnnounceNewIPs: netann.IPAnnouncer(
1972
                                func(modifier ...netann.NodeAnnModifier) (
1973
                                        lnwire.NodeAnnouncement, error) {
×
1974

×
1975
                                        return s.genNodeAnnouncement(
×
1976
                                                nil, modifier...,
×
1977
                                        )
×
1978
                                }),
×
1979
                })
1980
        }
1981

1982
        // Create liveness monitor.
1983
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1984

3✔
1985
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1986
        for i, listenAddr := range listenAddrs {
6✔
1987
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1988
                // doesn't need to call the general lndResolveTCP function
3✔
1989
                // since we are resolving a local address.
3✔
1990

3✔
1991
                // RESOLVE: We are actually partially accepting inbound
3✔
1992
                // connection requests when we call NewListener.
3✔
1993
                listeners[i], err = brontide.NewListener(
3✔
1994
                        nodeKeyECDH, listenAddr.String(),
3✔
1995
                        // TODO(yy): remove this check and unify the inbound
3✔
1996
                        // connection check inside `InboundPeerConnected`.
3✔
1997
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1998
                )
3✔
1999
                if err != nil {
3✔
2000
                        return nil, err
×
2001
                }
×
2002
        }
2003

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

3✔
2022
        // Finally, register the subsystems in blockbeat.
3✔
2023
        s.registerBlockConsumers()
3✔
2024

3✔
2025
        return s, nil
3✔
2026
}
2027

2028
// UpdateRoutingConfig is a callback function to update the routing config
2029
// values in the main cfg.
2030
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
2031
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
2032

3✔
2033
        switch c := cfg.Estimator.Config().(type) {
3✔
2034
        case routing.AprioriConfig:
3✔
2035
                routerCfg.ProbabilityEstimatorType =
3✔
2036
                        routing.AprioriEstimatorName
3✔
2037

3✔
2038
                targetCfg := routerCfg.AprioriConfig
3✔
2039
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
2040
                targetCfg.Weight = c.AprioriWeight
3✔
2041
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
2042
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
2043

2044
        case routing.BimodalConfig:
3✔
2045
                routerCfg.ProbabilityEstimatorType =
3✔
2046
                        routing.BimodalEstimatorName
3✔
2047

3✔
2048
                targetCfg := routerCfg.BimodalConfig
3✔
2049
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
2050
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
2051
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
2052
        }
2053

2054
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2055
}
2056

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

2076
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2077
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2078
// may differ from what is on disk.
2079
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2080
        error) {
3✔
2081

3✔
2082
        data, err := u.DataToSign()
3✔
2083
        if err != nil {
3✔
2084
                return nil, err
×
2085
        }
×
2086

2087
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2088
}
2089

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

3✔
2103
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2104
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2105
                srvrLog.Info("Disabling chain backend checks for " +
×
2106
                        "nochainbackend mode")
×
2107

×
2108
                chainBackendAttempts = 0
×
2109
        }
×
2110

2111
        chainHealthCheck := healthcheck.NewObservation(
3✔
2112
                "chain backend",
3✔
2113
                cc.HealthCheck,
3✔
2114
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2115
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2116
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2117
                chainBackendAttempts,
3✔
2118
        )
3✔
2119

3✔
2120
        diskCheck := healthcheck.NewObservation(
3✔
2121
                "disk space",
3✔
2122
                func() error {
3✔
2123
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2124
                                cfg.LndDir,
×
2125
                        )
×
2126
                        if err != nil {
×
2127
                                return err
×
2128
                        }
×
2129

2130
                        // If we have more free space than we require,
2131
                        // we return a nil error.
2132
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2133
                                return nil
×
2134
                        }
×
2135

2136
                        return fmt.Errorf("require: %v free space, got: %v",
×
2137
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2138
                                free)
×
2139
                },
2140
                cfg.HealthChecks.DiskCheck.Interval,
2141
                cfg.HealthChecks.DiskCheck.Timeout,
2142
                cfg.HealthChecks.DiskCheck.Backoff,
2143
                cfg.HealthChecks.DiskCheck.Attempts,
2144
        )
2145

2146
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2147
                "tls",
3✔
2148
                func() error {
3✔
2149
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2150
                                s.cc.KeyRing,
×
2151
                        )
×
2152
                        if err != nil {
×
2153
                                return err
×
2154
                        }
×
2155
                        if expired {
×
2156
                                return fmt.Errorf("TLS certificate is "+
×
2157
                                        "expired as of %v", expTime)
×
2158
                        }
×
2159

2160
                        // If the certificate is not outdated, no error needs
2161
                        // to be returned
2162
                        return nil
×
2163
                },
2164
                cfg.HealthChecks.TLSCheck.Interval,
2165
                cfg.HealthChecks.TLSCheck.Timeout,
2166
                cfg.HealthChecks.TLSCheck.Backoff,
2167
                cfg.HealthChecks.TLSCheck.Attempts,
2168
        )
2169

2170
        checks := []*healthcheck.Observation{
3✔
2171
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2172
        }
3✔
2173

3✔
2174
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2175
        if s.torController != nil {
3✔
2176
                torConnectionCheck := healthcheck.NewObservation(
×
2177
                        "tor connection",
×
2178
                        func() error {
×
2179
                                return healthcheck.CheckTorServiceStatus(
×
2180
                                        s.torController,
×
2181
                                        func() error {
×
2182
                                                return s.createNewHiddenService(
×
2183
                                                        context.TODO(),
×
2184
                                                )
×
2185
                                        },
×
2186
                                )
2187
                        },
2188
                        cfg.HealthChecks.TorConnection.Interval,
2189
                        cfg.HealthChecks.TorConnection.Timeout,
2190
                        cfg.HealthChecks.TorConnection.Backoff,
2191
                        cfg.HealthChecks.TorConnection.Attempts,
2192
                )
2193
                checks = append(checks, torConnectionCheck)
×
2194
        }
2195

2196
        // If remote signing is enabled, add the healthcheck for the remote
2197
        // signing RPC interface.
2198
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2199
                // Because we have two cascading timeouts here, we need to add
3✔
2200
                // some slack to the "outer" one of them in case the "inner"
3✔
2201
                // returns exactly on time.
3✔
2202
                overhead := time.Millisecond * 10
3✔
2203

3✔
2204
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2205
                        "remote signer connection",
3✔
2206
                        rpcwallet.HealthCheck(
3✔
2207
                                s.cfg.RemoteSigner,
3✔
2208

3✔
2209
                                // For the health check we might to be even
3✔
2210
                                // stricter than the initial/normal connect, so
3✔
2211
                                // we use the health check timeout here.
3✔
2212
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2213
                        ),
3✔
2214
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2215
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2216
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2217
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2218
                )
3✔
2219
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2220
        }
3✔
2221

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

×
2240
                                leader, err := leaderElector.IsLeader(
×
2241
                                        timeoutCtx,
×
2242
                                )
×
2243
                                if err != nil {
×
2244
                                        return fmt.Errorf("unable to check if "+
×
2245
                                                "still leader: %v", err)
×
2246
                                }
×
2247

2248
                                if !leader {
×
2249
                                        srvrLog.Debug("Not the current leader")
×
2250
                                        return fmt.Errorf("not the current " +
×
2251
                                                "leader")
×
2252
                                }
×
2253

2254
                                return nil
×
2255
                        },
2256
                        cfg.HealthChecks.LeaderCheck.Interval,
2257
                        cfg.HealthChecks.LeaderCheck.Timeout,
2258
                        cfg.HealthChecks.LeaderCheck.Backoff,
2259
                        cfg.HealthChecks.LeaderCheck.Attempts,
2260
                )
2261

2262
                checks = append(checks, leaderCheck)
×
2263
        }
2264

2265
        // If we have not disabled all of our health checks, we create a
2266
        // liveness monitor with our configured checks.
2267
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2268
                &healthcheck.Config{
3✔
2269
                        Checks:   checks,
3✔
2270
                        Shutdown: srvrLog.Criticalf,
3✔
2271
                },
3✔
2272
        )
3✔
2273
}
2274

2275
// Started returns true if the server has been started, and false otherwise.
2276
// NOTE: This function is safe for concurrent access.
2277
func (s *server) Started() bool {
3✔
2278
        return atomic.LoadInt32(&s.active) != 0
3✔
2279
}
3✔
2280

2281
// cleaner is used to aggregate "cleanup" functions during an operation that
2282
// starts several subsystems. In case one of the subsystem fails to start
2283
// and a proper resource cleanup is required, the "run" method achieves this
2284
// by running all these added "cleanup" functions.
2285
type cleaner []func() error
2286

2287
// add is used to add a cleanup function to be called when
2288
// the run function is executed.
2289
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2290
        return append(c, cleanup)
3✔
2291
}
3✔
2292

2293
// run is used to run all the previousely added cleanup functions.
2294
func (c cleaner) run() {
×
2295
        for i := len(c) - 1; i >= 0; i-- {
×
2296
                if err := c[i](); err != nil {
×
2297
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2298
                }
×
2299
        }
2300
}
2301

2302
// startLowLevelServices starts the low-level services of the server. These
2303
// services must be started successfully before running the main server. The
2304
// services are,
2305
// 1. the chain notifier.
2306
//
2307
// TODO(yy): identify and add more low-level services here.
2308
func (s *server) startLowLevelServices() error {
3✔
2309
        var startErr error
3✔
2310

3✔
2311
        cleanup := cleaner{}
3✔
2312

3✔
2313
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2314
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2315
                startErr = err
×
2316
        }
×
2317

2318
        if startErr != nil {
3✔
2319
                cleanup.run()
×
2320
        }
×
2321

2322
        return startErr
3✔
2323
}
2324

2325
// Start starts the main daemon server, all requested listeners, and any helper
2326
// goroutines.
2327
// NOTE: This function is safe for concurrent access.
2328
//
2329
//nolint:funlen
2330
func (s *server) Start(ctx context.Context) error {
3✔
2331
        // Get the current blockbeat.
3✔
2332
        beat, err := s.getStartingBeat()
3✔
2333
        if err != nil {
3✔
2334
                return err
×
2335
        }
×
2336

2337
        var startErr error
3✔
2338

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

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

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

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

2367
                // Start the notification server. This is used so channel
2368
                // management goroutines can be notified when a funding
2369
                // transaction reaches a sufficient number of confirmations, or
2370
                // when the input for the funding transaction is spent in an
2371
                // attempt at an uncooperative close by the counterparty.
2372
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2373
                if err := s.sigPool.Start(); err != nil {
3✔
2374
                        startErr = err
×
2375
                        return
×
2376
                }
×
2377

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

2384
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2385
                if err := s.readPool.Start(); err != nil {
3✔
2386
                        startErr = err
×
2387
                        return
×
2388
                }
×
2389

2390
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2391
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2392
                        startErr = err
×
2393
                        return
×
2394
                }
×
2395

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

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

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

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

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

2430
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2431
                if err := s.sweeper.Start(beat); err != nil {
3✔
2432
                        startErr = err
×
2433
                        return
×
2434
                }
×
2435

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

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

2448
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2449
                if err := s.fundingMgr.Start(); err != nil {
3✔
2450
                        startErr = err
×
2451
                        return
×
2452
                }
×
2453

2454
                // htlcSwitch must be started before chainArb since the latter
2455
                // relies on htlcSwitch to deliver resolution message upon
2456
                // start.
2457
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2458
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2459
                        startErr = err
×
2460
                        return
×
2461
                }
×
2462

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

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

2475
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2476
                if err := s.chainArb.Start(beat); err != nil {
3✔
2477
                        startErr = err
×
2478
                        return
×
2479
                }
×
2480

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

2487
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2488
                if err := s.graphBuilder.Start(); err != nil {
3✔
2489
                        startErr = err
×
2490
                        return
×
2491
                }
×
2492

2493
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2494
                if err := s.chanRouter.Start(); err != nil {
3✔
2495
                        startErr = err
×
2496
                        return
×
2497
                }
×
2498
                // The authGossiper depends on the chanRouter and therefore
2499
                // should be started after it.
2500
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2501
                if err := s.authGossiper.Start(); err != nil {
3✔
2502
                        startErr = err
×
2503
                        return
×
2504
                }
×
2505

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

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

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

2524
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2525
                if err := s.chanEventStore.Start(); err != nil {
3✔
2526
                        startErr = err
×
2527
                        return
×
2528
                }
×
2529

2530
                cleanup.add(func() error {
3✔
2531
                        s.missionController.StopStoreTickers()
×
2532
                        return nil
×
2533
                })
×
2534
                s.missionController.RunStoreTickers()
3✔
2535

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

2568
                // chanSubSwapper must be started after the `channelNotifier`
2569
                // because it depends on channel events as a synchronization
2570
                // point.
2571
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2572
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2573
                        startErr = err
×
2574
                        return
×
2575
                }
×
2576

2577
                if s.torController != nil {
3✔
2578
                        cleanup = cleanup.add(s.torController.Stop)
×
2579
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2580
                                startErr = err
×
2581
                                return
×
2582
                        }
×
2583
                }
2584

2585
                if s.natTraversal != nil {
3✔
2586
                        s.wg.Add(1)
×
2587
                        go s.watchExternalIP()
×
2588
                }
×
2589

2590
                // Start connmgr last to prevent connections before init.
2591
                cleanup = cleanup.add(func() error {
3✔
2592
                        s.connMgr.Stop()
×
2593
                        return nil
×
2594
                })
×
2595

2596
                // RESOLVE: s.connMgr.Start() is called here, but
2597
                // brontide.NewListener() is called in newServer. This means
2598
                // that we are actually listening and partially accepting
2599
                // inbound connections even before the connMgr starts.
2600
                //
2601
                // TODO(yy): move the log into the connMgr's `Start` method.
2602
                srvrLog.Info("connMgr starting...")
3✔
2603
                s.connMgr.Start()
3✔
2604
                srvrLog.Debug("connMgr started")
3✔
2605

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

2625
                        peerAddr := &lnwire.NetAddress{
3✔
2626
                                IdentityKey: parsedPubkey,
3✔
2627
                                Address:     addr,
3✔
2628
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2629
                        }
3✔
2630

3✔
2631
                        err = s.ConnectToPeer(
3✔
2632
                                peerAddr, true,
3✔
2633
                                s.cfg.ConnectionTimeout,
3✔
2634
                        )
3✔
2635
                        if err != nil {
3✔
2636
                                startErr = fmt.Errorf("unable to connect to "+
×
2637
                                        "peer address provided as a config "+
×
2638
                                        "option: %v", err)
×
2639
                                return
×
2640
                        }
×
2641
                }
2642

2643
                // Subscribe to NodeAnnouncements that advertise new addresses
2644
                // our persistent peers.
2645
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2646
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2647
                                "addr: %v", err)
×
2648

×
2649
                        startErr = err
×
2650
                        return
×
2651
                }
×
2652

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

×
2662
                        startErr = err
×
2663
                        return
×
2664
                }
×
2665

2666
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2667
                        srvrLog.Errorf("Failed to establish persistent "+
×
2668
                                "connections: %v", err)
×
2669
                }
×
2670

2671
                // setSeedList is a helper function that turns multiple DNS seed
2672
                // server tuples from the command line or config file into the
2673
                // data structure we need and does a basic formal sanity check
2674
                // in the process.
2675
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2676
                        if len(tuples) == 0 {
×
2677
                                return
×
2678
                        }
×
2679

2680
                        result := make([][2]string, len(tuples))
×
2681
                        for idx, tuple := range tuples {
×
2682
                                tuple = strings.TrimSpace(tuple)
×
2683
                                if len(tuple) == 0 {
×
2684
                                        return
×
2685
                                }
×
2686

2687
                                servers := strings.Split(tuple, ",")
×
2688
                                if len(servers) > 2 || len(servers) == 0 {
×
2689
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2690
                                                "seed tuple: %v", servers)
×
2691
                                        return
×
2692
                                }
×
2693

2694
                                copy(result[idx][:], servers)
×
2695
                        }
2696

2697
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2698
                }
2699

2700
                // Let users overwrite the DNS seed nodes. We only allow them
2701
                // for bitcoin mainnet/testnet/signet.
2702
                if s.cfg.Bitcoin.MainNet {
3✔
2703
                        setSeedList(
×
2704
                                s.cfg.Bitcoin.DNSSeeds,
×
2705
                                chainreg.BitcoinMainnetGenesis,
×
2706
                        )
×
2707
                }
×
2708
                if s.cfg.Bitcoin.TestNet3 {
3✔
2709
                        setSeedList(
×
2710
                                s.cfg.Bitcoin.DNSSeeds,
×
2711
                                chainreg.BitcoinTestnetGenesis,
×
2712
                        )
×
2713
                }
×
2714
                if s.cfg.Bitcoin.TestNet4 {
3✔
2715
                        setSeedList(
×
2716
                                s.cfg.Bitcoin.DNSSeeds,
×
2717
                                chainreg.BitcoinTestnet4Genesis,
×
2718
                        )
×
2719
                }
×
2720
                if s.cfg.Bitcoin.SigNet {
3✔
2721
                        setSeedList(
×
2722
                                s.cfg.Bitcoin.DNSSeeds,
×
2723
                                chainreg.BitcoinSignetGenesis,
×
2724
                        )
×
2725
                }
×
2726

2727
                // If network bootstrapping hasn't been disabled, then we'll
2728
                // configure the set of active bootstrappers, and launch a
2729
                // dedicated goroutine to maintain a set of persistent
2730
                // connections.
2731
                if !s.cfg.NoNetBootstrap {
6✔
2732
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2733
                        if err != nil {
3✔
2734
                                startErr = err
×
2735
                                return
×
2736
                        }
×
2737

2738
                        s.wg.Add(1)
3✔
2739
                        go s.peerBootstrapper(
3✔
2740
                                ctx, defaultMinPeers, bootstrappers,
3✔
2741
                        )
3✔
2742
                } else {
3✔
2743
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2744
                }
3✔
2745

2746
                // Start the blockbeat after all other subsystems have been
2747
                // started so they are ready to receive new blocks.
2748
                cleanup = cleanup.add(func() error {
3✔
2749
                        s.blockbeatDispatcher.Stop()
×
2750
                        return nil
×
2751
                })
×
2752
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2753
                        startErr = err
×
2754
                        return
×
2755
                }
×
2756

2757
                // Set the active flag now that we've completed the full
2758
                // startup.
2759
                atomic.StoreInt32(&s.active, 1)
3✔
2760
        })
2761

2762
        if startErr != nil {
3✔
2763
                cleanup.run()
×
2764
        }
×
2765
        return startErr
3✔
2766
}
2767

2768
// Stop gracefully shutsdown the main daemon server. This function will signal
2769
// any active goroutines, or helper objects to exit, then blocks until they've
2770
// all successfully exited. Additionally, any/all listeners are closed.
2771
// NOTE: This function is safe for concurrent access.
2772
func (s *server) Stop() error {
3✔
2773
        s.stop.Do(func() {
6✔
2774
                atomic.StoreInt32(&s.stopping, 1)
3✔
2775

3✔
2776
                ctx := context.Background()
3✔
2777

3✔
2778
                close(s.quit)
3✔
2779

3✔
2780
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2781
                s.connMgr.Stop()
3✔
2782

3✔
2783
                // Stop dispatching blocks to other systems immediately.
3✔
2784
                s.blockbeatDispatcher.Stop()
3✔
2785

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

2848
                // Update channel.backup file. Make sure to do it before
2849
                // stopping chanSubSwapper.
2850
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2851
                        ctx, s.chanStateDB, s.addrSource,
3✔
2852
                )
3✔
2853
                if err != nil {
3✔
2854
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2855
                                err)
×
2856
                } else {
3✔
2857
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2858
                        if err != nil {
6✔
2859
                                srvrLog.Warnf("Manual update of channel "+
3✔
2860
                                        "backup failed: %v", err)
3✔
2861
                        }
3✔
2862
                }
2863

2864
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2865
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2866
                }
×
2867
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2868
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2869
                }
×
2870
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2871
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2872
                                err)
×
2873
                }
×
2874
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2875
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2876
                                err)
×
2877
                }
×
2878
                s.missionController.StopStoreTickers()
3✔
2879

3✔
2880
                // Disconnect from each active peers to ensure that
3✔
2881
                // peerTerminationWatchers signal completion to each peer.
3✔
2882
                for _, peer := range s.Peers() {
6✔
2883
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2884
                        if err != nil {
3✔
2885
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2886
                                        "received error: %v", peer.IdentityKey(),
×
2887
                                        err,
×
2888
                                )
×
2889
                        }
×
2890
                }
2891

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

2903
                if s.hostAnn != nil {
3✔
2904
                        if err := s.hostAnn.Stop(); err != nil {
×
2905
                                srvrLog.Warnf("unable to shut down host "+
×
2906
                                        "annoucner: %v", err)
×
2907
                        }
×
2908
                }
2909

2910
                if s.livenessMonitor != nil {
6✔
2911
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2912
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2913
                                        "monitor: %v", err)
×
2914
                        }
×
2915
                }
2916

2917
                // Wait for all lingering goroutines to quit.
2918
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2919
                s.wg.Wait()
3✔
2920

3✔
2921
                srvrLog.Debug("Stopping buffer pools...")
3✔
2922
                s.sigPool.Stop()
3✔
2923
                s.writePool.Stop()
3✔
2924
                s.readPool.Stop()
3✔
2925
        })
2926

2927
        return nil
3✔
2928
}
2929

2930
// Stopped returns true if the server has been instructed to shutdown.
2931
// NOTE: This function is safe for concurrent access.
2932
func (s *server) Stopped() bool {
3✔
2933
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2934
}
3✔
2935

2936
// configurePortForwarding attempts to set up port forwarding for the different
2937
// ports that the server will be listening on.
2938
//
2939
// NOTE: This should only be used when using some kind of NAT traversal to
2940
// automatically set up forwarding rules.
2941
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2942
        ip, err := s.natTraversal.ExternalIP()
×
2943
        if err != nil {
×
2944
                return nil, err
×
2945
        }
×
2946
        s.lastDetectedIP = ip
×
2947

×
2948
        externalIPs := make([]string, 0, len(ports))
×
2949
        for _, port := range ports {
×
2950
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2951
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2952
                        continue
×
2953
                }
2954

2955
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2956
                externalIPs = append(externalIPs, hostIP)
×
2957
        }
2958

2959
        return externalIPs, nil
×
2960
}
2961

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

2977
// watchExternalIP continuously checks for an updated external IP address every
2978
// 15 minutes. Once a new IP address has been detected, it will automatically
2979
// handle port forwarding rules and send updated node announcements to the
2980
// currently connected peers.
2981
//
2982
// NOTE: This MUST be run as a goroutine.
2983
func (s *server) watchExternalIP() {
×
2984
        defer s.wg.Done()
×
2985

×
2986
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2987
        // up by the server.
×
2988
        defer s.removePortForwarding()
×
2989

×
2990
        // Keep track of the external IPs set by the user to avoid replacing
×
2991
        // them when detecting a new IP.
×
2992
        ipsSetByUser := make(map[string]struct{})
×
2993
        for _, ip := range s.cfg.ExternalIPs {
×
2994
                ipsSetByUser[ip.String()] = struct{}{}
×
2995
        }
×
2996

2997
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2998

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

3014
                        // Periodically renew the NAT port forwarding.
3015
                        for _, port := range forwardedPorts {
×
3016
                                err := s.natTraversal.AddPortMapping(port)
×
3017
                                if err != nil {
×
3018
                                        srvrLog.Warnf("Unable to automatically "+
×
3019
                                                "re-create port forwarding using %s: %v",
×
3020
                                                s.natTraversal.Name(), err)
×
3021
                                } else {
×
3022
                                        srvrLog.Debugf("Automatically re-created "+
×
3023
                                                "forwarding for port %d using %s to "+
×
3024
                                                "advertise external IP",
×
3025
                                                port, s.natTraversal.Name())
×
3026
                                }
×
3027
                        }
3028

3029
                        if ip.Equal(s.lastDetectedIP) {
×
3030
                                continue
×
3031
                        }
3032

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

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

3050
                                newAddrs = append(newAddrs, addr)
×
3051
                        }
3052

3053
                        // Skip the update if we weren't able to resolve any of
3054
                        // the new addresses.
3055
                        if len(newAddrs) == 0 {
×
3056
                                srvrLog.Debug("Skipping node announcement " +
×
3057
                                        "update due to not being able to " +
×
3058
                                        "resolve any new addresses")
×
3059
                                continue
×
3060
                        }
3061

3062
                        // Now, we'll need to update the addresses in our node's
3063
                        // announcement in order to propagate the update
3064
                        // throughout the network. We'll only include addresses
3065
                        // that have a different IP from the previous one, as
3066
                        // the previous IP is no longer valid.
3067
                        currentNodeAnn := s.getNodeAnnouncement()
×
3068

×
3069
                        for _, addr := range currentNodeAnn.Addresses {
×
3070
                                host, _, err := net.SplitHostPort(addr.String())
×
3071
                                if err != nil {
×
3072
                                        srvrLog.Debugf("Unable to determine "+
×
3073
                                                "host from address %v: %v",
×
3074
                                                addr, err)
×
3075
                                        continue
×
3076
                                }
3077

3078
                                // We'll also make sure to include external IPs
3079
                                // set manually by the user.
3080
                                _, setByUser := ipsSetByUser[addr.String()]
×
3081
                                if setByUser || host != s.lastDetectedIP.String() {
×
3082
                                        newAddrs = append(newAddrs, addr)
×
3083
                                }
×
3084
                        }
3085

3086
                        // Then, we'll generate a new timestamped node
3087
                        // announcement with the updated addresses and broadcast
3088
                        // it to our peers.
3089
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3090
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3091
                        )
×
3092
                        if err != nil {
×
3093
                                srvrLog.Debugf("Unable to generate new node "+
×
3094
                                        "announcement: %v", err)
×
3095
                                continue
×
3096
                        }
3097

3098
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3099
                        if err != nil {
×
3100
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3101
                                        "announcement to peers: %v", err)
×
3102
                                continue
×
3103
                        }
3104

3105
                        // Finally, update the last IP seen to the current one.
3106
                        s.lastDetectedIP = ip
×
3107
                case <-s.quit:
×
3108
                        break out
×
3109
                }
3110
        }
3111
}
3112

3113
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3114
// based on the server, and currently active bootstrap mechanisms as defined
3115
// within the current configuration.
3116
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3117
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3118

3✔
3119
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3120

3✔
3121
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3122
        // this can be used by default if we've already partially seeded the
3✔
3123
        // network.
3✔
3124
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3125
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3126
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3127
        )
3✔
3128
        if err != nil {
3✔
3129
                return nil, err
×
3130
        }
×
3131
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3132

3✔
3133
        // If this isn't using simnet or regtest mode, then one of our
3✔
3134
        // additional bootstrapping sources will be the set of running DNS
3✔
3135
        // seeds.
3✔
3136
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
3137
                //nolint:ll
×
3138
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3139

×
3140
                // If we have a set of DNS seeds for this chain, then we'll add
×
3141
                // it as an additional bootstrapping source.
×
3142
                if ok {
×
3143
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3144
                                "seeds: %v", dnsSeeds)
×
3145

×
3146
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3147
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3148
                        )
×
3149
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3150
                }
×
3151
        }
3152

3153
        return bootStrappers, nil
3✔
3154
}
3155

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

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

3✔
3168
        // We should ignore ourselves from bootstrapping.
3✔
3169
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3170
        ignore[selfKey] = struct{}{}
3✔
3171

3✔
3172
        // Ignore all connected peers.
3✔
3173
        for _, peer := range s.peersByPub {
3✔
3174
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3175
                ignore[nID] = struct{}{}
×
3176
        }
×
3177

3178
        // Ignore all persistent peers as they have a dedicated reconnecting
3179
        // process.
3180
        for pubKeyStr := range s.persistentPeers {
3✔
3181
                var nID autopilot.NodeID
×
3182
                copy(nID[:], []byte(pubKeyStr))
×
3183
                ignore[nID] = struct{}{}
×
3184
        }
×
3185

3186
        return ignore
3✔
3187
}
3188

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

3✔
3197
        defer s.wg.Done()
3✔
3198

3✔
3199
        // Before we continue, init the ignore peers map.
3✔
3200
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3201

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

3✔
3206
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3207
        // peers.
3✔
3208
        //
3✔
3209
        // We'll use a 15 second backoff, and double the time every time an
3✔
3210
        // epoch fails up to a ceiling.
3✔
3211
        backOff := time.Second * 15
3✔
3212

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

3✔
3218
        // We'll use the number of attempts and errors to determine if we need
3✔
3219
        // to increase the time between discovery epochs.
3✔
3220
        var epochErrors uint32 // To be used atomically.
3✔
3221
        var epochAttempts uint32
3✔
3222

3✔
3223
        for {
6✔
3224
                select {
3✔
3225
                // The ticker has just woken us up, so we'll need to check if
3226
                // we need to attempt to connect our to any more peers.
3227
                case <-sampleTicker.C:
×
3228
                        // Obtain the current number of peers, so we can gauge
×
3229
                        // if we need to sample more peers or not.
×
3230
                        s.mu.RLock()
×
3231
                        numActivePeers := uint32(len(s.peersByPub))
×
3232
                        s.mu.RUnlock()
×
3233

×
3234
                        // If we have enough peers, then we can loop back
×
3235
                        // around to the next round as we're done here.
×
3236
                        if numActivePeers >= numTargetPeers {
×
3237
                                continue
×
3238
                        }
3239

3240
                        // If all of our attempts failed during this last back
3241
                        // off period, then will increase our backoff to 5
3242
                        // minute ceiling to avoid an excessive number of
3243
                        // queries
3244
                        //
3245
                        // TODO(roasbeef): add reverse policy too?
3246

3247
                        if epochAttempts > 0 &&
×
3248
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3249

×
3250
                                sampleTicker.Stop()
×
3251

×
3252
                                backOff *= 2
×
3253
                                if backOff > bootstrapBackOffCeiling {
×
3254
                                        backOff = bootstrapBackOffCeiling
×
3255
                                }
×
3256

3257
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3258
                                        "%v", backOff)
×
3259
                                sampleTicker = time.NewTicker(backOff)
×
3260
                                continue
×
3261
                        }
3262

3263
                        atomic.StoreUint32(&epochErrors, 0)
×
3264
                        epochAttempts = 0
×
3265

×
3266
                        // Since we know need more peers, we'll compute the
×
3267
                        // exact number we need to reach our threshold.
×
3268
                        numNeeded := numTargetPeers - numActivePeers
×
3269

×
3270
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3271
                                "peers", numNeeded)
×
3272

×
3273
                        // With the number of peers we need calculated, we'll
×
3274
                        // query the network bootstrappers to sample a set of
×
3275
                        // random addrs for us.
×
3276
                        //
×
3277
                        // Before we continue, get a copy of the ignore peers
×
3278
                        // map.
×
3279
                        ignoreList = s.createBootstrapIgnorePeers()
×
3280

×
3281
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3282
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3283
                        )
×
3284
                        if err != nil {
×
3285
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3286
                                        "peers: %v", err)
×
3287
                                continue
×
3288
                        }
3289

3290
                        // Finally, we'll launch a new goroutine for each
3291
                        // prospective peer candidates.
3292
                        for _, addr := range peerAddrs {
×
3293
                                epochAttempts++
×
3294

×
3295
                                go func(a *lnwire.NetAddress) {
×
3296
                                        // TODO(roasbeef): can do AS, subnet,
×
3297
                                        // country diversity, etc
×
3298
                                        errChan := make(chan error, 1)
×
3299
                                        s.connectToPeer(
×
3300
                                                a, errChan,
×
3301
                                                s.cfg.ConnectionTimeout,
×
3302
                                        )
×
3303
                                        select {
×
3304
                                        case err := <-errChan:
×
3305
                                                if err == nil {
×
3306
                                                        return
×
3307
                                                }
×
3308

3309
                                                srvrLog.Errorf("Unable to "+
×
3310
                                                        "connect to %v: %v",
×
3311
                                                        a, err)
×
3312
                                                atomic.AddUint32(&epochErrors, 1)
×
3313
                                        case <-s.quit:
×
3314
                                        }
3315
                                }(addr)
3316
                        }
3317
                case <-s.quit:
3✔
3318
                        return
3✔
3319
                }
3320
        }
3321
}
3322

3323
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3324
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3325
// query back off each time we encounter a failure.
3326
const bootstrapBackOffCeiling = time.Minute * 5
3327

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

3✔
3335
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3336
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3337

3✔
3338
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3339
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3340
        var delaySignal <-chan time.Time
3✔
3341
        delayTime := time.Second * 2
3✔
3342

3✔
3343
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3344
        // then the main peer bootstrap logic.
3✔
3345
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3346

3✔
3347
        for attempts := 0; ; attempts++ {
6✔
3348
                // Check if the server has been requested to shut down in order
3✔
3349
                // to prevent blocking.
3✔
3350
                if s.Stopped() {
3✔
3351
                        return
×
3352
                }
×
3353

3354
                // We can exit our aggressive initial peer bootstrapping stage
3355
                // if we've reached out target number of peers.
3356
                s.mu.RLock()
3✔
3357
                numActivePeers := uint32(len(s.peersByPub))
3✔
3358
                s.mu.RUnlock()
3✔
3359

3✔
3360
                if numActivePeers >= numTargetPeers {
6✔
3361
                        return
3✔
3362
                }
3✔
3363

3364
                if attempts > 0 {
3✔
3365
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3366
                                "bootstrap peers (attempt #%v)", delayTime,
×
3367
                                attempts)
×
3368

×
3369
                        // We've completed at least one iterating and haven't
×
3370
                        // finished, so we'll start to insert a delay period
×
3371
                        // between each attempt.
×
3372
                        delaySignal = time.After(delayTime)
×
3373
                        select {
×
3374
                        case <-delaySignal:
×
3375
                        case <-s.quit:
×
3376
                                return
×
3377
                        }
3378

3379
                        // After our delay, we'll double the time we wait up to
3380
                        // the max back off period.
3381
                        delayTime *= 2
×
3382
                        if delayTime > backOffCeiling {
×
3383
                                delayTime = backOffCeiling
×
3384
                        }
×
3385
                }
3386

3387
                // Otherwise, we'll request for the remaining number of peers
3388
                // in order to reach our target.
3389
                peersNeeded := numTargetPeers - numActivePeers
3✔
3390
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3391
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3392
                )
3✔
3393
                if err != nil {
3✔
3394
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3395
                                "peers: %v", err)
×
3396
                        continue
×
3397
                }
3398

3399
                // Then, we'll attempt to establish a connection to the
3400
                // different peer addresses retrieved by our bootstrappers.
3401
                var wg sync.WaitGroup
3✔
3402
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3403
                        wg.Add(1)
3✔
3404
                        go func(addr *lnwire.NetAddress) {
6✔
3405
                                defer wg.Done()
3✔
3406

3✔
3407
                                errChan := make(chan error, 1)
3✔
3408
                                go s.connectToPeer(
3✔
3409
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3410
                                )
3✔
3411

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

3435
                wg.Wait()
3✔
3436
        }
3437
}
3438

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

3451
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3452
        if err != nil {
×
3453
                return err
×
3454
        }
×
3455

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

×
3468
        switch {
×
3469
        case s.cfg.Tor.V2:
×
3470
                onionCfg.Type = tor.V2
×
3471
        case s.cfg.Tor.V3:
×
3472
                onionCfg.Type = tor.V3
×
3473
        }
3474

3475
        addr, err := s.torController.AddOnion(onionCfg)
×
3476
        if err != nil {
×
3477
                return err
×
3478
        }
×
3479

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

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

3510
        return nil
×
3511
}
3512

3513
// findChannel finds a channel given a public key and ChannelID. It is an
3514
// optimization that is quicker than seeking for a channel given only the
3515
// ChannelID.
3516
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3517
        *channeldb.OpenChannel, error) {
3✔
3518

3✔
3519
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3520
        if err != nil {
3✔
3521
                return nil, err
×
3522
        }
×
3523

3524
        for _, channel := range nodeChans {
6✔
3525
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3526
                        return channel, nil
3✔
3527
                }
3✔
3528
        }
3529

3530
        return nil, fmt.Errorf("unable to find channel")
3✔
3531
}
3532

3533
// getNodeAnnouncement fetches the current, fully signed node announcement.
3534
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3535
        s.mu.Lock()
3✔
3536
        defer s.mu.Unlock()
3✔
3537

3✔
3538
        return *s.currentNodeAnn
3✔
3539
}
3✔
3540

3541
// genNodeAnnouncement generates and returns the current fully signed node
3542
// announcement. The time stamp of the announcement will be updated in order
3543
// to ensure it propagates through the network.
3544
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3545
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3546

3✔
3547
        s.mu.Lock()
3✔
3548
        defer s.mu.Unlock()
3✔
3549

3✔
3550
        // Create a shallow copy of the current node announcement to work on.
3✔
3551
        // This ensures the original announcement remains unchanged
3✔
3552
        // until the new announcement is fully signed and valid.
3✔
3553
        newNodeAnn := *s.currentNodeAnn
3✔
3554

3✔
3555
        // First, try to update our feature manager with the updated set of
3✔
3556
        // features.
3✔
3557
        if features != nil {
6✔
3558
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3559
                        feature.SetNodeAnn: features,
3✔
3560
                }
3✔
3561
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3562
                if err != nil {
6✔
3563
                        return lnwire.NodeAnnouncement{}, err
3✔
3564
                }
3✔
3565

3566
                // If we could successfully update our feature manager, add
3567
                // an update modifier to include these new features to our
3568
                // set.
3569
                modifiers = append(
3✔
3570
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3571
                )
3✔
3572
        }
3573

3574
        // Always update the timestamp when refreshing to ensure the update
3575
        // propagates.
3576
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3577

3✔
3578
        // Apply the requested changes to the node announcement.
3✔
3579
        for _, modifier := range modifiers {
6✔
3580
                modifier(&newNodeAnn)
3✔
3581
        }
3✔
3582

3583
        // Sign a new update after applying all of the passed modifiers.
3584
        err := netann.SignNodeAnnouncement(
3✔
3585
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3586
        )
3✔
3587
        if err != nil {
6✔
3588
                return lnwire.NodeAnnouncement{}, err
3✔
3589
        }
3✔
3590

3591
        // If signing succeeds, update the current announcement.
3592
        *s.currentNodeAnn = newNodeAnn
3✔
3593

3✔
3594
        return *s.currentNodeAnn, nil
3✔
3595
}
3596

3597
// updateAndBroadcastSelfNode generates a new node announcement
3598
// applying the giving modifiers and updating the time stamp
3599
// to ensure it propagates through the network. Then it broadcasts
3600
// it to the network.
3601
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3602
        features *lnwire.RawFeatureVector,
3603
        modifiers ...netann.NodeAnnModifier) error {
3✔
3604

3✔
3605
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3606
        if err != nil {
6✔
3607
                return fmt.Errorf("unable to generate new node "+
3✔
3608
                        "announcement: %v", err)
3✔
3609
        }
3✔
3610

3611
        // Update the on-disk version of our announcement.
3612
        // Load and modify self node istead of creating anew instance so we
3613
        // don't risk overwriting any existing values.
3614
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3615
        if err != nil {
3✔
3616
                return fmt.Errorf("unable to get current source node: %w", err)
×
3617
        }
×
3618

3619
        selfNode.HaveNodeAnnouncement = true
3✔
3620
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3621
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3622
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3623
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3624
        selfNode.Color = newNodeAnn.RGBColor
3✔
3625
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3626

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

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

3633
        // Finally, propagate it to the nodes in the network.
3634
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3635
        if err != nil {
3✔
3636
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3637
                        "announcement to peers: %v", err)
×
3638
                return err
×
3639
        }
×
3640

3641
        return nil
3✔
3642
}
3643

3644
type nodeAddresses struct {
3645
        pubKey    *btcec.PublicKey
3646
        addresses []net.Addr
3647
}
3648

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

3✔
3659
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3660
        // attempt to connect to based on our set of previous connections. Set
3✔
3661
        // the reconnection port to the default peer port.
3✔
3662
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3663
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3664
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3665
        }
×
3666

3667
        for _, node := range linkNodes {
6✔
3668
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3669
                nodeAddrs := &nodeAddresses{
3✔
3670
                        pubKey:    node.IdentityPub,
3✔
3671
                        addresses: node.Addresses,
3✔
3672
                }
3✔
3673
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3674
        }
3✔
3675

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

3✔
3685
                // If the remote party has announced the channel to us, but we
3✔
3686
                // haven't yet, then we won't have a policy. However, we don't
3✔
3687
                // need this to connect to the peer, so we'll log it and move on.
3✔
3688
                if !havePolicy {
3✔
3689
                        srvrLog.Warnf("No channel policy found for "+
×
3690
                                "ChannelPoint(%v): ", chanPoint)
×
3691
                }
×
3692

3693
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3694

3✔
3695
                // Add all unique addresses from channel
3✔
3696
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3697
                // connect to for this peer.
3✔
3698
                addrSet := make(map[string]net.Addr)
3✔
3699
                for _, addr := range channelPeer.Addresses {
6✔
3700
                        switch addr.(type) {
3✔
3701
                        case *net.TCPAddr:
3✔
3702
                                addrSet[addr.String()] = addr
3✔
3703

3704
                        // We'll only attempt to connect to Tor addresses if Tor
3705
                        // outbound support is enabled.
3706
                        case *tor.OnionAddr:
×
3707
                                if s.cfg.Tor.Active {
×
3708
                                        addrSet[addr.String()] = addr
×
3709
                                }
×
3710
                        }
3711
                }
3712

3713
                // If this peer is also recorded as a link node, we'll add any
3714
                // additional addresses that have not already been selected.
3715
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3716
                if ok {
6✔
3717
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3718
                                switch lnAddress.(type) {
3✔
3719
                                case *net.TCPAddr:
3✔
3720
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3721

3722
                                // We'll only attempt to connect to Tor
3723
                                // addresses if Tor outbound support is enabled.
3724
                                case *tor.OnionAddr:
×
3725
                                        if s.cfg.Tor.Active {
×
3726
                                                //nolint:ll
×
3727
                                                addrSet[lnAddress.String()] = lnAddress
×
3728
                                        }
×
3729
                                }
3730
                        }
3731
                }
3732

3733
                // Construct a slice of the deduped addresses.
3734
                var addrs []net.Addr
3✔
3735
                for _, addr := range addrSet {
6✔
3736
                        addrs = append(addrs, addr)
3✔
3737
                }
3✔
3738

3739
                n := &nodeAddresses{
3✔
3740
                        addresses: addrs,
3✔
3741
                }
3✔
3742
                n.pubKey, err = channelPeer.PubKey()
3✔
3743
                if err != nil {
3✔
3744
                        return err
×
3745
                }
×
3746

3747
                graphAddrs[pubStr] = n
3✔
3748
                return nil
3✔
3749
        }
3750
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3751
                ctx, forEachSrcNodeChan, func() {
6✔
3752
                        clear(graphAddrs)
3✔
3753
                },
3✔
3754
        )
3755
        if err != nil {
3✔
3756
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3757
                        "%v", err)
×
3758

×
3759
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3760
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3761

×
3762
                        return err
×
3763
                }
×
3764
        }
3765

3766
        // Combine the addresses from the link nodes and the channel graph.
3767
        for pubStr, nodeAddr := range graphAddrs {
6✔
3768
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3769
        }
3✔
3770

3771
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3772
                len(nodeAddrsMap))
3✔
3773

3✔
3774
        // Acquire and hold server lock until all persistent connection requests
3✔
3775
        // have been recorded and sent to the connection manager.
3✔
3776
        s.mu.Lock()
3✔
3777
        defer s.mu.Unlock()
3✔
3778

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

3793
                for _, address := range nodeAddr.addresses {
6✔
3794
                        // Create a wrapper address which couples the IP and
3✔
3795
                        // the pubkey so the brontide authenticated connection
3✔
3796
                        // can be established.
3✔
3797
                        lnAddr := &lnwire.NetAddress{
3✔
3798
                                IdentityKey: nodeAddr.pubKey,
3✔
3799
                                Address:     address,
3✔
3800
                        }
3✔
3801

3✔
3802
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3803
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3804
                }
3✔
3805

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

3✔
3816
                        go s.connectToPersistentPeer(pubStr)
3✔
3817
                } else {
3✔
3818
                        go s.delayInitialReconnect(pubStr)
×
3819
                }
×
3820

3821
                numOutboundConns++
3✔
3822
        }
3823

3824
        return nil
3✔
3825
}
3826

3827
// delayInitialReconnect will attempt a reconnection to the given peer after
3828
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3829
//
3830
// NOTE: This method MUST be run as a goroutine.
3831
func (s *server) delayInitialReconnect(pubStr string) {
×
3832
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3833
        select {
×
3834
        case <-time.After(delay):
×
3835
                s.connectToPersistentPeer(pubStr)
×
3836
        case <-s.quit:
×
3837
        }
3838
}
3839

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

3✔
3846
        s.mu.Lock()
3✔
3847
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3848
                delete(s.persistentPeers, pubKeyStr)
3✔
3849
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3850
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3851
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3852
                s.mu.Unlock()
3✔
3853

3✔
3854
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3855
                        "peer has no open channels", compressedPubKey)
3✔
3856

3✔
3857
                return
3✔
3858
        }
3✔
3859
        s.mu.Unlock()
3✔
3860
}
3861

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

3879
// BroadcastMessage sends a request to the server to broadcast a set of
3880
// messages to all peers other than the one specified by the `skips` parameter.
3881
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3882
// the target peers.
3883
//
3884
// NOTE: This function is safe for concurrent access.
3885
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3886
        msgs ...lnwire.Message) error {
3✔
3887

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

3902
                peers = append(peers, sPeer)
3✔
3903
        }
3904
        s.mu.RUnlock()
3✔
3905

3✔
3906
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3907
        // all messages to each of peers.
3✔
3908
        var wg sync.WaitGroup
3✔
3909
        for _, sPeer := range peers {
6✔
3910
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3911
                        sPeer.PubKey())
3✔
3912

3✔
3913
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3914
                wg.Add(1)
3✔
3915
                s.wg.Add(1)
3✔
3916
                go func(p lnpeer.Peer) {
6✔
3917
                        defer s.wg.Done()
3✔
3918
                        defer wg.Done()
3✔
3919

3✔
3920
                        p.SendMessageLazy(false, msgs...)
3✔
3921
                }(sPeer)
3✔
3922
        }
3923

3924
        // Wait for all messages to have been dispatched before returning to
3925
        // caller.
3926
        wg.Wait()
3✔
3927

3✔
3928
        return nil
3✔
3929
}
3930

3931
// NotifyWhenOnline can be called by other subsystems to get notified when a
3932
// particular peer comes online. The peer itself is sent across the peerChan.
3933
//
3934
// NOTE: This function is safe for concurrent access.
3935
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3936
        peerChan chan<- lnpeer.Peer) {
3✔
3937

3✔
3938
        s.mu.Lock()
3✔
3939

3✔
3940
        // Compute the target peer's identifier.
3✔
3941
        pubStr := string(peerKey[:])
3✔
3942

3✔
3943
        // Check if peer is connected.
3✔
3944
        peer, ok := s.peersByPub[pubStr]
3✔
3945
        if ok {
6✔
3946
                // Unlock here so that the mutex isn't held while we are
3✔
3947
                // waiting for the peer to become active.
3✔
3948
                s.mu.Unlock()
3✔
3949

3✔
3950
                // Wait until the peer signals that it is actually active
3✔
3951
                // rather than only in the server's maps.
3✔
3952
                select {
3✔
3953
                case <-peer.ActiveSignal():
3✔
3954
                case <-peer.QuitSignal():
×
3955
                        // The peer quit, so we'll add the channel to the slice
×
3956
                        // and return.
×
3957
                        s.mu.Lock()
×
3958
                        s.peerConnectedListeners[pubStr] = append(
×
3959
                                s.peerConnectedListeners[pubStr], peerChan,
×
3960
                        )
×
3961
                        s.mu.Unlock()
×
3962
                        return
×
3963
                }
3964

3965
                // Connected, can return early.
3966
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3967

3✔
3968
                select {
3✔
3969
                case peerChan <- peer:
3✔
3970
                case <-s.quit:
×
3971
                }
3972

3973
                return
3✔
3974
        }
3975

3976
        // Not connected, store this listener such that it can be notified when
3977
        // the peer comes online.
3978
        s.peerConnectedListeners[pubStr] = append(
3✔
3979
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3980
        )
3✔
3981
        s.mu.Unlock()
3✔
3982
}
3983

3984
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3985
// the given public key has been disconnected. The notification is signaled by
3986
// closing the channel returned.
3987
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3988
        s.mu.Lock()
3✔
3989
        defer s.mu.Unlock()
3✔
3990

3✔
3991
        c := make(chan struct{})
3✔
3992

3✔
3993
        // If the peer is already offline, we can immediately trigger the
3✔
3994
        // notification.
3✔
3995
        peerPubKeyStr := string(peerPubKey[:])
3✔
3996
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3997
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3998
                close(c)
×
3999
                return c
×
4000
        }
×
4001

4002
        // Otherwise, the peer is online, so we'll keep track of the channel to
4003
        // trigger the notification once the server detects the peer
4004
        // disconnects.
4005
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
4006
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
4007
        )
3✔
4008

3✔
4009
        return c
3✔
4010
}
4011

4012
// FindPeer will return the peer that corresponds to the passed in public key.
4013
// This function is used by the funding manager, allowing it to update the
4014
// daemon's local representation of the remote peer.
4015
//
4016
// NOTE: This function is safe for concurrent access.
4017
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
4018
        s.mu.RLock()
3✔
4019
        defer s.mu.RUnlock()
3✔
4020

3✔
4021
        pubStr := string(peerKey.SerializeCompressed())
3✔
4022

3✔
4023
        return s.findPeerByPubStr(pubStr)
3✔
4024
}
3✔
4025

4026
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
4027
// which should be a string representation of the peer's serialized, compressed
4028
// public key.
4029
//
4030
// NOTE: This function is safe for concurrent access.
4031
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
4032
        s.mu.RLock()
3✔
4033
        defer s.mu.RUnlock()
3✔
4034

3✔
4035
        return s.findPeerByPubStr(pubStr)
3✔
4036
}
3✔
4037

4038
// findPeerByPubStr is an internal method that retrieves the specified peer from
4039
// the server's internal state using.
4040
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
4041
        peer, ok := s.peersByPub[pubStr]
3✔
4042
        if !ok {
6✔
4043
                return nil, ErrPeerNotConnected
3✔
4044
        }
3✔
4045

4046
        return peer, nil
3✔
4047
}
4048

4049
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
4050
// exponential backoff. If no previous backoff was known, the default is
4051
// returned.
4052
func (s *server) nextPeerBackoff(pubStr string,
4053
        startTime time.Time) time.Duration {
3✔
4054

3✔
4055
        // Now, determine the appropriate backoff to use for the retry.
3✔
4056
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
4057
        if !ok {
6✔
4058
                // If an existing backoff was unknown, use the default.
3✔
4059
                return s.cfg.MinBackoff
3✔
4060
        }
3✔
4061

4062
        // If the peer failed to start properly, we'll just use the previous
4063
        // backoff to compute the subsequent randomized exponential backoff
4064
        // duration. This will roughly double on average.
4065
        if startTime.IsZero() {
3✔
4066
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4067
        }
×
4068

4069
        // The peer succeeded in starting. If the connection didn't last long
4070
        // enough to be considered stable, we'll continue to back off retries
4071
        // with this peer.
4072
        connDuration := time.Since(startTime)
3✔
4073
        if connDuration < defaultStableConnDuration {
6✔
4074
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4075
        }
3✔
4076

4077
        // The peer succeed in starting and this was stable peer, so we'll
4078
        // reduce the timeout duration by the length of the connection after
4079
        // applying randomized exponential backoff. We'll only apply this in the
4080
        // case that:
4081
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4082
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4083
        if relaxedBackoff > s.cfg.MinBackoff {
×
4084
                return relaxedBackoff
×
4085
        }
×
4086

4087
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4088
        // the stable connection lasted much longer than our previous backoff.
4089
        // To reward such good behavior, we'll reconnect after the default
4090
        // timeout.
4091
        return s.cfg.MinBackoff
×
4092
}
4093

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

×
4104
        // The connection that comes from the node with a "smaller" pubkey
×
4105
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4106
        // should drop our established connection.
×
4107
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4108
}
×
4109

4110
// InboundPeerConnected initializes a new peer in response to a new inbound
4111
// connection.
4112
//
4113
// NOTE: This function is safe for concurrent access.
4114
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4115
        // Exit early if we have already been instructed to shutdown, this
3✔
4116
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4117
        if s.Stopped() {
3✔
4118
                return
×
4119
        }
×
4120

4121
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4122
        pubSer := nodePub.SerializeCompressed()
3✔
4123
        pubStr := string(pubSer)
3✔
4124

3✔
4125
        var pubBytes [33]byte
3✔
4126
        copy(pubBytes[:], pubSer)
3✔
4127

3✔
4128
        s.mu.Lock()
3✔
4129
        defer s.mu.Unlock()
3✔
4130

3✔
4131
        // If we already have an outbound connection to this peer, then ignore
3✔
4132
        // this new connection.
3✔
4133
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4134
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4135
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4136
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4137

3✔
4138
                conn.Close()
3✔
4139
                return
3✔
4140
        }
3✔
4141

4142
        // If we already have a valid connection that is scheduled to take
4143
        // precedence once the prior peer has finished disconnecting, we'll
4144
        // ignore this connection.
4145
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4146
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4147
                        "scheduled", conn.RemoteAddr(), p)
×
4148
                conn.Close()
×
4149
                return
×
4150
        }
×
4151

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

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

4167
        case nil:
3✔
4168
                ctx := btclog.WithCtx(
3✔
4169
                        context.TODO(),
3✔
4170
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4171
                )
3✔
4172

3✔
4173
                // We already have a connection with the incoming peer. If the
3✔
4174
                // connection we've already established should be kept and is
3✔
4175
                // not of the same type of the new connection (inbound), then
3✔
4176
                // we'll close out the new connection s.t there's only a single
3✔
4177
                // connection between us.
3✔
4178
                localPub := s.identityECDH.PubKey()
3✔
4179
                if !connectedPeer.Inbound() &&
3✔
4180
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4181

×
4182
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4183
                                "peer, but already have outbound "+
×
4184
                                "connection, dropping conn",
×
4185
                                fmt.Errorf("already have outbound conn"))
×
4186
                        conn.Close()
×
4187
                        return
×
4188
                }
×
4189

4190
                // Otherwise, if we should drop the connection, then we'll
4191
                // disconnect our already connected peer.
4192
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4193

3✔
4194
                s.cancelConnReqs(pubStr, nil)
3✔
4195

3✔
4196
                // Remove the current peer from the server's internal state and
3✔
4197
                // signal that the peer termination watcher does not need to
3✔
4198
                // execute for this peer.
3✔
4199
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4200
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4201
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4202
                        s.peerConnected(conn, nil, true)
3✔
4203
                }
3✔
4204
        }
4205
}
4206

4207
// OutboundPeerConnected initializes a new peer in response to a new outbound
4208
// connection.
4209
// NOTE: This function is safe for concurrent access.
4210
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4211
        // Exit early if we have already been instructed to shutdown, this
3✔
4212
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4213
        if s.Stopped() {
3✔
4214
                return
×
4215
        }
×
4216

4217
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4218
        pubSer := nodePub.SerializeCompressed()
3✔
4219
        pubStr := string(pubSer)
3✔
4220

3✔
4221
        var pubBytes [33]byte
3✔
4222
        copy(pubBytes[:], pubSer)
3✔
4223

3✔
4224
        s.mu.Lock()
3✔
4225
        defer s.mu.Unlock()
3✔
4226

3✔
4227
        // If we already have an inbound connection to this peer, then ignore
3✔
4228
        // this new connection.
3✔
4229
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4230
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4231
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4232
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4233

3✔
4234
                if connReq != nil {
6✔
4235
                        s.connMgr.Remove(connReq.ID())
3✔
4236
                }
3✔
4237
                conn.Close()
3✔
4238
                return
3✔
4239
        }
4240
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4241
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4242
                s.connMgr.Remove(connReq.ID())
×
4243
                conn.Close()
×
4244
                return
×
4245
        }
×
4246

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

×
4253
                if connReq != nil {
×
4254
                        s.connMgr.Remove(connReq.ID())
×
4255
                }
×
4256

4257
                conn.Close()
×
4258
                return
×
4259
        }
4260

4261
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4262
                conn.RemoteAddr())
3✔
4263

3✔
4264
        if connReq != nil {
6✔
4265
                // A successful connection was returned by the connmgr.
3✔
4266
                // Immediately cancel all pending requests, excluding the
3✔
4267
                // outbound connection we just established.
3✔
4268
                ignore := connReq.ID()
3✔
4269
                s.cancelConnReqs(pubStr, &ignore)
3✔
4270
        } else {
6✔
4271
                // This was a successful connection made by some other
3✔
4272
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4273
                s.cancelConnReqs(pubStr, nil)
3✔
4274
        }
3✔
4275

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

4287
        case nil:
3✔
4288
                ctx := btclog.WithCtx(
3✔
4289
                        context.TODO(),
3✔
4290
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4291
                )
3✔
4292

3✔
4293
                // We already have a connection with the incoming peer. If the
3✔
4294
                // connection we've already established should be kept and is
3✔
4295
                // not of the same type of the new connection (outbound), then
3✔
4296
                // we'll close out the new connection s.t there's only a single
3✔
4297
                // connection between us.
3✔
4298
                localPub := s.identityECDH.PubKey()
3✔
4299
                if connectedPeer.Inbound() &&
3✔
4300
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4301

×
4302
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4303
                                "to peer, but already have inbound "+
×
4304
                                "connection, dropping conn",
×
4305
                                fmt.Errorf("already have inbound conn"))
×
4306
                        if connReq != nil {
×
4307
                                s.connMgr.Remove(connReq.ID())
×
4308
                        }
×
4309
                        conn.Close()
×
4310
                        return
×
4311
                }
4312

4313
                // Otherwise, _their_ connection should be dropped. So we'll
4314
                // disconnect the peer and send the now obsolete peer to the
4315
                // server for garbage collection.
4316
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4317

3✔
4318
                // Remove the current peer from the server's internal state and
3✔
4319
                // signal that the peer termination watcher does not need to
3✔
4320
                // execute for this peer.
3✔
4321
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4322
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4323
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4324
                        s.peerConnected(conn, connReq, false)
3✔
4325
                }
3✔
4326
        }
4327
}
4328

4329
// UnassignedConnID is the default connection ID that a request can have before
4330
// it actually is submitted to the connmgr.
4331
// TODO(conner): move into connmgr package, or better, add connmgr method for
4332
// generating atomic IDs
4333
const UnassignedConnID uint64 = 0
4334

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

4349
        // Next, check to see if we have any outstanding persistent connection
4350
        // requests to this peer. If so, then we'll remove all of these
4351
        // connection requests, and also delete the entry from the map.
4352
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4353
        if !ok {
6✔
4354
                return
3✔
4355
        }
3✔
4356

4357
        for _, connReq := range connReqs {
6✔
4358
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4359

3✔
4360
                // Atomically capture the current request identifier.
3✔
4361
                connID := connReq.ID()
3✔
4362

3✔
4363
                // Skip any zero IDs, this indicates the request has not
3✔
4364
                // yet been schedule.
3✔
4365
                if connID == UnassignedConnID {
3✔
4366
                        continue
×
4367
                }
4368

4369
                // Skip a particular connection ID if instructed.
4370
                if skip != nil && connID == *skip {
6✔
4371
                        continue
3✔
4372
                }
4373

4374
                s.connMgr.Remove(connID)
3✔
4375
        }
4376

4377
        delete(s.persistentConnReqs, pubStr)
3✔
4378
}
4379

4380
// handleCustomMessage dispatches an incoming custom peers message to
4381
// subscribers.
4382
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4383
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4384
                peer, msg.Type)
3✔
4385

3✔
4386
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4387
                Peer: peer,
3✔
4388
                Msg:  msg,
3✔
4389
        })
3✔
4390
}
3✔
4391

4392
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4393
// messages.
4394
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4395
        return s.customMessageServer.Subscribe()
3✔
4396
}
3✔
4397

4398
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4399
// the channelNotifier's NotifyOpenChannelEvent.
4400
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4401
        remotePub *btcec.PublicKey) {
3✔
4402

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

4409
        // Notify subscribers about this open channel event.
4410
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4411
}
4412

4413
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4414
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4415
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4416
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4417

3✔
4418
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4419
        // peer.
3✔
4420
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4421
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4422
                        "channel[%v] pending open",
×
4423
                        remotePub.SerializeCompressed(), op)
×
4424
        }
×
4425

4426
        // Notify subscribers about this event.
4427
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4428
}
4429

4430
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4431
// calls the channelNotifier's NotifyFundingTimeout.
4432
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4433
        remotePub *btcec.PublicKey) {
3✔
4434

3✔
4435
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4436
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4437
        if err != nil {
3✔
4438
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4439
                        "channel[%v] pending close",
×
4440
                        remotePub.SerializeCompressed(), op)
×
4441
        }
×
4442

4443
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4444
                // If we encounter an error while attempting to disconnect the
×
4445
                // peer, log the error.
×
4446
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4447
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4448
                }
×
4449
        }
4450

4451
        // Notify subscribers about this event.
4452
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4453
}
4454

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

3✔
4462
        brontideConn := conn.(*brontide.Conn)
3✔
4463
        addr := conn.RemoteAddr()
3✔
4464
        pubKey := brontideConn.RemotePub()
3✔
4465

3✔
4466
        // Only restrict access for inbound connections, which means if the
3✔
4467
        // remote node's public key is banned or the restricted slots are used
3✔
4468
        // up, we will drop the connection.
3✔
4469
        //
3✔
4470
        // TODO(yy): Consider perform this check in
3✔
4471
        // `peerAccessMan.addPeerAccess`.
3✔
4472
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4473
        if inbound && err != nil {
3✔
4474
                pubSer := pubKey.SerializeCompressed()
×
4475

×
4476
                // Clean up the persistent peer maps if we're dropping this
×
4477
                // connection.
×
4478
                s.bannedPersistentPeerConnection(string(pubSer))
×
4479

×
4480
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4481
                        "of restricted-access connection slots: %v.", pubSer,
×
4482
                        err)
×
4483

×
4484
                conn.Close()
×
4485

×
4486
                return
×
4487
        }
×
4488

4489
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4490
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4491

3✔
4492
        peerAddr := &lnwire.NetAddress{
3✔
4493
                IdentityKey: pubKey,
3✔
4494
                Address:     addr,
3✔
4495
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4496
        }
3✔
4497

3✔
4498
        // With the brontide connection established, we'll now craft the feature
3✔
4499
        // vectors to advertise to the remote node.
3✔
4500
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4501
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4502

3✔
4503
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4504
        // found, create a fresh buffer.
3✔
4505
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4506
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4507
        if !ok {
6✔
4508
                var err error
3✔
4509
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4510
                if err != nil {
3✔
4511
                        srvrLog.Errorf("unable to create peer %v", err)
×
4512
                        return
×
4513
                }
×
4514
        }
4515

4516
        // If we directly set the peer.Config TowerClient member to the
4517
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4518
        // the peer.Config's TowerClient member will not evaluate to nil even
4519
        // though the underlying value is nil. To avoid this gotcha which can
4520
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4521
        // TowerClient if needed.
4522
        var towerClient wtclient.ClientManager
3✔
4523
        if s.towerClientMgr != nil {
6✔
4524
                towerClient = s.towerClientMgr
3✔
4525
        }
3✔
4526

4527
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4528
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4529

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

3✔
4573
                        return s.genNodeAnnouncement(nil)
3✔
4574
                },
3✔
4575

4576
                PongBuf: s.pongBuf,
4577

4578
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4579

4580
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4581

4582
                FundingManager: s.fundingMgr,
4583

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

4614
                        return clock.NewDefaultClock().Now().Before(
3✔
4615
                                EndorsementExperimentEnd,
3✔
4616
                        )
3✔
4617
                },
4618
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4619
        }
4620

4621
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4622
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4623

3✔
4624
        p := peer.NewBrontide(pCfg)
3✔
4625

3✔
4626
        // Update the access manager with the access permission for this peer.
3✔
4627
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4628

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

3✔
4632
        s.addPeer(p)
3✔
4633

3✔
4634
        // Once we have successfully added the peer to the server, we can
3✔
4635
        // delete the previous error buffer from the server's map of error
3✔
4636
        // buffers.
3✔
4637
        delete(s.peerErrors, pkStr)
3✔
4638

3✔
4639
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4640
        // includes sending and receiving Init messages, which would be a DOS
3✔
4641
        // vector if we held the server's mutex throughout the procedure.
3✔
4642
        s.wg.Add(1)
3✔
4643
        go s.peerInitializer(p)
3✔
4644
}
4645

4646
// addPeer adds the passed peer to the server's global state of all active
4647
// peers.
4648
func (s *server) addPeer(p *peer.Brontide) {
3✔
4649
        if p == nil {
3✔
4650
                return
×
4651
        }
×
4652

4653
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4654

3✔
4655
        // Ignore new peers if we're shutting down.
3✔
4656
        if s.Stopped() {
3✔
4657
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4658
                        pubBytes)
×
4659
                p.Disconnect(ErrServerShuttingDown)
×
4660

×
4661
                return
×
4662
        }
×
4663

4664
        // Track the new peer in our indexes so we can quickly look it up either
4665
        // according to its public key, or its peer ID.
4666
        // TODO(roasbeef): pipe all requests through to the
4667
        // queryHandler/peerManager
4668

4669
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4670
        // be human-readable.
4671
        pubStr := string(pubBytes)
3✔
4672

3✔
4673
        s.peersByPub[pubStr] = p
3✔
4674

3✔
4675
        if p.Inbound() {
6✔
4676
                s.inboundPeers[pubStr] = p
3✔
4677
        } else {
6✔
4678
                s.outboundPeers[pubStr] = p
3✔
4679
        }
3✔
4680

4681
        // Inform the peer notifier of a peer online event so that it can be reported
4682
        // to clients listening for peer events.
4683
        var pubKey [33]byte
3✔
4684
        copy(pubKey[:], pubBytes)
3✔
4685
}
4686

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

3✔
4699
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4700

3✔
4701
        // Avoid initializing peers while the server is exiting.
3✔
4702
        if s.Stopped() {
3✔
4703
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4704
                        pubBytes)
×
4705
                return
×
4706
        }
×
4707

4708
        // Create a channel that will be used to signal a successful start of
4709
        // the link. This prevents the peer termination watcher from beginning
4710
        // its duty too early.
4711
        ready := make(chan struct{})
3✔
4712

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

3✔
4722
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4723
        // will unblock the peerTerminationWatcher.
3✔
4724
        if err := p.Start(); err != nil {
6✔
4725
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4726

3✔
4727
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4728
                return
3✔
4729
        }
3✔
4730

4731
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4732
        // was successful, and to begin watching the peer's wait group.
4733
        close(ready)
3✔
4734

3✔
4735
        s.mu.Lock()
3✔
4736
        defer s.mu.Unlock()
3✔
4737

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

3✔
4741
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4742
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4743
        pubStr := string(pubBytes)
3✔
4744
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4745
                select {
3✔
4746
                case peerChan <- p:
3✔
4747
                case <-s.quit:
×
4748
                        return
×
4749
                }
4750
        }
4751
        delete(s.peerConnectedListeners, pubStr)
3✔
4752

3✔
4753
        // Since the peer has been fully initialized, now it's time to notify
3✔
4754
        // the RPC about the peer online event.
3✔
4755
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4756
}
4757

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

3✔
4772
        ctx := btclog.WithCtx(
3✔
4773
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4774
        )
3✔
4775

3✔
4776
        p.WaitForDisconnect(ready)
3✔
4777

3✔
4778
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4779

3✔
4780
        // If the server is exiting then we can bail out early ourselves as all
3✔
4781
        // the other sub-systems will already be shutting down.
3✔
4782
        if s.Stopped() {
6✔
4783
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4784
                return
3✔
4785
        }
3✔
4786

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

3✔
4793
        pubKey := p.IdentityKey()
3✔
4794

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

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

4809
        for _, link := range links {
6✔
4810
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4811
        }
3✔
4812

4813
        s.mu.Lock()
3✔
4814
        defer s.mu.Unlock()
3✔
4815

3✔
4816
        // If there were any notification requests for when this peer
3✔
4817
        // disconnected, we can trigger them now.
3✔
4818
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4819
        pubStr := string(pubKey.SerializeCompressed())
3✔
4820
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4821
                close(offlineChan)
3✔
4822
        }
3✔
4823
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4824

3✔
4825
        // If the server has already removed this peer, we can short circuit the
3✔
4826
        // peer termination watcher and skip cleanup.
3✔
4827
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4828
                delete(s.ignorePeerTermination, p)
3✔
4829

3✔
4830
                pubKey := p.PubKey()
3✔
4831
                pubStr := string(pubKey[:])
3✔
4832

3✔
4833
                // If a connection callback is present, we'll go ahead and
3✔
4834
                // execute it now that previous peer has fully disconnected. If
3✔
4835
                // the callback is not present, this likely implies the peer was
3✔
4836
                // purposefully disconnected via RPC, and that no reconnect
3✔
4837
                // should be attempted.
3✔
4838
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4839
                if ok {
6✔
4840
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4841
                        connCallback()
3✔
4842
                }
3✔
4843
                return
3✔
4844
        }
4845

4846
        // First, cleanup any remaining state the server has regarding the peer
4847
        // in question.
4848
        s.removePeerUnsafe(ctx, p)
3✔
4849

3✔
4850
        // Next, check to see if this is a persistent peer or not.
3✔
4851
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4852
                return
3✔
4853
        }
3✔
4854

4855
        // Get the last address that we used to connect to the peer.
4856
        addrs := []net.Addr{
3✔
4857
                p.NetAddress().Address,
3✔
4858
        }
3✔
4859

3✔
4860
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4861
        // reconnection purposes.
3✔
4862
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4863
        switch {
3✔
4864
        // We found advertised addresses, so use them.
4865
        case err == nil:
3✔
4866
                addrs = advertisedAddrs
3✔
4867

4868
        // The peer doesn't have an advertised address.
4869
        case err == errNoAdvertisedAddr:
3✔
4870
                // If it is an outbound peer then we fall back to the existing
3✔
4871
                // peer address.
3✔
4872
                if !p.Inbound() {
6✔
4873
                        break
3✔
4874
                }
4875

4876
                // Fall back to the existing peer address if
4877
                // we're not accepting connections over Tor.
4878
                if s.torController == nil {
6✔
4879
                        break
3✔
4880
                }
4881

4882
                // If we are, the peer's address won't be known
4883
                // to us (we'll see a private address, which is
4884
                // the address used by our onion service to dial
4885
                // to lnd), so we don't have enough information
4886
                // to attempt a reconnect.
4887
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4888
                        "to inbound peer without advertised address")
×
4889
                return
×
4890

4891
        // We came across an error retrieving an advertised
4892
        // address, log it, and fall back to the existing peer
4893
        // address.
4894
        default:
3✔
4895
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4896
                        "address for peer", err)
3✔
4897
        }
4898

4899
        // Make an easy lookup map so that we can check if an address
4900
        // is already in the address list that we have stored for this peer.
4901
        existingAddrs := make(map[string]bool)
3✔
4902
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4903
                existingAddrs[addr.String()] = true
3✔
4904
        }
3✔
4905

4906
        // Add any missing addresses for this peer to persistentPeerAddr.
4907
        for _, addr := range addrs {
6✔
4908
                if existingAddrs[addr.String()] {
3✔
4909
                        continue
×
4910
                }
4911

4912
                s.persistentPeerAddrs[pubStr] = append(
3✔
4913
                        s.persistentPeerAddrs[pubStr],
3✔
4914
                        &lnwire.NetAddress{
3✔
4915
                                IdentityKey: p.IdentityKey(),
3✔
4916
                                Address:     addr,
3✔
4917
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4918
                        },
3✔
4919
                )
3✔
4920
        }
4921

4922
        // Record the computed backoff in the backoff map.
4923
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4924
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4925

3✔
4926
        // Initialize a retry canceller for this peer if one does not
3✔
4927
        // exist.
3✔
4928
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4929
        if !ok {
6✔
4930
                cancelChan = make(chan struct{})
3✔
4931
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4932
        }
3✔
4933

4934
        // We choose not to wait group this go routine since the Connect
4935
        // call can stall for arbitrarily long if we shutdown while an
4936
        // outbound connection attempt is being made.
4937
        go func() {
6✔
4938
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4939
                        "re-establishment to persistent peer",
3✔
4940
                        "reconnecting_in", backoff)
3✔
4941

3✔
4942
                select {
3✔
4943
                case <-time.After(backoff):
3✔
4944
                case <-cancelChan:
3✔
4945
                        return
3✔
4946
                case <-s.quit:
3✔
4947
                        return
3✔
4948
                }
4949

4950
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4951
                        "connection")
3✔
4952

3✔
4953
                s.connectToPersistentPeer(pubStr)
3✔
4954
        }()
4955
}
4956

4957
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4958
// to connect to the peer. It creates connection requests if there are
4959
// currently none for a given address and it removes old connection requests
4960
// if the associated address is no longer in the latest address list for the
4961
// peer.
4962
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4963
        s.mu.Lock()
3✔
4964
        defer s.mu.Unlock()
3✔
4965

3✔
4966
        // Create an easy lookup map of the addresses we have stored for the
3✔
4967
        // peer. We will remove entries from this map if we have existing
3✔
4968
        // connection requests for the associated address and then any leftover
3✔
4969
        // entries will indicate which addresses we should create new
3✔
4970
        // connection requests for.
3✔
4971
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4972
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4973
                addrMap[addr.String()] = addr
3✔
4974
        }
3✔
4975

4976
        // Go through each of the existing connection requests and
4977
        // check if they correspond to the latest set of addresses. If
4978
        // there is a connection requests that does not use one of the latest
4979
        // advertised addresses then remove that connection request.
4980
        var updatedConnReqs []*connmgr.ConnReq
3✔
4981
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4982
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4983

3✔
4984
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4985
                // If the existing connection request is using one of the
4986
                // latest advertised addresses for the peer then we add it to
4987
                // updatedConnReqs and remove the associated address from
4988
                // addrMap so that we don't recreate this connReq later on.
4989
                case true:
×
4990
                        updatedConnReqs = append(
×
4991
                                updatedConnReqs, connReq,
×
4992
                        )
×
4993
                        delete(addrMap, lnAddr)
×
4994

4995
                // If the existing connection request is using an address that
4996
                // is not one of the latest advertised addresses for the peer
4997
                // then we remove the connecting request from the connection
4998
                // manager.
4999
                case false:
3✔
5000
                        srvrLog.Info(
3✔
5001
                                "Removing conn req:", connReq.Addr.String(),
3✔
5002
                        )
3✔
5003
                        s.connMgr.Remove(connReq.ID())
3✔
5004
                }
5005
        }
5006

5007
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
5008

3✔
5009
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
5010
        if !ok {
6✔
5011
                cancelChan = make(chan struct{})
3✔
5012
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
5013
        }
3✔
5014

5015
        // Any addresses left in addrMap are new ones that we have not made
5016
        // connection requests for. So create new connection requests for those.
5017
        // If there is more than one address in the address map, stagger the
5018
        // creation of the connection requests for those.
5019
        go func() {
6✔
5020
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
5021
                defer ticker.Stop()
3✔
5022

3✔
5023
                for _, addr := range addrMap {
6✔
5024
                        // Send the persistent connection request to the
3✔
5025
                        // connection manager, saving the request itself so we
3✔
5026
                        // can cancel/restart the process as needed.
3✔
5027
                        connReq := &connmgr.ConnReq{
3✔
5028
                                Addr:      addr,
3✔
5029
                                Permanent: true,
3✔
5030
                        }
3✔
5031

3✔
5032
                        s.mu.Lock()
3✔
5033
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
5034
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
5035
                        )
3✔
5036
                        s.mu.Unlock()
3✔
5037

3✔
5038
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
5039
                                "channel peer %v", addr)
3✔
5040

3✔
5041
                        go s.connMgr.Connect(connReq)
3✔
5042

3✔
5043
                        select {
3✔
5044
                        case <-s.quit:
3✔
5045
                                return
3✔
5046
                        case <-cancelChan:
3✔
5047
                                return
3✔
5048
                        case <-ticker.C:
3✔
5049
                        }
5050
                }
5051
        }()
5052
}
5053

5054
// removePeerUnsafe removes the passed peer from the server's state of all
5055
// active peers.
5056
//
5057
// NOTE: Server mutex must be held when calling this function.
5058
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
5059
        if p == nil {
3✔
5060
                return
×
5061
        }
×
5062

5063
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5064

3✔
5065
        // Exit early if we have already been instructed to shutdown, the peers
3✔
5066
        // will be disconnected in the server shutdown process.
3✔
5067
        if s.Stopped() {
3✔
5068
                return
×
5069
        }
×
5070

5071
        // Capture the peer's public key and string representation.
5072
        pKey := p.PubKey()
3✔
5073
        pubSer := pKey[:]
3✔
5074
        pubStr := string(pubSer)
3✔
5075

3✔
5076
        delete(s.peersByPub, pubStr)
3✔
5077

3✔
5078
        if p.Inbound() {
6✔
5079
                delete(s.inboundPeers, pubStr)
3✔
5080
        } else {
6✔
5081
                delete(s.outboundPeers, pubStr)
3✔
5082
        }
3✔
5083

5084
        // When removing the peer we make sure to disconnect it asynchronously
5085
        // to avoid blocking the main server goroutine because it is holding the
5086
        // server's mutex. Disconnecting the peer might block and wait until the
5087
        // peer has fully started up. This can happen if an inbound and outbound
5088
        // race condition occurs.
5089
        s.wg.Add(1)
3✔
5090
        go func() {
6✔
5091
                defer s.wg.Done()
3✔
5092

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

3✔
5095
                // If this peer had an active persistent connection request,
3✔
5096
                // remove it.
3✔
5097
                if p.ConnReq() != nil {
6✔
5098
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5099
                }
3✔
5100

5101
                // Remove the peer's access permission from the access manager.
5102
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5103
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5104

3✔
5105
                // Copy the peer's error buffer across to the server if it has
3✔
5106
                // any items in it so that we can restore peer errors across
3✔
5107
                // connections. We need to look up the error after the peer has
3✔
5108
                // been disconnected because we write the error in the
3✔
5109
                // `Disconnect` method.
3✔
5110
                s.mu.Lock()
3✔
5111
                if p.ErrorBuffer().Total() > 0 {
6✔
5112
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5113
                }
3✔
5114
                s.mu.Unlock()
3✔
5115

3✔
5116
                // Inform the peer notifier of a peer offline event so that it
3✔
5117
                // can be reported to clients listening for peer events.
3✔
5118
                var pubKey [33]byte
3✔
5119
                copy(pubKey[:], pubSer)
3✔
5120

3✔
5121
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5122
        }()
5123
}
5124

5125
// ConnectToPeer requests that the server connect to a Lightning Network peer
5126
// at the specified address. This function will *block* until either a
5127
// connection is established, or the initial handshake process fails.
5128
//
5129
// NOTE: This function is safe for concurrent access.
5130
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5131
        perm bool, timeout time.Duration) error {
3✔
5132

3✔
5133
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5134

3✔
5135
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5136
        // better granularity.  In certain conditions, this method requires
3✔
5137
        // making an outbound connection to a remote peer, which requires the
3✔
5138
        // lock to be released, and subsequently reacquired.
3✔
5139
        s.mu.Lock()
3✔
5140

3✔
5141
        // Ensure we're not already connected to this peer.
3✔
5142
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5143

3✔
5144
        // When there's no error it means we already have a connection with this
3✔
5145
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5146
        // set, we will ignore the existing connection and continue.
3✔
5147
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5148
                s.mu.Unlock()
3✔
5149
                return &errPeerAlreadyConnected{peer: peer}
3✔
5150
        }
3✔
5151

5152
        // Peer was not found, continue to pursue connection with peer.
5153

5154
        // If there's already a pending connection request for this pubkey,
5155
        // then we ignore this request to ensure we don't create a redundant
5156
        // connection.
5157
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5158
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5159
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5160
        }
3✔
5161

5162
        // If there's not already a pending or active connection to this node,
5163
        // then instruct the connection manager to attempt to establish a
5164
        // persistent connection to the peer.
5165
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5166
        if perm {
6✔
5167
                connReq := &connmgr.ConnReq{
3✔
5168
                        Addr:      addr,
3✔
5169
                        Permanent: true,
3✔
5170
                }
3✔
5171

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

3✔
5185
                go s.connMgr.Connect(connReq)
3✔
5186

3✔
5187
                return nil
3✔
5188
        }
5189
        s.mu.Unlock()
3✔
5190

3✔
5191
        // If we're not making a persistent connection, then we'll attempt to
3✔
5192
        // connect to the target peer. If the we can't make the connection, or
3✔
5193
        // the crypto negotiation breaks down, then return an error to the
3✔
5194
        // caller.
3✔
5195
        errChan := make(chan error, 1)
3✔
5196
        s.connectToPeer(addr, errChan, timeout)
3✔
5197

3✔
5198
        select {
3✔
5199
        case err := <-errChan:
3✔
5200
                return err
3✔
5201
        case <-s.quit:
×
5202
                return ErrServerShuttingDown
×
5203
        }
5204
}
5205

5206
// connectToPeer establishes a connection to a remote peer. errChan is used to
5207
// notify the caller if the connection attempt has failed. Otherwise, it will be
5208
// closed.
5209
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5210
        errChan chan<- error, timeout time.Duration) {
3✔
5211

3✔
5212
        conn, err := brontide.Dial(
3✔
5213
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5214
        )
3✔
5215
        if err != nil {
6✔
5216
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5217
                select {
3✔
5218
                case errChan <- err:
3✔
5219
                case <-s.quit:
×
5220
                }
5221
                return
3✔
5222
        }
5223

5224
        close(errChan)
3✔
5225

3✔
5226
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5227
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5228

3✔
5229
        s.OutboundPeerConnected(nil, conn)
3✔
5230
}
5231

5232
// DisconnectPeer sends the request to server to close the connection with peer
5233
// identified by public key.
5234
//
5235
// NOTE: This function is safe for concurrent access.
5236
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5237
        pubBytes := pubKey.SerializeCompressed()
3✔
5238
        pubStr := string(pubBytes)
3✔
5239

3✔
5240
        s.mu.Lock()
3✔
5241
        defer s.mu.Unlock()
3✔
5242

3✔
5243
        // Check that were actually connected to this peer. If not, then we'll
3✔
5244
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5245
        // currently connected to.
3✔
5246
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5247
        if err == ErrPeerNotConnected {
6✔
5248
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5249
        }
3✔
5250

5251
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5252

3✔
5253
        s.cancelConnReqs(pubStr, nil)
3✔
5254

3✔
5255
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5256
        // them from this map so we don't attempt to re-connect after we
3✔
5257
        // disconnect.
3✔
5258
        delete(s.persistentPeers, pubStr)
3✔
5259
        delete(s.persistentPeersBackoff, pubStr)
3✔
5260

3✔
5261
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5262
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5263
        //
3✔
5264
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5265
        // goroutine because we might hold the server's mutex.
3✔
5266
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5267

3✔
5268
        return nil
3✔
5269
}
5270

5271
// OpenChannel sends a request to the server to open a channel to the specified
5272
// peer identified by nodeKey with the passed channel funding parameters.
5273
//
5274
// NOTE: This function is safe for concurrent access.
5275
func (s *server) OpenChannel(
5276
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5277

3✔
5278
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5279
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5280
        // not blocked if the caller is not reading the updates.
3✔
5281
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5282
        req.Err = make(chan error, 1)
3✔
5283

3✔
5284
        // First attempt to locate the target peer to open a channel with, if
3✔
5285
        // we're unable to locate the peer then this request will fail.
3✔
5286
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5287
        s.mu.RLock()
3✔
5288
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5289
        if !ok {
3✔
5290
                s.mu.RUnlock()
×
5291

×
5292
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5293
                return req.Updates, req.Err
×
5294
        }
×
5295
        req.Peer = peer
3✔
5296
        s.mu.RUnlock()
3✔
5297

3✔
5298
        // We'll wait until the peer is active before beginning the channel
3✔
5299
        // opening process.
3✔
5300
        select {
3✔
5301
        case <-peer.ActiveSignal():
3✔
5302
        case <-peer.QuitSignal():
×
5303
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5304
                return req.Updates, req.Err
×
5305
        case <-s.quit:
×
5306
                req.Err <- ErrServerShuttingDown
×
5307
                return req.Updates, req.Err
×
5308
        }
5309

5310
        // If the fee rate wasn't specified at this point we fail the funding
5311
        // because of the missing fee rate information. The caller of the
5312
        // `OpenChannel` method needs to make sure that default values for the
5313
        // fee rate are set beforehand.
5314
        if req.FundingFeePerKw == 0 {
3✔
5315
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5316
                        "the channel opening transaction")
×
5317

×
5318
                return req.Updates, req.Err
×
5319
        }
×
5320

5321
        // Spawn a goroutine to send the funding workflow request to the funding
5322
        // manager. This allows the server to continue handling queries instead
5323
        // of blocking on this request which is exported as a synchronous
5324
        // request to the outside world.
5325
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5326

3✔
5327
        return req.Updates, req.Err
3✔
5328
}
5329

5330
// Peers returns a slice of all active peers.
5331
//
5332
// NOTE: This function is safe for concurrent access.
5333
func (s *server) Peers() []*peer.Brontide {
3✔
5334
        s.mu.RLock()
3✔
5335
        defer s.mu.RUnlock()
3✔
5336

3✔
5337
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5338
        for _, peer := range s.peersByPub {
6✔
5339
                peers = append(peers, peer)
3✔
5340
        }
3✔
5341

5342
        return peers
3✔
5343
}
5344

5345
// computeNextBackoff uses a truncated exponential backoff to compute the next
5346
// backoff using the value of the exiting backoff. The returned duration is
5347
// randomized in either direction by 1/20 to prevent tight loops from
5348
// stabilizing.
5349
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5350
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5351
        nextBackoff := 2 * currBackoff
3✔
5352
        if nextBackoff > maxBackoff {
6✔
5353
                nextBackoff = maxBackoff
3✔
5354
        }
3✔
5355

5356
        // Using 1/10 of our duration as a margin, compute a random offset to
5357
        // avoid the nodes entering connection cycles.
5358
        margin := nextBackoff / 10
3✔
5359

3✔
5360
        var wiggle big.Int
3✔
5361
        wiggle.SetUint64(uint64(margin))
3✔
5362
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5363
                // Randomizing is not mission critical, so we'll just return the
×
5364
                // current backoff.
×
5365
                return nextBackoff
×
5366
        }
×
5367

5368
        // Otherwise add in our wiggle, but subtract out half of the margin so
5369
        // that the backoff can tweaked by 1/20 in either direction.
5370
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5371
}
5372

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

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

3✔
5381
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5382
        if err != nil {
3✔
5383
                return nil, err
×
5384
        }
×
5385

5386
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5387
        if err != nil {
6✔
5388
                return nil, err
3✔
5389
        }
3✔
5390

5391
        if len(node.Addresses) == 0 {
6✔
5392
                return nil, errNoAdvertisedAddr
3✔
5393
        }
3✔
5394

5395
        return node.Addresses, nil
3✔
5396
}
5397

5398
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5399
// channel update for a target channel.
5400
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5401
        *lnwire.ChannelUpdate1, error) {
3✔
5402

3✔
5403
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5404
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5405
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5406
                if err != nil {
6✔
5407
                        return nil, err
3✔
5408
                }
3✔
5409

5410
                return netann.ExtractChannelUpdate(
3✔
5411
                        ourPubKey[:], info, edge1, edge2,
3✔
5412
                )
3✔
5413
        }
5414
}
5415

5416
// applyChannelUpdate applies the channel update to the different sub-systems of
5417
// the server. The useAlias boolean denotes whether or not to send an alias in
5418
// place of the real SCID.
5419
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5420
        op *wire.OutPoint, useAlias bool) error {
3✔
5421

3✔
5422
        var (
3✔
5423
                peerAlias    *lnwire.ShortChannelID
3✔
5424
                defaultAlias lnwire.ShortChannelID
3✔
5425
        )
3✔
5426

3✔
5427
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5428

3✔
5429
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5430
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5431
        if useAlias {
6✔
5432
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5433
                if foundAlias != defaultAlias {
6✔
5434
                        peerAlias = &foundAlias
3✔
5435
                }
3✔
5436
        }
5437

5438
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5439
                update, discovery.RemoteAlias(peerAlias),
3✔
5440
        )
3✔
5441
        select {
3✔
5442
        case err := <-errChan:
3✔
5443
                return err
3✔
5444
        case <-s.quit:
×
5445
                return ErrServerShuttingDown
×
5446
        }
5447
}
5448

5449
// SendCustomMessage sends a custom message to the peer with the specified
5450
// pubkey.
5451
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5452
        data []byte) error {
3✔
5453

3✔
5454
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5455
        if err != nil {
6✔
5456
                return err
3✔
5457
        }
3✔
5458

5459
        // We'll wait until the peer is active.
5460
        select {
3✔
5461
        case <-peer.ActiveSignal():
3✔
5462
        case <-peer.QuitSignal():
×
5463
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5464
        case <-s.quit:
×
5465
                return ErrServerShuttingDown
×
5466
        }
5467

5468
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5469
        if err != nil {
6✔
5470
                return err
3✔
5471
        }
3✔
5472

5473
        // Send the message as low-priority. For now we assume that all
5474
        // application-defined message are low priority.
5475
        return peer.SendMessageLazy(true, msg)
3✔
5476
}
5477

5478
// newSweepPkScriptGen creates closure that generates a new public key script
5479
// which should be used to sweep any funds into the on-chain wallet.
5480
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5481
// (p2wkh) output.
5482
func newSweepPkScriptGen(
5483
        wallet lnwallet.WalletController,
5484
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5485

3✔
5486
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5487
                sweepAddr, err := wallet.NewAddress(
3✔
5488
                        lnwallet.TaprootPubkey, false,
3✔
5489
                        lnwallet.DefaultAccountName,
3✔
5490
                )
3✔
5491
                if err != nil {
3✔
5492
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5493
                }
×
5494

5495
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5496
                if err != nil {
3✔
5497
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5498
                }
×
5499

5500
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5501
                        wallet, netParams, addr,
3✔
5502
                )
3✔
5503
                if err != nil {
3✔
5504
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5505
                }
×
5506

5507
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5508
                        DeliveryAddress: addr,
3✔
5509
                        InternalKey:     internalKeyDesc,
3✔
5510
                })
3✔
5511
        }
5512
}
5513

5514
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5515
// finished.
5516
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5517
        // Get a list of closed channels.
3✔
5518
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5519
        if err != nil {
3✔
5520
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5521
                return nil
×
5522
        }
×
5523

5524
        // Save the SCIDs in a map.
5525
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5526
        for _, c := range channels {
6✔
5527
                // If the channel is not pending, its FC has been finalized.
3✔
5528
                if !c.IsPending {
6✔
5529
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5530
                }
3✔
5531
        }
5532

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

5547
        for _, c := range pendings {
6✔
5548
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5549
                        continue
3✔
5550
                }
5551

5552
                // If the channel is still reported as pending, remove it from
5553
                // the map.
5554
                delete(closedSCIDs, c.ShortChannelID)
×
5555

×
5556
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5557
                        c.ShortChannelID)
×
5558
        }
5559

5560
        return closedSCIDs
3✔
5561
}
5562

5563
// getStartingBeat returns the current beat. This is used during the startup to
5564
// initialize blockbeat consumers.
5565
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5566
        // beat is the current blockbeat.
3✔
5567
        var beat *chainio.Beat
3✔
5568

3✔
5569
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5570
        // we will skip fetching the best block.
3✔
5571
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5572
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5573
                        "mode")
×
5574

×
5575
                return &chainio.Beat{}, nil
×
5576
        }
×
5577

5578
        // We should get a notification with the current best block immediately
5579
        // by passing a nil block.
5580
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5581
        if err != nil {
3✔
5582
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5583
        }
×
5584
        defer blockEpochs.Cancel()
3✔
5585

3✔
5586
        // We registered for the block epochs with a nil request. The notifier
3✔
5587
        // should send us the current best block immediately. So we need to
3✔
5588
        // wait for it here because we need to know the current best height.
3✔
5589
        select {
3✔
5590
        case bestBlock := <-blockEpochs.Epochs:
3✔
5591
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5592
                        bestBlock.Hash, bestBlock.Height)
3✔
5593

3✔
5594
                // Update the current blockbeat.
3✔
5595
                beat = chainio.NewBeat(*bestBlock)
3✔
5596

5597
        case <-s.quit:
×
5598
                srvrLog.Debug("LND shutting down")
×
5599
        }
5600

5601
        return beat, nil
3✔
5602
}
5603

5604
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5605
// point has an active RBF chan closer.
5606
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5607
        chanPoint wire.OutPoint) bool {
3✔
5608

3✔
5609
        pubBytes := peerPub.SerializeCompressed()
3✔
5610

3✔
5611
        s.mu.RLock()
3✔
5612
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5613
        s.mu.RUnlock()
3✔
5614
        if !ok {
3✔
5615
                return false
×
5616
        }
×
5617

5618
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5619
}
5620

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

3✔
5629
        // First, we'll attempt to look up the channel based on it's
3✔
5630
        // ChannelPoint.
3✔
5631
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5632
        if err != nil {
3✔
5633
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5634
        }
×
5635

5636
        // From the channel, we can now get the pubkey of the peer, then use
5637
        // that to eventually get the chan closer.
5638
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5639

3✔
5640
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5641
        s.mu.RLock()
3✔
5642
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5643
        s.mu.RUnlock()
3✔
5644
        if !ok {
3✔
5645
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5646
                        "not online", chanPoint)
×
5647
        }
×
5648

5649
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5650
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5651
        )
3✔
5652
        if err != nil {
3✔
5653
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5654
                        "%w", err)
×
5655
        }
×
5656

5657
        return closeUpdates, nil
3✔
5658
}
5659

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

3✔
5668
        // If the channel is present in the switch, then the request should flow
3✔
5669
        // through the switch instead.
3✔
5670
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5671
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5672
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5673
                        "invalid request", chanPoint)
×
5674
        }
×
5675

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

5686
        return updates, nil
3✔
5687
}
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