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

lightningnetwork / lnd / 16529627948

25 Jul 2025 07:05PM UTC coverage: 67.245% (+0.04%) from 67.206%
16529627948

Pull #9455

github

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

131 of 179 new or added lines in 6 files covered. (73.18%)

59 existing lines in 16 files now uncovered.

135645 of 201717 relevant lines covered (67.25%)

21649.94 hits per line

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

69.51
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

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

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

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

418
        customMessageServer *subscribe.Server
419

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

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

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

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

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

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

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

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

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

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

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

490
                                        s.mu.Lock()
3✔
491

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

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

506
                                        s.mu.Unlock()
3✔
507

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

514
        return nil
3✔
515
}
516

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

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

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

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

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

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

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

569
        // Check if that DNS address resolve to any TCP addresses.
570
        if _, err = netCfg.ResolveTCPAddr("tcp", addr.String()); err != nil {
3✔
NEW
571
                return nil, err
×
NEW
572
        }
×
573

574
        return addr, nil
3✔
575
}
576

577
// isIP checks if the provided host is an IP address (IPv4 or IPv6).
578
func isIP(host string) bool {
3✔
579
        // Try parsing the host as an IP address.
3✔
580
        ip := net.ParseIP(host)
3✔
581
        return ip != nil
3✔
582
}
3✔
583

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

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

598
        return dnsAddr, nil
3✔
599
}
600

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

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

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

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

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

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

3✔
639
        netParams := cfg.ActiveNetParams.Params
3✔
640

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

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

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

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

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

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

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

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

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

3✔
710
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
711

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

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

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

3✔
737
                listenAddrs: listenAddrs,
3✔
738

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

3✔
743
                torController: torController,
3✔
744

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

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

3✔
761
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
762

3✔
763
                customMessageServer: subscribe.NewServer(),
3✔
764

3✔
765
                tlsManager: tlsManager,
3✔
766

3✔
767
                featureMgr: featureMgr,
3✔
768
                quit:       make(chan struct{}),
3✔
769
        }
3✔
770

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

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

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

3✔
795
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
796

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

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

806
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
807

3✔
808
                return nil
3✔
809
        }
810

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

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

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

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

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

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

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

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

×
897
                discoveryTimeout := time.Duration(10 * time.Second)
×
898

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

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

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

925
                        s.natTraversal = pmp
×
926
                }
927
        }
928

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

×
944
                        listenPorts = append(listenPorts, uint16(port))
×
945
                }
×
946

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

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

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

977
        selfAddrs := make([]net.Addr, 0, addrsLen)
3✔
978
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
979

3✔
980
        if cfg.ExternalDNSAddress != nil {
6✔
981
                selfAddrs = append(selfAddrs, cfg.ExternalDNSAddress)
3✔
982
        }
3✔
983

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1101
                        estimator, err = routing.NewAprioriEstimator(
3✔
1102
                                aprioriConfig,
3✔
1103
                        )
3✔
1104
                        if err != nil {
3✔
1105
                                return nil, err
×
1106
                        }
×
1107

1108
                case routing.BimodalEstimatorName:
×
1109
                        bCfg := routingConfig.BimodalConfig
×
1110
                        bimodalConfig := routing.BimodalConfig{
×
1111
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1112
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1113
                                        bCfg.Scale,
×
1114
                                ),
×
1115
                                BimodalDecayTime: bCfg.DecayTime,
×
1116
                        }
×
1117

×
1118
                        estimator, err = routing.NewBimodalEstimator(
×
1119
                                bimodalConfig,
×
1120
                        )
×
1121
                        if err != nil {
×
1122
                                return nil, err
×
1123
                        }
×
1124

1125
                default:
×
1126
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1127
                                routingConfig.ProbabilityEstimatorType)
×
1128
                }
1129
        }
1130

1131
        mcCfg := &routing.MissionControlConfig{
3✔
1132
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1133
                Estimator:               estimator,
3✔
1134
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1135
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1136
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1137
        }
3✔
1138

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

1154
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1155
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1156
                int64(routingConfig.AttemptCost),
3✔
1157
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1158
                routingConfig.MinRouteProbability)
3✔
1159

3✔
1160
        pathFindingConfig := routing.PathFindingConfig{
3✔
1161
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1162
                        routingConfig.AttemptCost,
3✔
1163
                ),
3✔
1164
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1165
                MinProbability: routingConfig.MinRouteProbability,
3✔
1166
        }
3✔
1167

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

3✔
1180
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1181

3✔
1182
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1183

3✔
1184
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1185
                cfg.Routing.StrictZombiePruning
3✔
1186

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

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

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

1234
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1235

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

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

1280
        accessCfg := &accessManConfig{
3✔
1281
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1282
                        error) {
6✔
1283

3✔
1284
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1285
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1286
                                genesisHash[:],
3✔
1287
                        )
3✔
1288
                },
3✔
1289
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1290
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1291
        }
1292

1293
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1294
        if err != nil {
3✔
1295
                return nil, err
×
1296
        }
×
1297

1298
        s.peerAccessMan = peerAccessMan
3✔
1299

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

3✔
1310
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1311
                                func(c *models.ChannelEdgeInfo,
3✔
1312
                                        e *models.ChannelEdgePolicy,
3✔
1313
                                        _ *models.ChannelEdgePolicy) error {
6✔
1314

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

×
1327
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1328
                },
×
1329
        }
1330

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

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

1347
        aggregator := sweep.NewBudgetAggregator(
3✔
1348
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1349
                s.implCfg.AuxSweeper,
3✔
1350
        )
3✔
1351

3✔
1352
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1353
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1354
                Wallet:     cc.Wallet,
3✔
1355
                Estimator:  cc.FeeEstimator,
3✔
1356
                Notifier:   cc.ChainNotifier,
3✔
1357
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1358
        })
3✔
1359

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

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

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

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

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

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

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

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

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

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

1486
                                // If the BreachArbitrator successfully handled
1487
                                // the event, we can signal that the handoff
1488
                                // was successful.
1489
                                finalErr <- nil
3✔
1490
                        }
1491

1492
                        event := &contractcourt.ContractBreachEvent{
3✔
1493
                                ChanPoint:         chanPoint,
3✔
1494
                                ProcessACK:        processACK,
3✔
1495
                                BreachRetribution: breachRet,
3✔
1496
                        }
3✔
1497

3✔
1498
                        // Send the contract breach event to the
3✔
1499
                        // BreachArbitrator.
3✔
1500
                        select {
3✔
1501
                        case contractBreaches <- event:
3✔
1502
                        case <-s.quit:
×
1503
                                return ErrServerShuttingDown
×
1504
                        }
1505

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

1531
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1532
                QueryIncomingCircuit: func(
1533
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1534

3✔
1535
                        // Get the circuit map.
3✔
1536
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1537

3✔
1538
                        // Lookup the outgoing circuit.
3✔
1539
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1540
                        if pc == nil {
5✔
1541
                                return nil
2✔
1542
                        }
2✔
1543

1544
                        return &pc.Incoming
3✔
1545
                },
1546
                AuxLeafStore: implCfg.AuxLeafStore,
1547
                AuxSigner:    implCfg.AuxSigner,
1548
                AuxResolver:  implCfg.AuxContractResolver,
1549
        }, dbs.ChanStateDB)
1550

1551
        // Select the configuration and funding parameters for Bitcoin.
1552
        chainCfg := cfg.Bitcoin
3✔
1553
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1554
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1555

3✔
1556
        var chanIDSeed [32]byte
3✔
1557
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1558
                return nil, err
×
1559
        }
×
1560

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

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

1579
                // Grab our key to find our policy.
1580
                var ourKey [33]byte
3✔
1581
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1582

3✔
1583
                var ourPolicy *models.ChannelEdgePolicy
3✔
1584
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1585
                        ourPolicy = e1
3✔
1586
                } else {
6✔
1587
                        ourPolicy = e2
3✔
1588
                }
3✔
1589

1590
                if ourPolicy == nil {
3✔
1591
                        // Something is wrong, so return an error.
×
1592
                        return nil, fmt.Errorf("we don't have an edge")
×
1593
                }
×
1594

1595
                err = s.graphDB.DeleteChannelEdges(
3✔
1596
                        false, false, scid.ToUint64(),
3✔
1597
                )
3✔
1598
                return ourPolicy, err
3✔
1599
        }
1600

1601
        // For the reservationTimeout and the zombieSweeperInterval different
1602
        // values are set in case we are in a dev environment so enhance test
1603
        // capacilities.
1604
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1605
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1606

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

3✔
1617
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1618
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1619

3✔
1620
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1621
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1622
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1623
        }
3✔
1624

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

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

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

1671
                        minConf := uint64(3)
×
1672
                        maxConf := uint64(6)
×
1673

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

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

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

1710
                        // If this is a wumbo channel, then we'll require the
1711
                        // max value.
1712
                        if chanAmt > MaxFundingAmount {
×
1713
                                return maxRemoteDelay
×
1714
                        }
×
1715

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

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

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

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

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

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

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

1829
        // Assemble a peer notifier which will provide clients with subscriptions
1830
        // to peer online and offline events.
1831
        s.peerNotifier = peernotifier.New()
3✔
1832

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

1848
        if cfg.WtClient.Active {
6✔
1849
                policy := wtpolicy.DefaultPolicy()
3✔
1850
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1851

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

3✔
1858
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1859

3✔
1860
                if err := policy.Validate(); err != nil {
3✔
1861
                        return nil, err
×
1862
                }
×
1863

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

3✔
1870
                        return brontide.Dial(
3✔
1871
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1872
                        )
3✔
1873
                }
3✔
1874

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

3✔
1882
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1883
                                nil, chanID,
3✔
1884
                        )
3✔
1885
                        if err != nil {
3✔
1886
                                return nil, 0, err
×
1887
                        }
×
1888

1889
                        br, err := lnwallet.NewBreachRetribution(
3✔
1890
                                channel, commitHeight, 0, nil,
3✔
1891
                                implCfg.AuxLeafStore,
3✔
1892
                                implCfg.AuxContractResolver,
3✔
1893
                        )
3✔
1894
                        if err != nil {
3✔
1895
                                return nil, 0, err
×
1896
                        }
×
1897

1898
                        return br, channel.ChanType, nil
3✔
1899
                }
1900

1901
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1902

3✔
1903
                // Copy the policy for legacy channels and set the blob flag
3✔
1904
                // signalling support for anchor channels.
3✔
1905
                anchorPolicy := policy
3✔
1906
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1907

3✔
1908
                // Copy the policy for legacy channels and set the blob flag
3✔
1909
                // signalling support for taproot channels.
3✔
1910
                taprootPolicy := policy
3✔
1911
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1912
                        blob.FlagTaprootChannel,
3✔
1913
                )
3✔
1914

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

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

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

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

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

×
1971
                                        return s.genNodeAnnouncement(
×
1972
                                                nil, modifier...,
×
1973
                                        )
×
1974
                                }),
×
1975
                })
1976
        }
1977

1978
        // Create liveness monitor.
1979
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1980

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

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

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

3✔
2018
        // Finally, register the subsystems in blockbeat.
3✔
2019
        s.registerBlockConsumers()
3✔
2020

3✔
2021
        return s, nil
3✔
2022
}
2023

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

3✔
2029
        switch c := cfg.Estimator.Config().(type) {
3✔
2030
        case routing.AprioriConfig:
3✔
2031
                routerCfg.ProbabilityEstimatorType =
3✔
2032
                        routing.AprioriEstimatorName
3✔
2033

3✔
2034
                targetCfg := routerCfg.AprioriConfig
3✔
2035
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
2036
                targetCfg.Weight = c.AprioriWeight
3✔
2037
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
2038
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
2039

2040
        case routing.BimodalConfig:
3✔
2041
                routerCfg.ProbabilityEstimatorType =
3✔
2042
                        routing.BimodalEstimatorName
3✔
2043

3✔
2044
                targetCfg := routerCfg.BimodalConfig
3✔
2045
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
2046
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
2047
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
2048
        }
2049

2050
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2051
}
2052

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

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

3✔
2078
        data, err := u.DataToSign()
3✔
2079
        if err != nil {
3✔
2080
                return nil, err
×
2081
        }
×
2082

2083
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2084
}
2085

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

3✔
2099
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2100
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2101
                srvrLog.Info("Disabling chain backend checks for " +
×
2102
                        "nochainbackend mode")
×
2103

×
2104
                chainBackendAttempts = 0
×
2105
        }
×
2106

2107
        chainHealthCheck := healthcheck.NewObservation(
3✔
2108
                "chain backend",
3✔
2109
                cc.HealthCheck,
3✔
2110
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2111
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2112
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2113
                chainBackendAttempts,
3✔
2114
        )
3✔
2115

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

2126
                        // If we have more free space than we require,
2127
                        // we return a nil error.
2128
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2129
                                return nil
×
2130
                        }
×
2131

2132
                        return fmt.Errorf("require: %v free space, got: %v",
×
2133
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2134
                                free)
×
2135
                },
2136
                cfg.HealthChecks.DiskCheck.Interval,
2137
                cfg.HealthChecks.DiskCheck.Timeout,
2138
                cfg.HealthChecks.DiskCheck.Backoff,
2139
                cfg.HealthChecks.DiskCheck.Attempts,
2140
        )
2141

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

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

2166
        checks := []*healthcheck.Observation{
3✔
2167
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2168
        }
3✔
2169

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

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

3✔
2200
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2201
                        "remote signer connection",
3✔
2202
                        rpcwallet.HealthCheck(
3✔
2203
                                s.cfg.RemoteSigner,
3✔
2204

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

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

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

2244
                                if !leader {
×
2245
                                        srvrLog.Debug("Not the current leader")
×
2246
                                        return fmt.Errorf("not the current " +
×
2247
                                                "leader")
×
2248
                                }
×
2249

2250
                                return nil
×
2251
                        },
2252
                        cfg.HealthChecks.LeaderCheck.Interval,
2253
                        cfg.HealthChecks.LeaderCheck.Timeout,
2254
                        cfg.HealthChecks.LeaderCheck.Backoff,
2255
                        cfg.HealthChecks.LeaderCheck.Attempts,
2256
                )
2257

2258
                checks = append(checks, leaderCheck)
×
2259
        }
2260

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

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

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

2283
// add is used to add a cleanup function to be called when
2284
// the run function is executed.
2285
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2286
        return append(c, cleanup)
3✔
2287
}
3✔
2288

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

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

3✔
2307
        cleanup := cleaner{}
3✔
2308

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

2314
        if startErr != nil {
3✔
2315
                cleanup.run()
×
2316
        }
×
2317

2318
        return startErr
3✔
2319
}
2320

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

2333
        var startErr error
3✔
2334

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

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

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

2355
                if s.livenessMonitor != nil {
6✔
2356
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2357
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2358
                                startErr = err
×
2359
                                return
×
2360
                        }
×
2361
                }
2362

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

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

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

2386
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2387
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2388
                        startErr = err
×
2389
                        return
×
2390
                }
×
2391

2392
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2393
                if err := s.channelNotifier.Start(); err != nil {
3✔
2394
                        startErr = err
×
2395
                        return
×
2396
                }
×
2397

2398
                cleanup = cleanup.add(func() error {
3✔
2399
                        return s.peerNotifier.Stop()
×
2400
                })
×
2401
                if err := s.peerNotifier.Start(); err != nil {
3✔
2402
                        startErr = err
×
2403
                        return
×
2404
                }
×
2405

2406
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2407
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2408
                        startErr = err
×
2409
                        return
×
2410
                }
×
2411

2412
                if s.towerClientMgr != nil {
6✔
2413
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2414
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2415
                                startErr = err
×
2416
                                return
×
2417
                        }
×
2418
                }
2419

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

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

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

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

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

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

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

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

2471
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2472
                if err := s.chainArb.Start(beat); err != nil {
3✔
2473
                        startErr = err
×
2474
                        return
×
2475
                }
×
2476

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

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

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

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

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

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

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

2526
                cleanup.add(func() error {
3✔
2527
                        s.missionController.StopStoreTickers()
×
2528
                        return nil
×
2529
                })
×
2530
                s.missionController.RunStoreTickers()
3✔
2531

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

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

2573
                if s.torController != nil {
3✔
2574
                        cleanup = cleanup.add(s.torController.Stop)
×
2575
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2576
                                startErr = err
×
2577
                                return
×
2578
                        }
×
2579
                }
2580

2581
                if s.natTraversal != nil {
3✔
2582
                        s.wg.Add(1)
×
2583
                        go s.watchExternalIP()
×
2584
                }
×
2585

2586
                // Start connmgr last to prevent connections before init.
2587
                cleanup = cleanup.add(func() error {
3✔
2588
                        s.connMgr.Stop()
×
2589
                        return nil
×
2590
                })
×
2591

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

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

2621
                        peerAddr := &lnwire.NetAddress{
3✔
2622
                                IdentityKey: parsedPubkey,
3✔
2623
                                Address:     addr,
3✔
2624
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2625
                        }
3✔
2626

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

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

×
2645
                        startErr = err
×
2646
                        return
×
2647
                }
×
2648

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

×
2658
                        startErr = err
×
2659
                        return
×
2660
                }
×
2661

2662
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2663
                        srvrLog.Errorf("Failed to establish persistent "+
×
2664
                                "connections: %v", err)
×
2665
                }
×
2666

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

2676
                        result := make([][2]string, len(tuples))
×
2677
                        for idx, tuple := range tuples {
×
2678
                                tuple = strings.TrimSpace(tuple)
×
2679
                                if len(tuple) == 0 {
×
2680
                                        return
×
2681
                                }
×
2682

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

2690
                                copy(result[idx][:], servers)
×
2691
                        }
2692

2693
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2694
                }
2695

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

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

2734
                        s.wg.Add(1)
3✔
2735
                        go s.peerBootstrapper(
3✔
2736
                                ctx, defaultMinPeers, bootstrappers,
3✔
2737
                        )
3✔
2738
                } else {
3✔
2739
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2740
                }
3✔
2741

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

2753
                // Set the active flag now that we've completed the full
2754
                // startup.
2755
                atomic.StoreInt32(&s.active, 1)
3✔
2756
        })
2757

2758
        if startErr != nil {
3✔
2759
                cleanup.run()
×
2760
        }
×
2761
        return startErr
3✔
2762
}
2763

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

3✔
2772
                ctx := context.Background()
3✔
2773

3✔
2774
                close(s.quit)
3✔
2775

3✔
2776
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2777
                s.connMgr.Stop()
3✔
2778

3✔
2779
                // Stop dispatching blocks to other systems immediately.
3✔
2780
                s.blockbeatDispatcher.Stop()
3✔
2781

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

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

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

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

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

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

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

2913
                // Wait for all lingering goroutines to quit.
2914
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2915
                s.wg.Wait()
3✔
2916

3✔
2917
                srvrLog.Debug("Stopping buffer pools...")
3✔
2918
                s.sigPool.Stop()
3✔
2919
                s.writePool.Stop()
3✔
2920
                s.readPool.Stop()
3✔
2921
        })
2922

2923
        return nil
3✔
2924
}
2925

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

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

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

2951
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2952
                externalIPs = append(externalIPs, hostIP)
×
2953
        }
2954

2955
        return externalIPs, nil
×
2956
}
2957

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

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

×
2982
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2983
        // up by the server.
×
2984
        defer s.removePortForwarding()
×
2985

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

2993
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2994

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

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

3025
                        if ip.Equal(s.lastDetectedIP) {
×
3026
                                continue
×
3027
                        }
3028

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

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

3046
                                newAddrs = append(newAddrs, addr)
×
3047
                        }
3048

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

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

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

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

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

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

3101
                        // Finally, update the last IP seen to the current one.
3102
                        s.lastDetectedIP = ip
×
3103
                case <-s.quit:
×
3104
                        break out
×
3105
                }
3106
        }
3107
}
3108

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

3✔
3115
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3116

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

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

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

×
3142
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3143
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3144
                        )
×
3145
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3146
                }
×
3147
        }
3148

3149
        return bootStrappers, nil
3✔
3150
}
3151

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

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

3✔
3164
        // We should ignore ourselves from bootstrapping.
3✔
3165
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3166
        ignore[selfKey] = struct{}{}
3✔
3167

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

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

3182
        return ignore
3✔
3183
}
3184

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

3✔
3193
        defer s.wg.Done()
3✔
3194

3✔
3195
        // Before we continue, init the ignore peers map.
3✔
3196
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3197

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

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

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

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

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

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

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

3243
                        if epochAttempts > 0 &&
×
3244
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3245

×
3246
                                sampleTicker.Stop()
×
3247

×
3248
                                backOff *= 2
×
3249
                                if backOff > bootstrapBackOffCeiling {
×
3250
                                        backOff = bootstrapBackOffCeiling
×
3251
                                }
×
3252

3253
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3254
                                        "%v", backOff)
×
3255
                                sampleTicker = time.NewTicker(backOff)
×
3256
                                continue
×
3257
                        }
3258

3259
                        atomic.StoreUint32(&epochErrors, 0)
×
3260
                        epochAttempts = 0
×
3261

×
3262
                        // Since we know need more peers, we'll compute the
×
3263
                        // exact number we need to reach our threshold.
×
3264
                        numNeeded := numTargetPeers - numActivePeers
×
3265

×
3266
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3267
                                "peers", numNeeded)
×
3268

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

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

3286
                        // Finally, we'll launch a new goroutine for each
3287
                        // prospective peer candidates.
3288
                        for _, addr := range peerAddrs {
×
3289
                                epochAttempts++
×
3290

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

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

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

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

3✔
3331
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3332
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3333

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

3✔
3339
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3340
        // then the main peer bootstrap logic.
3✔
3341
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3342

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

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

3✔
3356
                if numActivePeers >= numTargetPeers {
6✔
3357
                        return
3✔
3358
                }
3✔
3359

3360
                if attempts > 0 {
3✔
3361
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3362
                                "bootstrap peers (attempt #%v)", delayTime,
×
3363
                                attempts)
×
3364

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

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

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

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

3✔
3403
                                errChan := make(chan error, 1)
3✔
3404
                                go s.connectToPeer(
3✔
3405
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3406
                                )
3✔
3407

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

3431
                wg.Wait()
3✔
3432
        }
3433
}
3434

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

3447
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3448
        if err != nil {
×
3449
                return err
×
3450
        }
×
3451

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

×
3464
        switch {
×
3465
        case s.cfg.Tor.V2:
×
3466
                onionCfg.Type = tor.V2
×
3467
        case s.cfg.Tor.V3:
×
3468
                onionCfg.Type = tor.V3
×
3469
        }
3470

3471
        addr, err := s.torController.AddOnion(onionCfg)
×
3472
        if err != nil {
×
3473
                return err
×
3474
        }
×
3475

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

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

3506
        return nil
×
3507
}
3508

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

3✔
3515
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3516
        if err != nil {
3✔
3517
                return nil, err
×
3518
        }
×
3519

3520
        for _, channel := range nodeChans {
6✔
3521
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3522
                        return channel, nil
3✔
3523
                }
3✔
3524
        }
3525

3526
        return nil, fmt.Errorf("unable to find channel")
3✔
3527
}
3528

3529
// getNodeAnnouncement fetches the current, fully signed node announcement.
3530
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3531
        s.mu.Lock()
3✔
3532
        defer s.mu.Unlock()
3✔
3533

3✔
3534
        return *s.currentNodeAnn
3✔
3535
}
3✔
3536

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

3✔
3543
        s.mu.Lock()
3✔
3544
        defer s.mu.Unlock()
3✔
3545

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

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

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

3570
        // Always update the timestamp when refreshing to ensure the update
3571
        // propagates.
3572
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3573

3✔
3574
        // Apply the requested changes to the node announcement.
3✔
3575
        for _, modifier := range modifiers {
6✔
3576
                modifier(&newNodeAnn)
3✔
3577
        }
3✔
3578

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

3587
        // If signing succeeds, update the current announcement.
3588
        *s.currentNodeAnn = newNodeAnn
3✔
3589

3✔
3590
        return *s.currentNodeAnn, nil
3✔
3591
}
3592

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

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

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

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

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

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

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

3637
        return nil
3✔
3638
}
3639

3640
type nodeAddresses struct {
3641
        pubKey    *btcec.PublicKey
3642
        addresses []net.Addr
3643
}
3644

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

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

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

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

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

3689
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3690

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

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

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

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

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

3735
                n := &nodeAddresses{
3✔
3736
                        addresses: addrs,
3✔
3737
                }
3✔
3738
                n.pubKey, err = channelPeer.PubKey()
3✔
3739
                if err != nil {
3✔
3740
                        return err
×
3741
                }
×
3742

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

×
3755
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3756
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3757

×
3758
                        return err
×
3759
                }
×
3760
        }
3761

3762
        // Combine the addresses from the link nodes and the channel graph.
3763
        for pubStr, nodeAddr := range graphAddrs {
6✔
3764
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3765
        }
3✔
3766

3767
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3768
                len(nodeAddrsMap))
3✔
3769

3✔
3770
        // Acquire and hold server lock until all persistent connection requests
3✔
3771
        // have been recorded and sent to the connection manager.
3✔
3772
        s.mu.Lock()
3✔
3773
        defer s.mu.Unlock()
3✔
3774

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

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

3✔
3798
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3799
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3800
                }
3✔
3801

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

3✔
3812
                        go s.connectToPersistentPeer(pubStr)
3✔
3813
                } else {
3✔
3814
                        go s.delayInitialReconnect(pubStr)
×
3815
                }
×
3816

3817
                numOutboundConns++
3✔
3818
        }
3819

3820
        return nil
3✔
3821
}
3822

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

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

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

3✔
3850
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3851
                        "peer has no open channels", compressedPubKey)
3✔
3852

3✔
3853
                return
3✔
3854
        }
3✔
3855
        s.mu.Unlock()
3✔
3856
}
3857

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

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

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

3898
                peers = append(peers, sPeer)
3✔
3899
        }
3900
        s.mu.RUnlock()
3✔
3901

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

3✔
3909
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3910
                wg.Add(1)
3✔
3911
                s.wg.Add(1)
3✔
3912
                go func(p lnpeer.Peer) {
6✔
3913
                        defer s.wg.Done()
3✔
3914
                        defer wg.Done()
3✔
3915

3✔
3916
                        p.SendMessageLazy(false, msgs...)
3✔
3917
                }(sPeer)
3✔
3918
        }
3919

3920
        // Wait for all messages to have been dispatched before returning to
3921
        // caller.
3922
        wg.Wait()
3✔
3923

3✔
3924
        return nil
3✔
3925
}
3926

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

3✔
3934
        s.mu.Lock()
3✔
3935

3✔
3936
        // Compute the target peer's identifier.
3✔
3937
        pubStr := string(peerKey[:])
3✔
3938

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

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

3961
                // Connected, can return early.
3962
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3963

3✔
3964
                select {
3✔
3965
                case peerChan <- peer:
3✔
3966
                case <-s.quit:
×
3967
                }
3968

3969
                return
3✔
3970
        }
3971

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

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

3✔
3987
        c := make(chan struct{})
3✔
3988

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

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

3✔
4005
        return c
3✔
4006
}
4007

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

3✔
4017
        pubStr := string(peerKey.SerializeCompressed())
3✔
4018

3✔
4019
        return s.findPeerByPubStr(pubStr)
3✔
4020
}
3✔
4021

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

3✔
4031
        return s.findPeerByPubStr(pubStr)
3✔
4032
}
3✔
4033

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

4042
        return peer, nil
3✔
4043
}
4044

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

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

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

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

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

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

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

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

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

4117
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4118
        pubSer := nodePub.SerializeCompressed()
3✔
4119
        pubStr := string(pubSer)
3✔
4120

3✔
4121
        var pubBytes [33]byte
3✔
4122
        copy(pubBytes[:], pubSer)
3✔
4123

3✔
4124
        s.mu.Lock()
3✔
4125
        defer s.mu.Unlock()
3✔
4126

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

3✔
4134
                conn.Close()
3✔
4135
                return
3✔
4136
        }
3✔
4137

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

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

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

4163
        case nil:
3✔
4164
                ctx := btclog.WithCtx(
3✔
4165
                        context.TODO(),
3✔
4166
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4167
                )
3✔
4168

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

×
4178
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4179
                                "peer, but already have outbound "+
×
4180
                                "connection, dropping conn",
×
4181
                                fmt.Errorf("already have outbound conn"))
×
4182
                        conn.Close()
×
4183
                        return
×
4184
                }
×
4185

4186
                // Otherwise, if we should drop the connection, then we'll
4187
                // disconnect our already connected peer.
4188
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4189

3✔
4190
                s.cancelConnReqs(pubStr, nil)
3✔
4191

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

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

4213
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4214
        pubSer := nodePub.SerializeCompressed()
3✔
4215
        pubStr := string(pubSer)
3✔
4216

3✔
4217
        var pubBytes [33]byte
3✔
4218
        copy(pubBytes[:], pubSer)
3✔
4219

3✔
4220
        s.mu.Lock()
3✔
4221
        defer s.mu.Unlock()
3✔
4222

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

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

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

×
4249
                if connReq != nil {
×
4250
                        s.connMgr.Remove(connReq.ID())
×
4251
                }
×
4252

4253
                conn.Close()
×
4254
                return
×
4255
        }
4256

4257
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4258
                conn.RemoteAddr())
3✔
4259

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

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

4283
        case nil:
3✔
4284
                ctx := btclog.WithCtx(
3✔
4285
                        context.TODO(),
3✔
4286
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4287
                )
3✔
4288

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

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

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

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

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

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

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

4353
        for _, connReq := range connReqs {
6✔
4354
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4355

3✔
4356
                // Atomically capture the current request identifier.
3✔
4357
                connID := connReq.ID()
3✔
4358

3✔
4359
                // Skip any zero IDs, this indicates the request has not
3✔
4360
                // yet been schedule.
3✔
4361
                if connID == UnassignedConnID {
3✔
4362
                        continue
×
4363
                }
4364

4365
                // Skip a particular connection ID if instructed.
4366
                if skip != nil && connID == *skip {
6✔
4367
                        continue
3✔
4368
                }
4369

4370
                s.connMgr.Remove(connID)
3✔
4371
        }
4372

4373
        delete(s.persistentConnReqs, pubStr)
3✔
4374
}
4375

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

3✔
4382
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4383
                Peer: peer,
3✔
4384
                Msg:  msg,
3✔
4385
        })
3✔
4386
}
3✔
4387

4388
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4389
// messages.
4390
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4391
        return s.customMessageServer.Subscribe()
3✔
4392
}
3✔
4393

4394
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4395
// the channelNotifier's NotifyOpenChannelEvent.
4396
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4397
        remotePub *btcec.PublicKey) {
3✔
4398

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

4405
        // Notify subscribers about this open channel event.
4406
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4407
}
4408

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

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

4422
        // Notify subscribers about this event.
4423
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4424
}
4425

4426
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4427
// calls the channelNotifier's NotifyFundingTimeout.
4428
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4429
        remotePub *btcec.PublicKey) {
3✔
4430

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

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

4447
        // Notify subscribers about this event.
4448
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4449
}
4450

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

3✔
4458
        brontideConn := conn.(*brontide.Conn)
3✔
4459
        addr := conn.RemoteAddr()
3✔
4460
        pubKey := brontideConn.RemotePub()
3✔
4461

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

×
4472
                // Clean up the persistent peer maps if we're dropping this
×
4473
                // connection.
×
4474
                s.bannedPersistentPeerConnection(string(pubSer))
×
4475

×
4476
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4477
                        "of restricted-access connection slots: %v.", pubSer,
×
4478
                        err)
×
4479

×
4480
                conn.Close()
×
4481

×
4482
                return
×
4483
        }
×
4484

4485
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4486
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4487

3✔
4488
        peerAddr := &lnwire.NetAddress{
3✔
4489
                IdentityKey: pubKey,
3✔
4490
                Address:     addr,
3✔
4491
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4492
        }
3✔
4493

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

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

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

4523
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4524
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4525

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

3✔
4569
                        return s.genNodeAnnouncement(nil)
3✔
4570
                },
3✔
4571

4572
                PongBuf: s.pongBuf,
4573

4574
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4575

4576
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4577

4578
                FundingManager: s.fundingMgr,
4579

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

4610
                        return clock.NewDefaultClock().Now().Before(
3✔
4611
                                EndorsementExperimentEnd,
3✔
4612
                        )
3✔
4613
                },
4614
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4615
        }
4616

4617
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4618
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4619

3✔
4620
        p := peer.NewBrontide(pCfg)
3✔
4621

3✔
4622
        // Update the access manager with the access permission for this peer.
3✔
4623
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4624

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

3✔
4628
        s.addPeer(p)
3✔
4629

3✔
4630
        // Once we have successfully added the peer to the server, we can
3✔
4631
        // delete the previous error buffer from the server's map of error
3✔
4632
        // buffers.
3✔
4633
        delete(s.peerErrors, pkStr)
3✔
4634

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

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

4649
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4650

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

×
4657
                return
×
4658
        }
×
4659

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

4665
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4666
        // be human-readable.
4667
        pubStr := string(pubBytes)
3✔
4668

3✔
4669
        s.peersByPub[pubStr] = p
3✔
4670

3✔
4671
        if p.Inbound() {
6✔
4672
                s.inboundPeers[pubStr] = p
3✔
4673
        } else {
6✔
4674
                s.outboundPeers[pubStr] = p
3✔
4675
        }
3✔
4676

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

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

3✔
4695
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4696

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

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

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

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

3✔
4723
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4724
                return
3✔
4725
        }
3✔
4726

4727
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4728
        // was successful, and to begin watching the peer's wait group.
4729
        close(ready)
3✔
4730

3✔
4731
        s.mu.Lock()
3✔
4732
        defer s.mu.Unlock()
3✔
4733

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

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

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

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

3✔
4768
        ctx := btclog.WithCtx(
3✔
4769
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4770
        )
3✔
4771

3✔
4772
        p.WaitForDisconnect(ready)
3✔
4773

3✔
4774
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4775

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

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

3✔
4789
        pubKey := p.IdentityKey()
3✔
4790

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

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

4805
        for _, link := range links {
6✔
4806
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4807
        }
3✔
4808

4809
        s.mu.Lock()
3✔
4810
        defer s.mu.Unlock()
3✔
4811

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

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

3✔
4826
                pubKey := p.PubKey()
3✔
4827
                pubStr := string(pubKey[:])
3✔
4828

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

4842
        // First, cleanup any remaining state the server has regarding the peer
4843
        // in question.
4844
        s.removePeerUnsafe(ctx, p)
3✔
4845

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

4851
        // Get the last address that we used to connect to the peer.
4852
        addrs := []net.Addr{
3✔
4853
                p.NetAddress().Address,
3✔
4854
        }
3✔
4855

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

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

4872
                // Fall back to the existing peer address if
4873
                // we're not accepting connections over Tor.
4874
                if s.torController == nil {
6✔
4875
                        break
3✔
4876
                }
4877

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

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

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

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

4908
                s.persistentPeerAddrs[pubStr] = append(
3✔
4909
                        s.persistentPeerAddrs[pubStr],
3✔
4910
                        &lnwire.NetAddress{
3✔
4911
                                IdentityKey: p.IdentityKey(),
3✔
4912
                                Address:     addr,
3✔
4913
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4914
                        },
3✔
4915
                )
3✔
4916
        }
4917

4918
        // Record the computed backoff in the backoff map.
4919
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4920
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4921

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

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

3✔
4938
                select {
3✔
4939
                case <-time.After(backoff):
3✔
4940
                case <-cancelChan:
3✔
4941
                        return
3✔
4942
                case <-s.quit:
3✔
4943
                        return
3✔
4944
                }
4945

4946
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4947
                        "connection")
3✔
4948

3✔
4949
                s.connectToPersistentPeer(pubStr)
3✔
4950
        }()
4951
}
4952

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

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

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

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

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

5003
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
5004

3✔
5005
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
5006
        if !ok {
6✔
5007
                cancelChan = make(chan struct{})
3✔
5008
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
5009
        }
3✔
5010

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

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

3✔
5028
                        s.mu.Lock()
3✔
5029
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
5030
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
5031
                        )
3✔
5032
                        s.mu.Unlock()
3✔
5033

3✔
5034
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
5035
                                "channel peer %v", addr)
3✔
5036

3✔
5037
                        go s.connMgr.Connect(connReq)
3✔
5038

3✔
5039
                        select {
3✔
5040
                        case <-s.quit:
3✔
5041
                                return
3✔
5042
                        case <-cancelChan:
3✔
5043
                                return
3✔
5044
                        case <-ticker.C:
3✔
5045
                        }
5046
                }
5047
        }()
5048
}
5049

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

5059
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5060

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

5067
        // Capture the peer's public key and string representation.
5068
        pKey := p.PubKey()
3✔
5069
        pubSer := pKey[:]
3✔
5070
        pubStr := string(pubSer)
3✔
5071

3✔
5072
        delete(s.peersByPub, pubStr)
3✔
5073

3✔
5074
        if p.Inbound() {
6✔
5075
                delete(s.inboundPeers, pubStr)
3✔
5076
        } else {
6✔
5077
                delete(s.outboundPeers, pubStr)
3✔
5078
        }
3✔
5079

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

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

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

5097
                // Remove the peer's access permission from the access manager.
5098
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5099
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5100

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

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

3✔
5117
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5118
        }()
5119
}
5120

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

3✔
5129
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5130

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

3✔
5137
        // Ensure we're not already connected to this peer.
3✔
5138
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5139

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

5148
        // Peer was not found, continue to pursue connection with peer.
5149

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

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

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

3✔
5181
                go s.connMgr.Connect(connReq)
3✔
5182

3✔
5183
                return nil
3✔
5184
        }
5185
        s.mu.Unlock()
3✔
5186

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

3✔
5194
        select {
3✔
5195
        case err := <-errChan:
3✔
5196
                return err
3✔
5197
        case <-s.quit:
×
5198
                return ErrServerShuttingDown
×
5199
        }
5200
}
5201

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

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

5220
        close(errChan)
3✔
5221

3✔
5222
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5223
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5224

3✔
5225
        s.OutboundPeerConnected(nil, conn)
3✔
5226
}
5227

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

3✔
5236
        s.mu.Lock()
3✔
5237
        defer s.mu.Unlock()
3✔
5238

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

5247
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5248

3✔
5249
        s.cancelConnReqs(pubStr, nil)
3✔
5250

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

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

3✔
5264
        return nil
3✔
5265
}
5266

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

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

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

×
5288
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5289
                return req.Updates, req.Err
×
5290
        }
×
5291
        req.Peer = peer
3✔
5292
        s.mu.RUnlock()
3✔
5293

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

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

×
5314
                return req.Updates, req.Err
×
5315
        }
×
5316

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

3✔
5323
        return req.Updates, req.Err
3✔
5324
}
5325

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

3✔
5333
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5334
        for _, peer := range s.peersByPub {
6✔
5335
                peers = append(peers, peer)
3✔
5336
        }
3✔
5337

5338
        return peers
3✔
5339
}
5340

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

5352
        // Using 1/10 of our duration as a margin, compute a random offset to
5353
        // avoid the nodes entering connection cycles.
5354
        margin := nextBackoff / 10
3✔
5355

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

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

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

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

3✔
5377
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5378
        if err != nil {
3✔
5379
                return nil, err
×
5380
        }
×
5381

5382
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5383
        if err != nil {
6✔
5384
                return nil, err
3✔
5385
        }
3✔
5386

5387
        if len(node.Addresses) == 0 {
6✔
5388
                return nil, errNoAdvertisedAddr
3✔
5389
        }
3✔
5390

5391
        return node.Addresses, nil
3✔
5392
}
5393

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

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

5406
                return netann.ExtractChannelUpdate(
3✔
5407
                        ourPubKey[:], info, edge1, edge2,
3✔
5408
                )
3✔
5409
        }
5410
}
5411

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

3✔
5418
        var (
3✔
5419
                peerAlias    *lnwire.ShortChannelID
3✔
5420
                defaultAlias lnwire.ShortChannelID
3✔
5421
        )
3✔
5422

3✔
5423
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5424

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

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

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

3✔
5450
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5451
        if err != nil {
6✔
5452
                return err
3✔
5453
        }
3✔
5454

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

5464
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5465
        if err != nil {
6✔
5466
                return err
3✔
5467
        }
3✔
5468

5469
        // Send the message as low-priority. For now we assume that all
5470
        // application-defined message are low priority.
5471
        return peer.SendMessageLazy(true, msg)
3✔
5472
}
5473

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

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

5491
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5492
                if err != nil {
3✔
5493
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5494
                }
×
5495

5496
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5497
                        wallet, netParams, addr,
3✔
5498
                )
3✔
5499
                if err != nil {
3✔
5500
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5501
                }
×
5502

5503
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5504
                        DeliveryAddress: addr,
3✔
5505
                        InternalKey:     internalKeyDesc,
3✔
5506
                })
3✔
5507
        }
5508
}
5509

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

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

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

5543
        for _, c := range pendings {
6✔
5544
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5545
                        continue
3✔
5546
                }
5547

5548
                // If the channel is still reported as pending, remove it from
5549
                // the map.
5550
                delete(closedSCIDs, c.ShortChannelID)
×
5551

×
5552
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5553
                        c.ShortChannelID)
×
5554
        }
5555

5556
        return closedSCIDs
3✔
5557
}
5558

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

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

×
5571
                return &chainio.Beat{}, nil
×
5572
        }
×
5573

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

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

3✔
5590
                // Update the current blockbeat.
3✔
5591
                beat = chainio.NewBeat(*bestBlock)
3✔
5592

5593
        case <-s.quit:
×
5594
                srvrLog.Debug("LND shutting down")
×
5595
        }
5596

5597
        return beat, nil
3✔
5598
}
5599

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

3✔
5605
        pubBytes := peerPub.SerializeCompressed()
3✔
5606

3✔
5607
        s.mu.RLock()
3✔
5608
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5609
        s.mu.RUnlock()
3✔
5610
        if !ok {
3✔
5611
                return false
×
5612
        }
×
5613

5614
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5615
}
5616

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

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

5632
        // From the channel, we can now get the pubkey of the peer, then use
5633
        // that to eventually get the chan closer.
5634
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5635

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

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

5653
        return closeUpdates, nil
3✔
5654
}
5655

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

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

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

5682
        return updates, nil
3✔
5683
}
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