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

lightningnetwork / lnd / 26282430397

22 May 2026 10:26AM UTC coverage: 62.329% (+0.03%) from 62.303%
26282430397

Pull #10789

github

web-flow
Merge ee2aa98a8 into cc49b3773
Pull Request #10789: bolt12+lnwire: add codec foundation with Offer message

549 of 678 new or added lines in 12 files covered. (80.97%)

153 existing lines in 32 files now uncovered.

144272 of 231468 relevant lines covered (62.33%)

18978.73 hits per line

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

70.09
/server.go
1
package lnd
2

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

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

92
const (
93
        // defaultMinPeers is the minimum number of peers nodes should always be
94
        // connected to.
95
        defaultMinPeers = 3
96

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

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

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

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

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

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

130
        // ErrServerShuttingDown indicates that the server is in the process of
131
        // gracefully exiting.
132
        ErrServerShuttingDown = errors.New("server is shutting down")
133

134
        // MaxFundingAmount is a soft-limit of the maximum channel size
135
        // currently accepted within the Lightning Protocol. This is
136
        // defined in BOLT-0002, and serves as an initial precautionary limit
137
        // while implementations are battle tested in the real world.
138
        //
139
        // At the moment, this value depends on which chain is active. It is set
140
        // to the value under the Bitcoin chain as default.
141
        //
142
        // TODO(roasbeef): add command line param to modify.
143
        MaxFundingAmount = funding.MaxBtcFundingAmount
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 {
4✔
175
        return fmt.Sprintf("already connected to peer: %v", e.peer)
4✔
176
}
4✔
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 {
4✔
200
        switch p {
4✔
201
        case peerStatusRestricted:
4✔
202
                return "restricted"
4✔
203

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

207
        case peerStatusProtected:
4✔
208
                return "protected"
4✔
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
        v1Graph *graphdb.VersionedGraph
328

329
        chanStateDB chanstate.Store
330
        linkNodeDB  *channeldb.LinkNodeDB
331

332
        addrSource channeldb.AddrSource
333

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

338
        invoicesDB invoices.InvoiceDB
339

340
        // paymentsDB is the DB that contains all functions for managing
341
        // payments.
342
        paymentsDB paymentsdb.DB
343

344
        aliasMgr *aliasmgr.Manager
345

346
        htlcSwitch *htlcswitch.Switch
347

348
        interceptableSwitch *htlcswitch.InterceptableSwitch
349

350
        invoices *invoices.InvoiceRegistry
351

352
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
353

354
        channelNotifier *channelnotifier.ChannelNotifier
355

356
        peerNotifier *peernotifier.PeerNotifier
357

358
        htlcNotifier *htlcswitch.HtlcNotifier
359

360
        witnessBeacon contractcourt.WitnessBeacon
361

362
        breachArbitrator *contractcourt.BreachArbitrator
363

364
        missionController *routing.MissionController
365
        defaultMC         *routing.MissionControl
366

367
        graphBuilder *graph.Builder
368

369
        chanRouter *routing.ChannelRouter
370

371
        controlTower routing.ControlTower
372

373
        authGossiper *discovery.AuthenticatedGossiper
374

375
        localChanMgr *localchans.Manager
376

377
        utxoNursery *contractcourt.UtxoNursery
378

379
        sweeper *sweep.UtxoSweeper
380

381
        chainArb *contractcourt.ChainArbitrator
382

383
        sphinxPayment *hop.OnionProcessor
384

385
        sphinxOnionMsg *sphinx.Router
386

387
        towerClientMgr *wtclient.Manager
388

389
        connMgr *connmgr.ConnManager
390

391
        sigPool *lnwallet.SigPool
392

393
        writePool *pool.Write
394

395
        readPool *pool.Read
396

397
        tlsManager *TLSManager
398

399
        // featureMgr dispatches feature vectors for various contexts within the
400
        // daemon.
401
        featureMgr *feature.Manager
402

403
        // currentNodeAnn is the node announcement that has been broadcast to
404
        // the network upon startup, if the attributes of the node (us) has
405
        // changed since last start.
406
        currentNodeAnn *lnwire.NodeAnnouncement1
407

408
        // chansToRestore is the set of channels that upon starting, the server
409
        // should attempt to restore/recover.
410
        chansToRestore walletunlocker.ChannelsToRecover
411

412
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
413
        // backups are consistent at all times. It interacts with the
414
        // channelNotifier to be notified of newly opened and closed channels.
415
        chanSubSwapper *chanbackup.SubSwapper
416

417
        // chanEventStore tracks the behaviour of channels and their remote peers to
418
        // provide insights into their health and performance.
419
        chanEventStore *chanfitness.ChannelEventStore
420

421
        hostAnn *netann.HostAnnouncer
422

423
        // livenessMonitor monitors that lnd has access to critical resources.
424
        livenessMonitor *healthcheck.Monitor
425

426
        customMessageServer *subscribe.Server
427

428
        onionMessageServer *subscribe.Server
429

430
        // actorSystem is the actor system tasked with handling actors that are
431
        // created for this server.
432
        actorSystem *actor.ActorSystem
433

434
        // onionActorFactory is a factory function that spawns per-peer onion
435
        // message actors. It captures shared dependencies and is passed to
436
        // each peer connection.
437
        onionActorFactory onionmessage.OnionActorFactory
438

439
        // defaultOnionActorOpts holds the default ActorOptions (backpressure
440
        // mailbox with RED) applied to every onion peer actor. These are
441
        // computed once during server start and returned by the per-peer
442
        // OnionActorOpts callback.
443
        defaultOnionActorOpts []actor.ActorOption[
444
                *onionmessage.Request, *onionmessage.Response,
445
        ]
446

447
        // onionLimiter is the combined per-peer + global onion message
448
        // ingress limiter. It hides the split between the two underlying
449
        // buckets behind a single interface so peer.Config only needs to
450
        // carry one field and brontide.readHandler only needs one call
451
        // per incoming onion message. Nil means onion message rate
452
        // limiting is disabled (e.g. when onion messaging itself is
453
        // turned off).
454
        onionLimiter onionmessage.IngressLimiter
455

456
        // txPublisher is a publisher with fee-bumping capability.
457
        txPublisher *sweep.TxPublisher
458

459
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
460
        // of new blocks.
461
        blockbeatDispatcher *chainio.BlockbeatDispatcher
462

463
        // peerAccessMan implements peer access controls.
464
        peerAccessMan *accessMan
465

466
        quit chan struct{}
467

468
        wg sync.WaitGroup
469
}
470

471
// updatePersistentPeerAddrs subscribes to topology changes and stores
472
// advertised addresses for any NodeAnnouncements from our persisted peers.
473
func (s *server) updatePersistentPeerAddrs() error {
4✔
474
        graphSub, err := s.graphDB.SubscribeTopology()
4✔
475
        if err != nil {
4✔
476
                return err
×
477
        }
×
478

479
        s.wg.Add(1)
4✔
480
        go func() {
8✔
481
                defer func() {
8✔
482
                        graphSub.Cancel()
4✔
483
                        s.wg.Done()
4✔
484
                }()
4✔
485

486
                for {
8✔
487
                        select {
4✔
488
                        case <-s.quit:
4✔
489
                                return
4✔
490

491
                        case topChange, ok := <-graphSub.TopologyChanges:
4✔
492
                                // If the router is shutting down, then we will
4✔
493
                                // as well.
4✔
494
                                if !ok {
4✔
495
                                        return
×
496
                                }
×
497

498
                                for _, update := range topChange.NodeUpdates {
8✔
499
                                        pubKeyStr := string(
4✔
500
                                                update.IdentityKey.
4✔
501
                                                        SerializeCompressed(),
4✔
502
                                        )
4✔
503

4✔
504
                                        // We only care about updates from
4✔
505
                                        // our persistentPeers.
4✔
506
                                        s.mu.RLock()
4✔
507
                                        _, ok := s.persistentPeers[pubKeyStr]
4✔
508
                                        s.mu.RUnlock()
4✔
509
                                        if !ok {
8✔
510
                                                continue
4✔
511
                                        }
512

513
                                        addrs := make([]*lnwire.NetAddress, 0,
4✔
514
                                                len(update.Addresses))
4✔
515

4✔
516
                                        for _, addr := range update.Addresses {
8✔
517
                                                addrs = append(addrs,
4✔
518
                                                        &lnwire.NetAddress{
4✔
519
                                                                IdentityKey: update.IdentityKey,
4✔
520
                                                                Address:     addr,
4✔
521
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
522
                                                        },
4✔
523
                                                )
4✔
524
                                        }
4✔
525

526
                                        s.mu.Lock()
4✔
527

4✔
528
                                        // Update the stored addresses for this
4✔
529
                                        // to peer to reflect the new set.
4✔
530
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
4✔
531

4✔
532
                                        // If there are no outstanding
4✔
533
                                        // connection requests for this peer
4✔
534
                                        // then our work is done since we are
4✔
535
                                        // not currently trying to connect to
4✔
536
                                        // them.
4✔
537
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
8✔
538
                                                s.mu.Unlock()
4✔
539
                                                continue
4✔
540
                                        }
541

542
                                        s.mu.Unlock()
4✔
543

4✔
544
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
545
                                }
546
                        }
547
                }
548
        }()
549

550
        return nil
4✔
551
}
552

553
// CustomMessage is a custom message that is received from a peer.
554
type CustomMessage struct {
555
        // Peer is the peer pubkey
556
        Peer [33]byte
557

558
        // Msg is the custom wire message.
559
        Msg *lnwire.Custom
560
}
561

562
// parseAddr parses an address from its string format to a net.Addr.
563
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
4✔
564
        var (
4✔
565
                host string
4✔
566
                port int
4✔
567
        )
4✔
568

4✔
569
        // Split the address into its host and port components.
4✔
570
        h, p, err := net.SplitHostPort(address)
4✔
571
        if err != nil {
4✔
572
                // If a port wasn't specified, we'll assume the address only
×
573
                // contains the host so we'll use the default port.
×
574
                host = address
×
575
                port = defaultPeerPort
×
576
        } else {
4✔
577
                // Otherwise, we'll note both the host and ports.
4✔
578
                host = h
4✔
579
                portNum, err := strconv.Atoi(p)
4✔
580
                if err != nil {
4✔
581
                        return nil, err
×
582
                }
×
583
                port = portNum
4✔
584
        }
585

586
        if tor.IsOnionHost(host) {
4✔
587
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
588
        }
×
589

590
        // If the host is part of a TCP address, we'll use the network
591
        // specific ResolveTCPAddr function in order to resolve these
592
        // addresses over Tor in order to prevent leaking your real IP
593
        // address.
594
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
4✔
595
        return netCfg.ResolveTCPAddr("tcp", hostPort)
4✔
596
}
597

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

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

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

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

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

4✔
633
        netParams := cfg.ActiveNetParams.Params
4✔
634

4✔
635
        // Initialize the sphinx router.
4✔
636
        replayLog := htlcswitch.NewDecayedLog(
4✔
637
                dbs.DecayedLogDB, cc.ChainNotifier,
4✔
638
        )
4✔
639
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
4✔
640

4✔
641
        // Initialize the onion message sphinx router. This router doesn't need
4✔
642
        // replay protection.
4✔
643
        sphinxOnionMsg := sphinx.NewRouter(
4✔
644
                nodeKeyECDH, sphinx.NewNoOpReplayLog(),
4✔
645
        )
4✔
646

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

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

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

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

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

×
670
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
671
                        "overlay channels are not supported " +
×
672
                        "in a standalone lnd build")
×
673
        }
×
674

675
        // If taproot channels are enabled, we also enable the RBF cooperative
676
        // close protocol, as it is required for taproot channel
677
        // interoperability.
678
        //
679
        // Exception: when taproot-overlay channels are enabled we do NOT
680
        // auto-enable RBF, because the RBF coop close state machine does not
681
        // yet thread through the AuxCloser hook that overlay channels rely on
682
        // to build the aux-aware close transaction. Forcing RBF on for a
683
        // node that holds overlay channels would silently break their coop
684
        // closes.
685
        if cfg.ProtocolOptions.TaprootChans &&
4✔
686
                !cfg.ProtocolOptions.TaprootOverlayChans {
8✔
687

4✔
688
                cfg.ProtocolOptions.RbfCoopClose = true
4✔
689
        }
4✔
690

691
        //nolint:ll
692
        featureMgr, err := feature.NewManager(feature.Config{
4✔
693
                NoTLVOnion:                   cfg.ProtocolOptions.LegacyOnion(),
4✔
694
                NoStaticRemoteKey:            cfg.ProtocolOptions.NoStaticRemoteKey(),
4✔
695
                NoAnchors:                    cfg.ProtocolOptions.NoAnchorCommitments(),
4✔
696
                NoWumbo:                      !cfg.ProtocolOptions.Wumbo(),
4✔
697
                NoScriptEnforcementLease:     cfg.ProtocolOptions.NoScriptEnforcementLease(),
4✔
698
                NoKeysend:                    !cfg.AcceptKeySend,
4✔
699
                NoOptionScidAlias:            !cfg.ProtocolOptions.ScidAlias(),
4✔
700
                NoZeroConf:                   !cfg.ProtocolOptions.ZeroConf(),
4✔
701
                NoAnySegwit:                  cfg.ProtocolOptions.NoAnySegwit(),
4✔
702
                CustomFeatures:               cfg.ProtocolOptions.CustomFeatures(),
4✔
703
                NoTaprootChans:               !cfg.ProtocolOptions.TaprootChans,
4✔
704
                NoTaprootOverlay:             !cfg.ProtocolOptions.TaprootOverlayChans,
4✔
705
                NoRouteBlinding:              cfg.ProtocolOptions.NoRouteBlinding(),
4✔
706
                NoOnionMessages:              cfg.ProtocolOptions.NoOnionMessages(),
4✔
707
                NoExperimentalAccountability: cfg.ProtocolOptions.NoExpAccountability(),
4✔
708
                NoQuiescence:                 cfg.ProtocolOptions.NoQuiescence(),
4✔
709
                NoRbfCoopClose:               !cfg.ProtocolOptions.RbfCoopClose,
4✔
710
        })
4✔
711
        if err != nil {
4✔
712
                return nil, err
×
713
        }
×
714

715
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
4✔
716
        registryConfig := invoices.RegistryConfig{
4✔
717
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
4✔
718
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
4✔
719
                Clock:                       clock.NewDefaultClock(),
4✔
720
                AcceptKeySend:               cfg.AcceptKeySend,
4✔
721
                AcceptAMP:                   cfg.AcceptAMP,
4✔
722
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
4✔
723
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
4✔
724
                KeysendHoldTime:             cfg.KeysendHoldTime,
4✔
725
                HtlcInterceptor:             invoiceHtlcModifier,
4✔
726
        }
4✔
727

4✔
728
        v1Graph := graphdb.NewVersionedGraph(
4✔
729
                dbs.GraphDB, lnwire.GossipVersion1,
4✔
730
        )
4✔
731

4✔
732
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, v1Graph)
4✔
733
        chanStateDB := dbs.ChanStateDB.ChannelStateDB()
4✔
734

4✔
735
        s := &server{
4✔
736
                cfg:            cfg,
4✔
737
                implCfg:        implCfg,
4✔
738
                graphDB:        dbs.GraphDB,
4✔
739
                v1Graph:        v1Graph,
4✔
740
                chanStateDB:    chanStateDB,
4✔
741
                linkNodeDB:     chanStateDB.LinkNodeDB(),
4✔
742
                addrSource:     addrSource,
4✔
743
                miscDB:         dbs.ChanStateDB,
4✔
744
                invoicesDB:     dbs.InvoiceDB,
4✔
745
                paymentsDB:     dbs.PaymentsDB,
4✔
746
                cc:             cc,
4✔
747
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
4✔
748
                writePool:      writePool,
4✔
749
                readPool:       readPool,
4✔
750
                chansToRestore: chansToRestore,
4✔
751

4✔
752
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
4✔
753
                        cc.ChainNotifier,
4✔
754
                ),
4✔
755
                channelNotifier: channelnotifier.New(chanStateDB),
4✔
756

4✔
757
                identityECDH:   nodeKeyECDH,
4✔
758
                identityKeyLoc: nodeKeyDesc.KeyLocator,
4✔
759
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
4✔
760

4✔
761
                listenAddrs: listenAddrs,
4✔
762

4✔
763
                // TODO(roasbeef): derive proper onion key based on rotation
4✔
764
                // schedule
4✔
765
                sphinxPayment:  hop.NewOnionProcessor(sphinxRouter),
4✔
766
                sphinxOnionMsg: sphinxOnionMsg,
4✔
767

4✔
768
                torController: torController,
4✔
769

4✔
770
                persistentPeers:         make(map[string]bool),
4✔
771
                persistentPeersBackoff:  make(map[string]time.Duration),
4✔
772
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
4✔
773
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
4✔
774
                persistentRetryCancels:  make(map[string]chan struct{}),
4✔
775
                peerErrors:              make(map[string]*queue.CircularBuffer),
4✔
776
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
4✔
777
                scheduledPeerConnection: make(map[string]func()),
4✔
778
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
4✔
779

4✔
780
                peersByPub:                make(map[string]*peer.Brontide),
4✔
781
                inboundPeers:              make(map[string]*peer.Brontide),
4✔
782
                outboundPeers:             make(map[string]*peer.Brontide),
4✔
783
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
4✔
784
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
4✔
785

4✔
786
                invoiceHtlcModifier: invoiceHtlcModifier,
4✔
787

4✔
788
                customMessageServer: subscribe.NewServer(),
4✔
789

4✔
790
                onionMessageServer: subscribe.NewServer(),
4✔
791

4✔
792
                actorSystem: actor.NewActorSystem(),
4✔
793

4✔
794
                tlsManager: tlsManager,
4✔
795

4✔
796
                featureMgr: featureMgr,
4✔
797
                quit:       make(chan struct{}),
4✔
798
        }
4✔
799

4✔
800
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
4✔
801
        if err != nil {
4✔
802
                return nil, err
×
803
        }
×
804

805
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
4✔
806
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
4✔
807
                uint32(currentHeight), currentHash, cc.ChainNotifier,
4✔
808
        )
4✔
809
        s.invoices = invoices.NewRegistry(
4✔
810
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
4✔
811
        )
4✔
812

4✔
813
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
814

4✔
815
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
4✔
816
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
817

4✔
818
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
8✔
819
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
4✔
820
                if err != nil {
4✔
821
                        return err
×
822
                }
×
823

824
                s.htlcSwitch.UpdateLinkAliases(link)
4✔
825

4✔
826
                return nil
4✔
827
        }
828

829
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
4✔
830
        if err != nil {
4✔
831
                return nil, err
×
832
        }
×
833

834
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
4✔
835
                DB:                   dbs.ChanStateDB,
4✔
836
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
4✔
837
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
4✔
838
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
4✔
839
                LocalChannelClose: func(pubKey []byte,
4✔
840
                        request *htlcswitch.ChanClose) {
8✔
841

4✔
842
                        peer, err := s.FindPeerByPubStr(string(pubKey))
4✔
843
                        if err != nil {
4✔
844
                                srvrLog.Errorf("unable to close channel, peer"+
×
845
                                        " with %v id can't be found: %v",
×
846
                                        pubKey, err,
×
847
                                )
×
848
                                return
×
849
                        }
×
850

851
                        peer.HandleLocalCloseChanReqs(request)
4✔
852
                },
853
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
854
                SwitchPackager:         channeldb.NewSwitchPackager(),
855
                ExtractErrorEncrypter:  s.sphinxPayment.ExtractErrorEncrypter,
856
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
857
                Notifier:               s.cc.ChainNotifier,
858
                HtlcNotifier:           s.htlcNotifier,
859
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
860
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
861
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
862
                AllowCircularRoute:     cfg.AllowCircularRoute,
863
                RejectHTLC:             cfg.RejectHTLC,
864
                Clock:                  clock.NewDefaultClock(),
865
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
866
                MaxFeeExposure:         thresholdMSats,
867
                SignAliasUpdate:        s.signAliasUpdate,
868
                IsAlias:                aliasmgr.IsAlias,
869
        }, uint32(currentHeight))
870
        if err != nil {
4✔
871
                return nil, err
×
872
        }
×
873
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
4✔
874
                &htlcswitch.InterceptableSwitchConfig{
4✔
875
                        Switch:             s.htlcSwitch,
4✔
876
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
4✔
877
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
4✔
878
                        RequireInterceptor: s.cfg.RequireInterceptor,
4✔
879
                        Notifier:           s.cc.ChainNotifier,
4✔
880
                },
4✔
881
        )
4✔
882
        if err != nil {
4✔
883
                return nil, err
×
884
        }
×
885

886
        s.witnessBeacon = newPreimageBeacon(
4✔
887
                dbs.ChanStateDB.NewWitnessCache(),
4✔
888
                s.interceptableSwitch.ForwardPacket,
4✔
889
        )
4✔
890

4✔
891
        chanStatusMgrCfg := &netann.ChanStatusConfig{
4✔
892
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
4✔
893
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
4✔
894
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
4✔
895
                OurPubKey:                nodeKeyDesc.PubKey,
4✔
896
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
4✔
897
                MessageSigner:            s.nodeSigner,
4✔
898
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
4✔
899
                ApplyChannelUpdate:       s.applyChannelUpdate,
4✔
900
                DB:                       s.chanStateDB,
4✔
901
                Graph:                    dbs.GraphDB,
4✔
902
        }
4✔
903

4✔
904
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
4✔
905
        if err != nil {
4✔
906
                return nil, err
×
907
        }
×
908
        s.chanStatusMgr = chanStatusMgr
4✔
909

4✔
910
        // If enabled, use either UPnP or NAT-PMP to automatically configure
4✔
911
        // port forwarding for users behind a NAT.
4✔
912
        if cfg.NAT {
4✔
913
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
914

×
915
                discoveryTimeout := time.Duration(10 * time.Second)
×
916

×
917
                ctx, cancel := context.WithTimeout(
×
918
                        context.Background(), discoveryTimeout,
×
919
                )
×
920
                defer cancel()
×
921
                upnp, err := nat.DiscoverUPnP(ctx)
×
922
                if err == nil {
×
923
                        s.natTraversal = upnp
×
924
                } else {
×
925
                        // If we were not able to discover a UPnP enabled device
×
926
                        // on the local network, we'll fall back to attempting
×
927
                        // to discover a NAT-PMP enabled device.
×
928
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
929
                                "device on the local network: %v", err)
×
930

×
931
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
932
                                "enabled device")
×
933

×
934
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
935
                        if err != nil {
×
936
                                err := fmt.Errorf("unable to discover a "+
×
937
                                        "NAT-PMP enabled device on the local "+
×
938
                                        "network: %v", err)
×
939
                                srvrLog.Error(err)
×
940
                                return nil, err
×
941
                        }
×
942

943
                        s.natTraversal = pmp
×
944
                }
945
        }
946

947
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
4✔
948
        // Set the self node which represents our node in the graph.
4✔
949
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
4✔
950
        if err != nil {
4✔
951
                return nil, err
×
952
        }
×
953

954
        // The router will get access to the payment ID sequencer, such that it
955
        // can generate unique payment IDs.
956
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
4✔
957
        if err != nil {
4✔
958
                return nil, err
×
959
        }
×
960

961
        // Instantiate mission control with config from the sub server.
962
        //
963
        // TODO(joostjager): When we are further in the process of moving to sub
964
        // servers, the mission control instance itself can be moved there too.
965
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
4✔
966

4✔
967
        // We only initialize a probability estimator if there's no custom one.
4✔
968
        var estimator routing.Estimator
4✔
969
        if cfg.Estimator != nil {
4✔
970
                estimator = cfg.Estimator
×
971
        } else {
4✔
972
                switch routingConfig.ProbabilityEstimatorType {
4✔
973
                case routing.AprioriEstimatorName:
4✔
974
                        aCfg := routingConfig.AprioriConfig
4✔
975
                        aprioriConfig := routing.AprioriConfig{
4✔
976
                                AprioriHopProbability: aCfg.HopProbability,
4✔
977
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
4✔
978
                                AprioriWeight:         aCfg.Weight,
4✔
979
                                CapacityFraction:      aCfg.CapacityFraction,
4✔
980
                        }
4✔
981

4✔
982
                        estimator, err = routing.NewAprioriEstimator(
4✔
983
                                aprioriConfig,
4✔
984
                        )
4✔
985
                        if err != nil {
4✔
986
                                return nil, err
×
987
                        }
×
988

989
                case routing.BimodalEstimatorName:
×
990
                        bCfg := routingConfig.BimodalConfig
×
991
                        bimodalConfig := routing.BimodalConfig{
×
992
                                BimodalNodeWeight: bCfg.NodeWeight,
×
993
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
994
                                        bCfg.Scale,
×
995
                                ),
×
996
                                BimodalDecayTime: bCfg.DecayTime,
×
997
                        }
×
998

×
999
                        estimator, err = routing.NewBimodalEstimator(
×
1000
                                bimodalConfig,
×
1001
                        )
×
1002
                        if err != nil {
×
1003
                                return nil, err
×
1004
                        }
×
1005

1006
                default:
×
1007
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1008
                                routingConfig.ProbabilityEstimatorType)
×
1009
                }
1010
        }
1011

1012
        mcCfg := &routing.MissionControlConfig{
4✔
1013
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
4✔
1014
                Estimator:               estimator,
4✔
1015
                MaxMcHistory:            routingConfig.MaxMcHistory,
4✔
1016
                McFlushInterval:         routingConfig.McFlushInterval,
4✔
1017
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
4✔
1018
        }
4✔
1019

4✔
1020
        s.missionController, err = routing.NewMissionController(
4✔
1021
                dbs.ChanStateDB, nodePubKey, mcCfg,
4✔
1022
        )
4✔
1023
        if err != nil {
4✔
1024
                return nil, fmt.Errorf("can't create mission control "+
×
1025
                        "manager: %w", err)
×
1026
        }
×
1027
        s.defaultMC, err = s.missionController.GetNamespacedStore(
4✔
1028
                routing.DefaultMissionControlNamespace,
4✔
1029
        )
4✔
1030
        if err != nil {
4✔
1031
                return nil, fmt.Errorf("can't create mission control in the "+
×
1032
                        "default namespace: %w", err)
×
1033
        }
×
1034

1035
        srvrLog.Debugf("Instantiating payment session source with config: "+
4✔
1036
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
4✔
1037
                int64(routingConfig.AttemptCost),
4✔
1038
                float64(routingConfig.AttemptCostPPM)/10000,
4✔
1039
                routingConfig.MinRouteProbability)
4✔
1040

4✔
1041
        pathFindingConfig := routing.PathFindingConfig{
4✔
1042
                AttemptCost: lnwire.NewMSatFromSatoshis(
4✔
1043
                        routingConfig.AttemptCost,
4✔
1044
                ),
4✔
1045
                AttemptCostPPM: routingConfig.AttemptCostPPM,
4✔
1046
                MinProbability: routingConfig.MinRouteProbability,
4✔
1047
        }
4✔
1048

4✔
1049
        sourceNode, err := s.v1Graph.SourceNode(ctx)
4✔
1050
        if err != nil {
4✔
1051
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1052
        }
×
1053
        paymentSessionSource := &routing.SessionSource{
4✔
1054
                GraphSessionFactory: s.v1Graph,
4✔
1055
                SourceNode:          sourceNode,
4✔
1056
                MissionControl:      s.defaultMC,
4✔
1057
                GetLink:             s.htlcSwitch.GetLinkByShortID,
4✔
1058
                PathFindingConfig:   pathFindingConfig,
4✔
1059
        }
4✔
1060

4✔
1061
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
4✔
1062

4✔
1063
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
1064
                cfg.Routing.StrictZombiePruning
4✔
1065

4✔
1066
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
4✔
1067
                SelfNode:            nodePubKey,
4✔
1068
                Graph:               dbs.GraphDB,
4✔
1069
                Chain:               cc.ChainIO,
4✔
1070
                ChainView:           cc.ChainView,
4✔
1071
                Notifier:            cc.ChainNotifier,
4✔
1072
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
4✔
1073
                GraphPruneInterval:  time.Hour,
4✔
1074
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
4✔
1075
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
4✔
1076
                StrictZombiePruning: strictPruning,
4✔
1077
                IsAlias:             aliasmgr.IsAlias,
4✔
1078
        })
4✔
1079
        if err != nil {
4✔
1080
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1081
        }
×
1082

1083
        s.chanRouter, err = routing.New(routing.Config{
4✔
1084
                SelfNode:                  nodePubKey,
4✔
1085
                RoutingGraph:              s.v1Graph,
4✔
1086
                Chain:                     cc.ChainIO,
4✔
1087
                Payer:                     s.htlcSwitch,
4✔
1088
                Control:                   s.controlTower,
4✔
1089
                MissionControl:            s.defaultMC,
4✔
1090
                SessionSource:             paymentSessionSource,
4✔
1091
                GetLink:                   s.htlcSwitch.GetLinkByShortID,
4✔
1092
                NextPaymentID:             sequencer.NextID,
4✔
1093
                PathFindingConfig:         pathFindingConfig,
4✔
1094
                Clock:                     clock.NewDefaultClock(),
4✔
1095
                ApplyChannelUpdate:        s.graphBuilder.ApplyChannelUpdate,
4✔
1096
                ClosedSCIDs:               s.fetchClosedChannelSCIDs(),
4✔
1097
                TrafficShaper:             implCfg.TrafficShaper,
4✔
1098
                KeepFailedPaymentAttempts: cfg.KeepFailedPaymentAttempts,
4✔
1099
        })
4✔
1100
        if err != nil {
4✔
1101
                return nil, fmt.Errorf("can't create router: %w", err)
×
1102
        }
×
1103

1104
        chanSeries := discovery.NewChanSeries(
4✔
1105
                graphdb.NewVersionedGraph(s.graphDB, lnwire.GossipVersion1),
4✔
1106
        )
4✔
1107
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
4✔
1108
        if err != nil {
4✔
1109
                return nil, err
×
1110
        }
×
1111
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
4✔
1112
        if err != nil {
4✔
1113
                return nil, err
×
1114
        }
×
1115

1116
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
4✔
1117

4✔
1118
        s.authGossiper = discovery.New(discovery.Config{
4✔
1119
                Graph:                 s.graphBuilder,
4✔
1120
                ChainIO:               s.cc.ChainIO,
4✔
1121
                Notifier:              s.cc.ChainNotifier,
4✔
1122
                ChainParams:           s.cfg.ActiveNetParams.Params,
4✔
1123
                Broadcast:             s.BroadcastMessage,
4✔
1124
                ChanSeries:            chanSeries,
4✔
1125
                NotifyWhenOnline:      s.NotifyWhenOnline,
4✔
1126
                NotifyWhenOffline:     s.NotifyWhenOffline,
4✔
1127
                FetchSelfAnnouncement: s.getNodeAnnouncement,
4✔
1128
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
4✔
1129
                        error) {
4✔
1130

×
1131
                        return s.genNodeAnnouncement(nil)
×
1132
                },
×
1133
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1134
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1135
                RetransmitTicker:        ticker.New(time.Minute * 30),
1136
                RebroadcastInterval:     time.Hour * 24,
1137
                WaitingProofStore:       waitingProofStore,
1138
                MessageStore:            gossipMessageStore,
1139
                AnnSigner:               s.nodeSigner,
1140
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1141
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1142
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1143
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1144
                MinimumBatchSize:        10,
1145
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1146
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1147
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1148
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1149
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1150
                IsAlias:                 aliasmgr.IsAlias,
1151
                SignAliasUpdate:         s.signAliasUpdate,
1152
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1153
                GetAlias:                s.aliasMgr.GetPeerAlias,
1154
                FindChannel:             s.findChannel,
1155
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1156
                ScidCloser:              scidCloserMan,
1157
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1158
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1159
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1160
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1161
                BanThreshold:            cfg.Gossip.BanThreshold,
1162
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1163
        }, nodeKeyDesc)
1164

1165
        accessCfg := &accessManConfig{
4✔
1166
                initAccessPerms: func() (map[string]channeldb.ChanCount,
4✔
1167
                        error) {
8✔
1168

4✔
1169
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
4✔
1170
                        return s.chanStateDB.FetchPermAndTempPeers(
4✔
1171
                                genesisHash[:],
4✔
1172
                        )
4✔
1173
                },
4✔
1174
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1175
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1176
        }
1177

1178
        peerAccessMan, err := newAccessMan(accessCfg)
4✔
1179
        if err != nil {
4✔
1180
                return nil, err
×
1181
        }
×
1182

1183
        s.peerAccessMan = peerAccessMan
4✔
1184

4✔
1185
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1186
        //nolint:ll
4✔
1187
        s.localChanMgr = &localchans.Manager{
4✔
1188
                SelfPub:              nodeKeyDesc.PubKey,
4✔
1189
                DefaultRoutingPolicy: cc.RoutingPolicy,
4✔
1190
                ForAllOutgoingChannels: func(ctx context.Context,
4✔
1191
                        cb func(*models.ChannelEdgeInfo,
4✔
1192
                                *models.ChannelEdgePolicy) error,
4✔
1193
                        reset func()) error {
8✔
1194

4✔
1195
                        return s.v1Graph.ForEachNodeChannel(
4✔
1196
                                ctx, selfVertex,
4✔
1197
                                func(c *models.ChannelEdgeInfo,
4✔
1198
                                        e *models.ChannelEdgePolicy,
4✔
1199
                                        _ *models.ChannelEdgePolicy) error {
8✔
1200

4✔
1201
                                        // NOTE: The invoked callback here may
4✔
1202
                                        // receive a nil channel policy.
4✔
1203
                                        return cb(c, e)
4✔
1204
                                }, reset,
4✔
1205
                        )
1206
                },
1207
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1208
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1209
                FetchChannel:              s.chanStateDB.FetchChannel,
1210
                AddEdge: func(ctx context.Context,
1211
                        edge *models.ChannelEdgeInfo) error {
×
1212

×
1213
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1214
                },
×
1215
        }
1216

1217
        utxnStore, err := contractcourt.NewNurseryStore(
4✔
1218
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
4✔
1219
        )
4✔
1220
        if err != nil {
4✔
1221
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1222
                return nil, err
×
1223
        }
×
1224

1225
        sweeperStore, err := sweep.NewSweeperStore(
4✔
1226
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
4✔
1227
        )
4✔
1228
        if err != nil {
4✔
1229
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1230
                return nil, err
×
1231
        }
×
1232

1233
        aggregator := sweep.NewBudgetAggregator(
4✔
1234
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
4✔
1235
                s.implCfg.AuxSweeper,
4✔
1236
        )
4✔
1237

4✔
1238
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
4✔
1239
                Signer:     cc.Wallet.Cfg.Signer,
4✔
1240
                Wallet:     cc.Wallet,
4✔
1241
                Estimator:  cc.FeeEstimator,
4✔
1242
                Notifier:   cc.ChainNotifier,
4✔
1243
                AuxSweeper: s.implCfg.AuxSweeper,
4✔
1244
        })
4✔
1245

4✔
1246
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
4✔
1247
                FeeEstimator: cc.FeeEstimator,
4✔
1248
                GenSweepScript: newSweepPkScriptGen(
4✔
1249
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
4✔
1250
                ),
4✔
1251
                Signer:               cc.Wallet.Cfg.Signer,
4✔
1252
                Wallet:               newSweeperWallet(cc.Wallet),
4✔
1253
                Mempool:              cc.MempoolNotifier,
4✔
1254
                Notifier:             cc.ChainNotifier,
4✔
1255
                Store:                sweeperStore,
4✔
1256
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
4✔
1257
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
4✔
1258
                Aggregator:           aggregator,
4✔
1259
                Publisher:            s.txPublisher,
4✔
1260
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
4✔
1261
        })
4✔
1262

4✔
1263
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
4✔
1264
                ChainIO:             cc.ChainIO,
4✔
1265
                ConfDepth:           1,
4✔
1266
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
4✔
1267
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
4✔
1268
                Notifier:            cc.ChainNotifier,
4✔
1269
                PublishTransaction:  cc.Wallet.PublishTransaction,
4✔
1270
                Store:               utxnStore,
4✔
1271
                SweepInput:          s.sweeper.SweepInput,
4✔
1272
                Budget:              s.cfg.Sweeper.Budget,
4✔
1273
        })
4✔
1274

4✔
1275
        // Construct a closure that wraps the htlcswitch's CloseLink method.
4✔
1276
        closeLink := func(chanPoint *wire.OutPoint,
4✔
1277
                closureType contractcourt.ChannelCloseType) {
8✔
1278
                // TODO(conner): Properly respect the update and error channels
4✔
1279
                // returned by CloseLink.
4✔
1280

4✔
1281
                // Instruct the switch to close the channel.  Provide no close out
4✔
1282
                // delivery script or target fee per kw because user input is not
4✔
1283
                // available when the remote peer closes the channel.
4✔
1284
                s.htlcSwitch.CloseLink(
4✔
1285
                        context.Background(), chanPoint, closureType, 0, 0, nil,
4✔
1286
                )
4✔
1287
        }
4✔
1288

1289
        // We will use the following channel to reliably hand off contract
1290
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1291
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
4✔
1292

4✔
1293
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
4✔
1294
                &contractcourt.BreachConfig{
4✔
1295
                        CloseLink: closeLink,
4✔
1296
                        DB:        s.chanStateDB,
4✔
1297
                        Estimator: s.cc.FeeEstimator,
4✔
1298
                        GenSweepScript: newSweepPkScriptGen(
4✔
1299
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
4✔
1300
                        ),
4✔
1301
                        Notifier:           cc.ChainNotifier,
4✔
1302
                        PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1303
                        ContractBreaches:   contractBreaches,
4✔
1304
                        Signer:             cc.Wallet.Cfg.Signer,
4✔
1305
                        Store: contractcourt.NewRetributionStore(
4✔
1306
                                dbs.ChanStateDB,
4✔
1307
                        ),
4✔
1308
                        AuxSweeper: s.implCfg.AuxSweeper,
4✔
1309
                },
4✔
1310
        )
4✔
1311

4✔
1312
        //nolint:ll
4✔
1313
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
4✔
1314
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
4✔
1315
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
4✔
1316
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
4✔
1317
                NewSweepAddr: func() ([]byte, error) {
4✔
1318
                        addr, err := newSweepPkScriptGen(
×
1319
                                cc.Wallet, netParams,
×
1320
                        )().Unpack()
×
1321
                        if err != nil {
×
1322
                                return nil, err
×
1323
                        }
×
1324

1325
                        return addr.DeliveryAddress, nil
×
1326
                },
1327
                PublishTx: cc.Wallet.PublishTransaction,
1328
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
4✔
1329
                        for _, msg := range msgs {
8✔
1330
                                err := s.htlcSwitch.ProcessContractResolution(msg)
4✔
1331
                                if err != nil {
4✔
1332
                                        return err
×
1333
                                }
×
1334
                        }
1335
                        return nil
4✔
1336
                },
1337
                IncubateOutputs: func(chanPoint wire.OutPoint,
1338
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1339
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1340
                        broadcastHeight uint32,
1341
                        deadlineHeight fn.Option[int32],
1342
                        opts ...contractcourt.IncubateOption) error {
4✔
1343

4✔
1344
                        return s.utxoNursery.IncubateOutputs(
4✔
1345
                                chanPoint, outHtlcRes, inHtlcRes,
4✔
1346
                                broadcastHeight, deadlineHeight,
4✔
1347
                                opts...,
4✔
1348
                        )
4✔
1349
                },
4✔
1350
                PreimageDB:   s.witnessBeacon,
1351
                Notifier:     cc.ChainNotifier,
1352
                Mempool:      cc.MempoolNotifier,
1353
                Signer:       cc.Wallet.Cfg.Signer,
1354
                FeeEstimator: cc.FeeEstimator,
1355
                ChainIO:      cc.ChainIO,
1356
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
4✔
1357
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1358
                        s.htlcSwitch.RemoveLink(chanID)
4✔
1359
                        return nil
4✔
1360
                },
4✔
1361
                IsOurAddress: cc.Wallet.IsOurAddress,
1362
                ContractBreach: func(chanPoint wire.OutPoint,
1363
                        breachRet *lnwallet.BreachRetribution) error {
4✔
1364

4✔
1365
                        // processACK will handle the BreachArbitrator ACKing
4✔
1366
                        // the event.
4✔
1367
                        finalErr := make(chan error, 1)
4✔
1368
                        processACK := func(brarErr error) {
8✔
1369
                                if brarErr != nil {
4✔
1370
                                        finalErr <- brarErr
×
1371
                                        return
×
1372
                                }
×
1373

1374
                                // If the BreachArbitrator successfully handled
1375
                                // the event, we can signal that the handoff
1376
                                // was successful.
1377
                                finalErr <- nil
4✔
1378
                        }
1379

1380
                        event := &contractcourt.ContractBreachEvent{
4✔
1381
                                ChanPoint:         chanPoint,
4✔
1382
                                ProcessACK:        processACK,
4✔
1383
                                BreachRetribution: breachRet,
4✔
1384
                        }
4✔
1385

4✔
1386
                        // Send the contract breach event to the
4✔
1387
                        // BreachArbitrator.
4✔
1388
                        select {
4✔
1389
                        case contractBreaches <- event:
4✔
1390
                        case <-s.quit:
×
1391
                                return ErrServerShuttingDown
×
1392
                        }
1393

1394
                        // We'll wait for a final error to be available from
1395
                        // the BreachArbitrator.
1396
                        select {
4✔
1397
                        case err := <-finalErr:
4✔
1398
                                return err
4✔
1399
                        case <-s.quit:
×
1400
                                return ErrServerShuttingDown
×
1401
                        }
1402
                },
1403
                DisableChannel: func(chanPoint wire.OutPoint) error {
4✔
1404
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
4✔
1405
                },
4✔
1406
                Sweeper:                       s.sweeper,
1407
                Registry:                      s.invoices,
1408
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1409
                NotifyEarlyClosedChannel:      s.channelNotifier.NotifyEarlyClosedChannelEvent,
1410
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1411
                OnionProcessor:                s.sphinxPayment,
1412
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1413
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1414
                Clock:                         clock.NewDefaultClock(),
1415
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1416
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1417
                HtlcNotifier:                  s.htlcNotifier,
1418
                Budget:                        *s.cfg.Sweeper.Budget,
1419

1420
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1421
                QueryIncomingCircuit: func(
1422
                        circuit models.CircuitKey) *models.CircuitKey {
4✔
1423

4✔
1424
                        // Get the circuit map.
4✔
1425
                        circuits := s.htlcSwitch.CircuitLookup()
4✔
1426

4✔
1427
                        // Lookup the outgoing circuit.
4✔
1428
                        pc := circuits.LookupOpenCircuit(circuit)
4✔
1429
                        if pc == nil {
7✔
1430
                                return nil
3✔
1431
                        }
3✔
1432

1433
                        return &pc.Incoming
4✔
1434
                },
1435
                AuxLeafStore: implCfg.AuxLeafStore,
1436
                AuxSigner:    implCfg.AuxSigner,
1437
                AuxResolver:  implCfg.AuxContractResolver,
1438
                AuxCloser: fn.MapOption(
1439
                        func(c chcl.AuxChanCloser) contractcourt.AuxChanCloser {
×
1440
                                return c
×
1441
                        },
×
1442
                )(implCfg.AuxChanCloser),
1443
                ChannelCloseConfs: s.cfg.Dev.ChannelCloseConfs(),
1444
        }, dbs.ChanStateDB)
1445

1446
        // Select the configuration and funding parameters for Bitcoin.
1447
        chainCfg := cfg.Bitcoin
4✔
1448
        minRemoteDelay := funding.MinBtcRemoteDelay
4✔
1449
        maxRemoteDelay := funding.MaxBtcRemoteDelay
4✔
1450

4✔
1451
        var chanIDSeed [32]byte
4✔
1452
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
4✔
1453
                return nil, err
×
1454
        }
×
1455

1456
        // Wrap the DeleteChannelEdges method so that the funding manager can
1457
        // use it without depending on several layers of indirection.
1458
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
4✔
1459
                *models.ChannelEdgePolicy, error) {
8✔
1460

4✔
1461
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
4✔
1462
                        context.TODO(), scid.ToUint64(),
4✔
1463
                )
4✔
1464
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
4✔
1465
                        // This is unlikely but there is a slim chance of this
×
1466
                        // being hit if lnd was killed via SIGKILL and the
×
1467
                        // funding manager was stepping through the delete
×
1468
                        // alias edge logic.
×
1469
                        return nil, nil
×
1470
                } else if err != nil {
4✔
1471
                        return nil, err
×
1472
                }
×
1473

1474
                // Grab our key to find our policy.
1475
                var ourKey [33]byte
4✔
1476
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
4✔
1477

4✔
1478
                var ourPolicy *models.ChannelEdgePolicy
4✔
1479
                if info != nil && info.NodeKey1Bytes == ourKey {
8✔
1480
                        ourPolicy = e1
4✔
1481
                } else {
8✔
1482
                        ourPolicy = e2
4✔
1483
                }
4✔
1484

1485
                if ourPolicy == nil {
4✔
1486
                        // Something is wrong, so return an error.
×
1487
                        return nil, fmt.Errorf("we don't have an edge")
×
1488
                }
×
1489

1490
                err = s.v1Graph.DeleteChannelEdges(
4✔
1491
                        context.TODO(), false, false, scid.ToUint64(),
4✔
1492
                )
4✔
1493
                return ourPolicy, err
4✔
1494
        }
1495

1496
        // For the reservationTimeout and the zombieSweeperInterval different
1497
        // values are set in case we are in a dev environment so enhance test
1498
        // capacilities.
1499
        reservationTimeout := chanfunding.DefaultReservationTimeout
4✔
1500
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
4✔
1501

4✔
1502
        // Get the development config for funding manager. If we are not in
4✔
1503
        // development mode, this would be nil.
4✔
1504
        var devCfg *funding.DevConfig
4✔
1505
        if lncfg.IsDevBuild() {
8✔
1506
                devCfg = &funding.DevConfig{
4✔
1507
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
4✔
1508
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
4✔
1509
                                GetMaxWaitNumBlocksFundingConf(),
4✔
1510
                }
4✔
1511

4✔
1512
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1513
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1514

4✔
1515
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
4✔
1516
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
4✔
1517
                        devCfg, reservationTimeout, zombieSweeperInterval)
4✔
1518
        }
4✔
1519

1520
        // Attempt to parse the provided upfront-shutdown address (if any).
1521
        script, err := chcl.ParseUpfrontShutdownAddress(
4✔
1522
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
4✔
1523
        )
4✔
1524
        if err != nil {
4✔
1525
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1526
                        err)
×
1527
        }
×
1528

1529
        //nolint:ll
1530
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
4✔
1531
                Dev:                devCfg,
4✔
1532
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
4✔
1533
                IDKey:              nodeKeyDesc.PubKey,
4✔
1534
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
4✔
1535
                Wallet:             cc.Wallet,
4✔
1536
                PublishTransaction: cc.Wallet.PublishTransaction,
4✔
1537
                UpdateLabel: func(hash chainhash.Hash, label string) error {
8✔
1538
                        return cc.Wallet.LabelTransaction(hash, label, true)
4✔
1539
                },
4✔
1540
                Notifier:     cc.ChainNotifier,
1541
                ChannelDB:    s.chanStateDB,
1542
                FeeEstimator: cc.FeeEstimator,
1543
                SignMessage:  cc.MsgSigner.SignMessage,
1544
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1545
                        error) {
4✔
1546

4✔
1547
                        return s.genNodeAnnouncement(nil)
4✔
1548
                },
4✔
1549
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1550
                NotifyWhenOnline:     s.NotifyWhenOnline,
1551
                TempChanIDSeed:       chanIDSeed,
1552
                FindChannel:          s.findChannel,
1553
                DefaultRoutingPolicy: cc.RoutingPolicy,
1554
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1555
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1556
                        pushAmt lnwire.MilliSatoshi) uint16 {
4✔
1557
                        // In case the user has explicitly specified
4✔
1558
                        // a default value for the number of
4✔
1559
                        // confirmations, we use it.
4✔
1560
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
4✔
1561
                        if defaultConf != 0 {
8✔
1562
                                return defaultConf
4✔
1563
                        }
4✔
1564

1565
                        // Otherwise, scale the number of confirmations based on
1566
                        // the channel amount and push amount. For large
1567
                        // channels we increase the number of
1568
                        // confirmations we require for the channel to be
1569
                        // considered open. As it is always the
1570
                        // responder that gets to choose value, the
1571
                        // pushAmt is value being pushed to us. This
1572
                        // means we have more to lose in the case this
1573
                        // gets re-orged out, and we will require more
1574
                        // confirmations before we consider it open.
1575
                        return lnwallet.FundingConfsForAmounts(chanAmt, pushAmt)
×
1576
                },
1577
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
4✔
1578
                        // We scale the remote CSV delay (the time the
4✔
1579
                        // remote have to claim funds in case of a unilateral
4✔
1580
                        // close) linearly from minRemoteDelay blocks
4✔
1581
                        // for small channels, to maxRemoteDelay blocks
4✔
1582
                        // for channels of size MaxFundingAmount.
4✔
1583

4✔
1584
                        // In case the user has explicitly specified
4✔
1585
                        // a default value for the remote delay, we
4✔
1586
                        // use it.
4✔
1587
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
4✔
1588
                        if defaultDelay > 0 {
8✔
1589
                                return defaultDelay
4✔
1590
                        }
4✔
1591

1592
                        // If this is a wumbo channel, then we'll require the
1593
                        // max value.
1594
                        if chanAmt > MaxFundingAmount {
×
1595
                                return maxRemoteDelay
×
1596
                        }
×
1597

1598
                        // If not we scale according to channel size.
1599
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1600
                                chanAmt / MaxFundingAmount)
×
1601
                        if delay < minRemoteDelay {
×
1602
                                delay = minRemoteDelay
×
1603
                        }
×
1604
                        if delay > maxRemoteDelay {
×
1605
                                delay = maxRemoteDelay
×
1606
                        }
×
1607
                        return delay
×
1608
                },
1609
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1610
                        peerKey *btcec.PublicKey) error {
4✔
1611

4✔
1612
                        // First, we'll mark this new peer as a persistent peer
4✔
1613
                        // for re-connection purposes. If the peer is not yet
4✔
1614
                        // tracked or the user hasn't requested it to be perm,
4✔
1615
                        // we'll set false to prevent the server from continuing
4✔
1616
                        // to connect to this peer even if the number of
4✔
1617
                        // channels with this peer is zero.
4✔
1618
                        s.mu.Lock()
4✔
1619
                        pubStr := string(peerKey.SerializeCompressed())
4✔
1620
                        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
1621
                                s.persistentPeers[pubStr] = false
4✔
1622
                        }
4✔
1623
                        s.mu.Unlock()
4✔
1624

4✔
1625
                        // With that taken care of, we'll send this channel to
4✔
1626
                        // the chain arb so it can react to on-chain events.
4✔
1627
                        return s.chainArb.WatchNewChannel(channel)
4✔
1628
                },
1629
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
4✔
1630
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
4✔
1631
                        return s.htlcSwitch.UpdateShortChanID(cid)
4✔
1632
                },
4✔
1633
                RequiredRemoteChanReserve: func(chanAmt,
1634
                        dustLimit btcutil.Amount) btcutil.Amount {
4✔
1635

4✔
1636
                        // By default, we'll require the remote peer to maintain
4✔
1637
                        // at least 1% of the total channel capacity at all
4✔
1638
                        // times. If this value ends up dipping below the dust
4✔
1639
                        // limit, then we'll use the dust limit itself as the
4✔
1640
                        // reserve as required by BOLT #2.
4✔
1641
                        reserve := chanAmt / 100
4✔
1642
                        if reserve < dustLimit {
8✔
1643
                                reserve = dustLimit
4✔
1644
                        }
4✔
1645

1646
                        return reserve
4✔
1647
                },
1648
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
4✔
1649
                        // By default, we'll allow the remote peer to fully
4✔
1650
                        // utilize the full bandwidth of the channel, minus our
4✔
1651
                        // required reserve.
4✔
1652
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
4✔
1653
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
4✔
1654
                },
4✔
1655
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
4✔
1656
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
8✔
1657
                                return cfg.DefaultRemoteMaxHtlcs
4✔
1658
                        }
4✔
1659

1660
                        // By default, we'll permit them to utilize the full
1661
                        // channel bandwidth.
1662
                        return uint16(input.MaxHTLCNumber / 2)
×
1663
                },
1664
                ZombieSweeperInterval:         zombieSweeperInterval,
1665
                ReservationTimeout:            reservationTimeout,
1666
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1667
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1668
                MaxPendingChannels:            cfg.MaxPendingChannels,
1669
                RejectPush:                    cfg.RejectPush,
1670
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1671
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1672
                OpenChannelPredicate:          chanPredicate,
1673
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1674
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1675
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1676
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1677
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1678
                DeleteAliasEdge:      deleteAliasEdge,
1679
                AliasManager:         s.aliasMgr,
1680
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1681
                AuxFundingController: implCfg.AuxFundingController,
1682
                AuxSigner:            implCfg.AuxSigner,
1683
                AuxResolver:          implCfg.AuxContractResolver,
1684
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1685
                ShutdownScript:       peer.ChooseAddr(script),
1686
        })
1687
        if err != nil {
4✔
1688
                return nil, err
×
1689
        }
×
1690

1691
        // Next, we'll assemble the sub-system that will maintain an on-disk
1692
        // static backup of the latest channel state.
1693
        chanNotifier := &channelNotifier{
4✔
1694
                chanNotifier: s.channelNotifier,
4✔
1695
                addrs:        s.addrSource,
4✔
1696
        }
4✔
1697
        backupFile := chanbackup.NewMultiFile(
4✔
1698
                cfg.BackupFilePath, cfg.NoBackupArchive,
4✔
1699
        )
4✔
1700
        startingChans, err := chanbackup.FetchStaticChanBackups(
4✔
1701
                ctx, s.chanStateDB, s.addrSource,
4✔
1702
        )
4✔
1703
        if err != nil {
4✔
1704
                return nil, err
×
1705
        }
×
1706
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
4✔
1707
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
4✔
1708
        )
4✔
1709
        if err != nil {
4✔
1710
                return nil, err
×
1711
        }
×
1712

1713
        // Assemble a peer notifier which will provide clients with subscriptions
1714
        // to peer online and offline events.
1715
        s.peerNotifier = peernotifier.New()
4✔
1716

4✔
1717
        // Create a channel event store which monitors all open channels.
4✔
1718
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
4✔
1719
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
8✔
1720
                        return s.channelNotifier.SubscribeChannelEvents()
4✔
1721
                },
4✔
1722
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
4✔
1723
                        return s.peerNotifier.SubscribePeerEvents()
4✔
1724
                },
4✔
1725
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1726
                Clock:           clock.NewDefaultClock(),
1727
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1728
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1729
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1730
        })
1731

1732
        if cfg.WtClient.Active {
8✔
1733
                policy := wtpolicy.DefaultPolicy()
4✔
1734
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
4✔
1735

4✔
1736
                // We expose the sweep fee rate in sat/vbyte, but the tower
4✔
1737
                // protocol operations on sat/kw.
4✔
1738
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
4✔
1739
                        1000 * cfg.WtClient.SweepFeeRate,
4✔
1740
                )
4✔
1741

4✔
1742
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1743

4✔
1744
                if err := policy.Validate(); err != nil {
4✔
1745
                        return nil, err
×
1746
                }
×
1747

1748
                // authDial is the wrapper around the btrontide.Dial for the
1749
                // watchtower.
1750
                authDial := func(localKey keychain.SingleKeyECDH,
4✔
1751
                        netAddr *lnwire.NetAddress,
4✔
1752
                        dialer tor.DialFunc) (wtserver.Peer, error) {
8✔
1753

4✔
1754
                        return brontide.Dial(
4✔
1755
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
4✔
1756
                        )
4✔
1757
                }
4✔
1758

1759
                // buildBreachRetribution is a call-back that can be used to
1760
                // query the BreachRetribution info and channel type given a
1761
                // channel ID and commitment height.
1762
                buildBreachRetribution := func(chanID lnwire.ChannelID,
4✔
1763
                        commitHeight uint64) (*lnwallet.BreachRetribution,
4✔
1764
                        channeldb.ChannelType, error) {
8✔
1765

4✔
1766
                        channel, err := s.chanStateDB.FetchChannelByID(chanID)
4✔
1767
                        if err != nil {
4✔
1768
                                return nil, 0, err
×
1769
                        }
×
1770

1771
                        br, err := lnwallet.NewBreachRetribution(
4✔
1772
                                channel, commitHeight, 0, nil,
4✔
1773
                                implCfg.AuxLeafStore,
4✔
1774
                                implCfg.AuxContractResolver,
4✔
1775
                        )
4✔
1776
                        if err != nil {
4✔
1777
                                return nil, 0, err
×
1778
                        }
×
1779

1780
                        return br, channel.ChanType, nil
4✔
1781
                }
1782

1783
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1784

4✔
1785
                // Copy the policy for legacy channels and set the blob flag
4✔
1786
                // signalling support for anchor channels.
4✔
1787
                anchorPolicy := policy
4✔
1788
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
4✔
1789

4✔
1790
                // Copy the policy for legacy channels and set the blob flag
4✔
1791
                // signalling support for taproot channels.
4✔
1792
                taprootPolicy := policy
4✔
1793
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1794
                        blob.FlagTaprootChannel,
4✔
1795
                )
4✔
1796

4✔
1797
                // Copy the policy for legacy channels and set the blob flags
4✔
1798
                // signalling support for production taproot channels.
4✔
1799
                taprootFinalPolicy := policy
4✔
1800
                taprootFinalPolicy.TxPolicy.BlobType |= blob.Type(
4✔
1801
                        blob.FlagTaprootChannel | blob.FlagTaprootFinalChannel,
4✔
1802
                )
4✔
1803

4✔
1804
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
4✔
1805
                        FetchClosedChannel:     fetchClosedChannel,
4✔
1806
                        BuildBreachRetribution: buildBreachRetribution,
4✔
1807
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
4✔
1808
                        ChainNotifier:          s.cc.ChainNotifier,
4✔
1809
                        SubscribeChannelEvents: func() (subscribe.Subscription,
4✔
1810
                                error) {
8✔
1811

4✔
1812
                                return s.channelNotifier.
4✔
1813
                                        SubscribeChannelEvents()
4✔
1814
                        },
4✔
1815
                        Signer: cc.Wallet.Cfg.Signer,
1816
                        NewAddress: func() ([]byte, error) {
4✔
1817
                                addr, err := newSweepPkScriptGen(
4✔
1818
                                        cc.Wallet, netParams,
4✔
1819
                                )().Unpack()
4✔
1820
                                if err != nil {
4✔
1821
                                        return nil, err
×
1822
                                }
×
1823

1824
                                return addr.DeliveryAddress, nil
4✔
1825
                        },
1826
                        SecretKeyRing:      s.cc.KeyRing,
1827
                        Dial:               cfg.net.Dial,
1828
                        AuthDial:           authDial,
1829
                        DB:                 dbs.TowerClientDB,
1830
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1831
                        MinBackoff:         10 * time.Second,
1832
                        MaxBackoff:         5 * time.Minute,
1833
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1834
                }, policy, anchorPolicy, taprootPolicy, taprootFinalPolicy)
1835
                if err != nil {
4✔
1836
                        return nil, err
×
1837
                }
×
1838
        }
1839

1840
        if len(cfg.ExternalHosts) != 0 {
4✔
1841
                advertisedIPs := make(map[string]struct{})
×
1842
                for _, addr := range s.currentNodeAnn.Addresses {
×
1843
                        advertisedIPs[addr.String()] = struct{}{}
×
1844
                }
×
1845

1846
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1847
                        Hosts:         cfg.ExternalHosts,
×
1848
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1849
                        LookupHost: func(host string) (net.Addr, error) {
×
1850
                                return lncfg.ParseAddressString(
×
1851
                                        host, strconv.Itoa(defaultPeerPort),
×
1852
                                        cfg.net.ResolveTCPAddr,
×
1853
                                )
×
1854
                        },
×
1855
                        AdvertisedIPs: advertisedIPs,
1856
                        AnnounceNewIPs: netann.IPAnnouncer(
1857
                                func(modifier ...netann.NodeAnnModifier) (
1858
                                        lnwire.NodeAnnouncement1, error) {
×
1859

×
1860
                                        return s.genNodeAnnouncement(
×
1861
                                                nil, modifier...,
×
1862
                                        )
×
1863
                                }),
×
1864
                })
1865
        }
1866

1867
        // Create liveness monitor.
1868
        s.createLivenessMonitor(cfg, cc, leaderElector)
4✔
1869

4✔
1870
        listeners := make([]net.Listener, len(listenAddrs))
4✔
1871
        for i, listenAddr := range listenAddrs {
8✔
1872
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
4✔
1873
                // doesn't need to call the general lndResolveTCP function
4✔
1874
                // since we are resolving a local address.
4✔
1875

4✔
1876
                // RESOLVE: We are actually partially accepting inbound
4✔
1877
                // connection requests when we call NewListener.
4✔
1878
                listeners[i], err = brontide.NewListener(
4✔
1879
                        nodeKeyECDH, listenAddr.String(),
4✔
1880
                        // TODO(yy): remove this check and unify the inbound
4✔
1881
                        // connection check inside `InboundPeerConnected`.
4✔
1882
                        s.peerAccessMan.checkAcceptIncomingConn,
4✔
1883
                )
4✔
1884
                if err != nil {
4✔
1885
                        return nil, err
×
1886
                }
×
1887
        }
1888

1889
        // Create the connection manager which will be responsible for
1890
        // maintaining persistent outbound connections and also accepting new
1891
        // incoming connections
1892
        cmgr, err := connmgr.New(&connmgr.Config{
4✔
1893
                Listeners:      listeners,
4✔
1894
                OnAccept:       s.InboundPeerConnected,
4✔
1895
                RetryDuration:  time.Second * 5,
4✔
1896
                TargetOutbound: 100,
4✔
1897
                Dial: noiseDial(
4✔
1898
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
4✔
1899
                ),
4✔
1900
                OnConnection: s.OutboundPeerConnected,
4✔
1901
        })
4✔
1902
        if err != nil {
4✔
1903
                return nil, err
×
1904
        }
×
1905
        s.connMgr = cmgr
4✔
1906

4✔
1907
        // Finally, register the subsystems in blockbeat.
4✔
1908
        s.registerBlockConsumers()
4✔
1909

4✔
1910
        return s, nil
4✔
1911
}
1912

1913
// UpdateRoutingConfig is a callback function to update the routing config
1914
// values in the main cfg.
1915
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
4✔
1916
        routerCfg := s.cfg.SubRPCServers.RouterRPC
4✔
1917

4✔
1918
        switch c := cfg.Estimator.Config().(type) {
4✔
1919
        case routing.AprioriConfig:
4✔
1920
                routerCfg.ProbabilityEstimatorType =
4✔
1921
                        routing.AprioriEstimatorName
4✔
1922

4✔
1923
                targetCfg := routerCfg.AprioriConfig
4✔
1924
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
4✔
1925
                targetCfg.Weight = c.AprioriWeight
4✔
1926
                targetCfg.CapacityFraction = c.CapacityFraction
4✔
1927
                targetCfg.HopProbability = c.AprioriHopProbability
4✔
1928

1929
        case routing.BimodalConfig:
4✔
1930
                routerCfg.ProbabilityEstimatorType =
4✔
1931
                        routing.BimodalEstimatorName
4✔
1932

4✔
1933
                targetCfg := routerCfg.BimodalConfig
4✔
1934
                targetCfg.Scale = int64(c.BimodalScaleMsat)
4✔
1935
                targetCfg.NodeWeight = c.BimodalNodeWeight
4✔
1936
                targetCfg.DecayTime = c.BimodalDecayTime
4✔
1937
        }
1938

1939
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
4✔
1940
}
1941

1942
// registerBlockConsumers registers the subsystems that consume block events.
1943
// By calling `RegisterQueue`, a list of subsystems are registered in the
1944
// blockbeat for block notifications. When a new block arrives, the subsystems
1945
// in the same queue are notified sequentially, and different queues are
1946
// notified concurrently.
1947
//
1948
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1949
// a new `RegisterQueue` call.
1950
func (s *server) registerBlockConsumers() {
4✔
1951
        // In this queue, when a new block arrives, it will be received and
4✔
1952
        // processed in this order: chainArb -> sweeper -> txPublisher.
4✔
1953
        consumers := []chainio.Consumer{
4✔
1954
                s.chainArb,
4✔
1955
                s.sweeper,
4✔
1956
                s.txPublisher,
4✔
1957
        }
4✔
1958
        s.blockbeatDispatcher.RegisterQueue(consumers)
4✔
1959
}
4✔
1960

1961
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1962
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1963
// may differ from what is on disk.
1964
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1965
        error) {
4✔
1966

4✔
1967
        data, err := u.DataToSign()
4✔
1968
        if err != nil {
4✔
1969
                return nil, err
×
1970
        }
×
1971

1972
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
4✔
1973
}
1974

1975
// createLivenessMonitor creates a set of health checks using our configured
1976
// values and uses these checks to create a liveness monitor. Available
1977
// health checks,
1978
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1979
//   - diskCheck
1980
//   - tlsHealthCheck
1981
//   - torController, only created when tor is enabled.
1982
//
1983
// If a health check has been disabled by setting attempts to 0, our monitor
1984
// will not run it.
1985
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1986
        leaderElector cluster.LeaderElector) {
4✔
1987

4✔
1988
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
4✔
1989
        if cfg.Bitcoin.Node == "nochainbackend" {
4✔
1990
                srvrLog.Info("Disabling chain backend checks for " +
×
1991
                        "nochainbackend mode")
×
1992

×
1993
                chainBackendAttempts = 0
×
1994
        }
×
1995

1996
        chainHealthCheck := healthcheck.NewObservation(
4✔
1997
                "chain backend",
4✔
1998
                cc.HealthCheck,
4✔
1999
                cfg.HealthChecks.ChainCheck.Interval,
4✔
2000
                cfg.HealthChecks.ChainCheck.Timeout,
4✔
2001
                cfg.HealthChecks.ChainCheck.Backoff,
4✔
2002
                chainBackendAttempts,
4✔
2003
        )
4✔
2004

4✔
2005
        diskCheck := healthcheck.NewObservation(
4✔
2006
                "disk space",
4✔
2007
                func() error {
4✔
2008
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2009
                                cfg.LndDir,
×
2010
                        )
×
2011
                        if err != nil {
×
2012
                                return err
×
2013
                        }
×
2014

2015
                        // If we have more free space than we require,
2016
                        // we return a nil error.
2017
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2018
                                return nil
×
2019
                        }
×
2020

2021
                        return fmt.Errorf("require: %v free space, got: %v",
×
2022
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2023
                                free)
×
2024
                },
2025
                cfg.HealthChecks.DiskCheck.Interval,
2026
                cfg.HealthChecks.DiskCheck.Timeout,
2027
                cfg.HealthChecks.DiskCheck.Backoff,
2028
                cfg.HealthChecks.DiskCheck.Attempts,
2029
        )
2030

2031
        tlsHealthCheck := healthcheck.NewObservation(
4✔
2032
                "tls",
4✔
2033
                func() error {
4✔
2034
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2035
                                s.cc.KeyRing,
×
2036
                        )
×
2037
                        if err != nil {
×
2038
                                return err
×
2039
                        }
×
2040
                        if expired {
×
2041
                                return fmt.Errorf("TLS certificate is "+
×
2042
                                        "expired as of %v", expTime)
×
2043
                        }
×
2044

2045
                        // If the certificate is not outdated, no error needs
2046
                        // to be returned
2047
                        return nil
×
2048
                },
2049
                cfg.HealthChecks.TLSCheck.Interval,
2050
                cfg.HealthChecks.TLSCheck.Timeout,
2051
                cfg.HealthChecks.TLSCheck.Backoff,
2052
                cfg.HealthChecks.TLSCheck.Attempts,
2053
        )
2054

2055
        checks := []*healthcheck.Observation{
4✔
2056
                chainHealthCheck, diskCheck, tlsHealthCheck,
4✔
2057
        }
4✔
2058

4✔
2059
        // If Tor is enabled, add the healthcheck for tor connection.
4✔
2060
        if s.torController != nil {
4✔
2061
                torConnectionCheck := healthcheck.NewObservation(
×
2062
                        "tor connection",
×
2063
                        func() error {
×
2064
                                return healthcheck.CheckTorServiceStatus(
×
2065
                                        s.torController,
×
2066
                                        func() error {
×
2067
                                                return s.createNewHiddenService(
×
2068
                                                        context.TODO(),
×
2069
                                                )
×
2070
                                        },
×
2071
                                )
2072
                        },
2073
                        cfg.HealthChecks.TorConnection.Interval,
2074
                        cfg.HealthChecks.TorConnection.Timeout,
2075
                        cfg.HealthChecks.TorConnection.Backoff,
2076
                        cfg.HealthChecks.TorConnection.Attempts,
2077
                )
2078
                checks = append(checks, torConnectionCheck)
×
2079
        }
2080

2081
        // If remote signing is enabled, add the healthcheck for the remote
2082
        // signing RPC interface.
2083
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
8✔
2084
                // Because we have two cascading timeouts here, we need to add
4✔
2085
                // some slack to the "outer" one of them in case the "inner"
4✔
2086
                // returns exactly on time.
4✔
2087
                overhead := time.Millisecond * 10
4✔
2088

4✔
2089
                remoteSignerConnectionCheck := healthcheck.NewObservation(
4✔
2090
                        "remote signer connection",
4✔
2091
                        rpcwallet.HealthCheck(
4✔
2092
                                s.cfg.RemoteSigner,
4✔
2093

4✔
2094
                                // For the health check we might to be even
4✔
2095
                                // stricter than the initial/normal connect, so
4✔
2096
                                // we use the health check timeout here.
4✔
2097
                                cfg.HealthChecks.RemoteSigner.Timeout,
4✔
2098
                        ),
4✔
2099
                        cfg.HealthChecks.RemoteSigner.Interval,
4✔
2100
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
4✔
2101
                        cfg.HealthChecks.RemoteSigner.Backoff,
4✔
2102
                        cfg.HealthChecks.RemoteSigner.Attempts,
4✔
2103
                )
4✔
2104
                checks = append(checks, remoteSignerConnectionCheck)
4✔
2105
        }
4✔
2106

2107
        // If we have a leader elector, we add a health check to ensure we are
2108
        // still the leader. During normal operation, we should always be the
2109
        // leader, but there are circumstances where this may change, such as
2110
        // when we lose network connectivity for long enough expiring out lease.
2111
        if leaderElector != nil {
4✔
2112
                leaderCheck := healthcheck.NewObservation(
×
2113
                        "leader status",
×
2114
                        func() error {
×
2115
                                // Check if we are still the leader. Note that
×
2116
                                // we don't need to use a timeout context here
×
2117
                                // as the healthcheck observer will handle the
×
2118
                                // timeout case for us.
×
2119
                                timeoutCtx, cancel := context.WithTimeout(
×
2120
                                        context.Background(),
×
2121
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2122
                                )
×
2123
                                defer cancel()
×
2124

×
2125
                                leader, err := leaderElector.IsLeader(
×
2126
                                        timeoutCtx,
×
2127
                                )
×
2128
                                if err != nil {
×
2129
                                        return fmt.Errorf("unable to check if "+
×
2130
                                                "still leader: %v", err)
×
2131
                                }
×
2132

2133
                                if !leader {
×
2134
                                        srvrLog.Debug("Not the current leader")
×
2135
                                        return fmt.Errorf("not the current " +
×
2136
                                                "leader")
×
2137
                                }
×
2138

2139
                                return nil
×
2140
                        },
2141
                        cfg.HealthChecks.LeaderCheck.Interval,
2142
                        cfg.HealthChecks.LeaderCheck.Timeout,
2143
                        cfg.HealthChecks.LeaderCheck.Backoff,
2144
                        cfg.HealthChecks.LeaderCheck.Attempts,
2145
                )
2146

2147
                checks = append(checks, leaderCheck)
×
2148
        }
2149

2150
        // If we have not disabled all of our health checks, we create a
2151
        // liveness monitor with our configured checks.
2152
        s.livenessMonitor = healthcheck.NewMonitor(
4✔
2153
                &healthcheck.Config{
4✔
2154
                        Checks:   checks,
4✔
2155
                        Shutdown: srvrLog.Criticalf,
4✔
2156
                },
4✔
2157
        )
4✔
2158
}
2159

2160
// Started returns true if the server has been started, and false otherwise.
2161
// NOTE: This function is safe for concurrent access.
2162
func (s *server) Started() bool {
4✔
2163
        return atomic.LoadInt32(&s.active) != 0
4✔
2164
}
4✔
2165

2166
// cleaner is used to aggregate "cleanup" functions during an operation that
2167
// starts several subsystems. In case one of the subsystem fails to start
2168
// and a proper resource cleanup is required, the "run" method achieves this
2169
// by running all these added "cleanup" functions.
2170
type cleaner []func() error
2171

2172
// add is used to add a cleanup function to be called when
2173
// the run function is executed.
2174
func (c cleaner) add(cleanup func() error) cleaner {
4✔
2175
        return append(c, cleanup)
4✔
2176
}
4✔
2177

2178
// run is used to run all the previousely added cleanup functions.
2179
func (c cleaner) run() {
×
2180
        for i := len(c) - 1; i >= 0; i-- {
×
2181
                if err := c[i](); err != nil {
×
2182
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2183
                }
×
2184
        }
2185
}
2186

2187
// Start starts the main daemon server, all requested listeners, and any helper
2188
// goroutines.
2189
// NOTE: This function is safe for concurrent access.
2190
//
2191
//nolint:funlen
2192
func (s *server) Start(ctx context.Context) error {
4✔
2193
        var startErr error
4✔
2194

4✔
2195
        // If one sub system fails to start, the following code ensures that the
4✔
2196
        // previous started ones are stopped. It also ensures a proper wallet
4✔
2197
        // shutdown which is important for releasing its resources (boltdb, etc...)
4✔
2198
        cleanup := cleaner{}
4✔
2199

4✔
2200
        s.start.Do(func() {
8✔
2201
                // Before starting any subsystems, repair any link nodes that
4✔
2202
                // may have been incorrectly pruned due to the race condition
4✔
2203
                // that was fixed in the link node pruning logic. This must
4✔
2204
                // happen before the chain arbitrator and other subsystems load
4✔
2205
                // channels, to ensure the invariant "link node exists iff
4✔
2206
                // channels exist" is maintained.
4✔
2207
                err := s.chanStateDB.RepairLinkNodes(s.cfg.ActiveNetParams.Net)
4✔
2208
                if err != nil {
4✔
2209
                        srvrLog.Errorf("Failed to repair link nodes: %v", err)
×
2210

×
2211
                        startErr = err
×
2212

×
2213
                        return
×
2214
                }
×
2215

2216
                cleanup = cleanup.add(s.customMessageServer.Stop)
4✔
2217
                if err := s.customMessageServer.Start(); err != nil {
4✔
2218
                        startErr = err
×
2219
                        return
×
2220
                }
×
2221

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

2228
                if s.hostAnn != nil {
4✔
2229
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2230
                        if err := s.hostAnn.Start(); err != nil {
×
2231
                                startErr = err
×
2232
                                return
×
2233
                        }
×
2234
                }
2235

2236
                if s.livenessMonitor != nil {
8✔
2237
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
4✔
2238
                        if err := s.livenessMonitor.Start(); err != nil {
4✔
2239
                                startErr = err
×
2240
                                return
×
2241
                        }
×
2242
                }
2243

2244
                // Start the notification server. This is used so channel
2245
                // management goroutines can be notified when a funding
2246
                // transaction reaches a sufficient number of confirmations, or
2247
                // when the input for the funding transaction is spent in an
2248
                // attempt at an uncooperative close by the counterparty.
2249
                cleanup = cleanup.add(s.sigPool.Stop)
4✔
2250
                if err := s.sigPool.Start(); err != nil {
4✔
2251
                        startErr = err
×
2252
                        return
×
2253
                }
×
2254

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

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

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

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

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

2285
                cleanup = cleanup.add(func() error {
4✔
2286
                        return s.peerNotifier.Stop()
×
2287
                })
×
2288
                if err := s.peerNotifier.Start(); err != nil {
4✔
2289
                        startErr = err
×
2290
                        return
×
2291
                }
×
2292

2293
                cleanup = cleanup.add(s.htlcNotifier.Stop)
4✔
2294
                if err := s.htlcNotifier.Start(); err != nil {
4✔
2295
                        startErr = err
×
2296
                        return
×
2297
                }
×
2298

2299
                if s.towerClientMgr != nil {
8✔
2300
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
4✔
2301
                        if err := s.towerClientMgr.Start(); err != nil {
4✔
2302
                                startErr = err
×
2303
                                return
×
2304
                        }
×
2305
                }
2306

2307
                beat, err := s.getStartingBeat()
4✔
2308
                if err != nil {
4✔
2309
                        startErr = err
×
2310
                        return
×
2311
                }
×
2312

2313
                cleanup = cleanup.add(s.txPublisher.Stop)
4✔
2314
                if err := s.txPublisher.Start(beat); err != nil {
4✔
2315
                        startErr = err
×
2316
                        return
×
2317
                }
×
2318

2319
                cleanup = cleanup.add(s.sweeper.Stop)
4✔
2320
                if err := s.sweeper.Start(beat); err != nil {
4✔
2321
                        startErr = err
×
2322
                        return
×
2323
                }
×
2324

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

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

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

2343
                // htlcSwitch must be started before chainArb since the latter
2344
                // relies on htlcSwitch to deliver resolution message upon
2345
                // start.
2346
                cleanup = cleanup.add(s.htlcSwitch.Stop)
4✔
2347
                if err := s.htlcSwitch.Start(); err != nil {
4✔
2348
                        startErr = err
×
2349
                        return
×
2350
                }
×
2351

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

2358
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
4✔
2359
                if err := s.invoiceHtlcModifier.Start(); err != nil {
4✔
2360
                        startErr = err
×
2361
                        return
×
2362
                }
×
2363

2364
                cleanup = cleanup.add(s.chainArb.Stop)
4✔
2365
                if err := s.chainArb.Start(beat); err != nil {
4✔
2366
                        startErr = err
×
2367
                        return
×
2368
                }
×
2369

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

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

2382
                cleanup = cleanup.add(s.chanRouter.Stop)
4✔
2383
                if err := s.chanRouter.Start(); err != nil {
4✔
2384
                        startErr = err
×
2385
                        return
×
2386
                }
×
2387
                // The authGossiper depends on the chanRouter and therefore
2388
                // should be started after it.
2389
                cleanup = cleanup.add(s.authGossiper.Stop)
4✔
2390
                if err := s.authGossiper.Start(); err != nil {
4✔
2391
                        startErr = err
×
2392
                        return
×
2393
                }
×
2394

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

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

2407
                cleanup = cleanup.add(func() error {
4✔
2408
                        s.sphinxOnionMsg.Stop()
×
2409
                        return nil
×
2410
                })
×
2411
                if err := s.sphinxOnionMsg.Start(); err != nil {
4✔
2412
                        startErr = err
×
2413
                        return
×
2414
                }
×
2415

2416
                // Create the onion message actor factory that will be used to
2417
                // spawn per-peer actors for handling onion messages. Skip if
2418
                // onion messaging is disabled via config.
2419
                if !s.cfg.ProtocolOptions.NoOnionMessages() {
8✔
2420
                        resolver := onionmessage.NewGraphNodeResolver(
4✔
2421
                                s.graphDB, s.identityECDH.PubKey(),
4✔
2422
                        )
4✔
2423
                        s.onionActorFactory = onionmessage.NewOnionActorFactory(
4✔
2424
                                s.sphinxOnionMsg, resolver, s,
4✔
2425
                                s.onionMessageServer,
4✔
2426
                        )
4✔
2427

4✔
2428
                        s.defaultOnionActorOpts = onionmessage.
4✔
2429
                                DefaultOnionActorOpts()
4✔
2430

4✔
2431
                        // Build the global and per-peer onion message rate
4✔
2432
                        // limiters from the configured values, then compose
4✔
2433
                        // them behind a single IngressLimiter so the peer
4✔
2434
                        // package only needs to carry one field. A zero
4✔
2435
                        // kbps or a zero burst-bytes disables the
4✔
2436
                        // corresponding bucket; rates are expressed in
4✔
2437
                        // decimal kilobits per second and bursts in bytes
4✔
2438
                        // so operators can reason about onion message
4✔
2439
                        // ingress in terms of bandwidth rather than raw
4✔
2440
                        // message counts.
4✔
2441
                        onionPeerLim := onionmessage.NewPeerRateLimiter(
4✔
2442
                                s.cfg.ProtocolOptions.OnionMsgPeerKbps,
4✔
2443
                                s.cfg.ProtocolOptions.OnionMsgPeerBurstBytes,
4✔
2444
                        )
4✔
2445
                        onionGlobalLim := onionmessage.NewGlobalLimiter(
4✔
2446
                                s.cfg.ProtocolOptions.OnionMsgGlobalKbps,
4✔
2447
                                s.cfg.ProtocolOptions.OnionMsgGlobalBurstBytes,
4✔
2448
                        )
4✔
2449
                        s.onionLimiter = onionmessage.NewIngressLimiter(
4✔
2450
                                onionPeerLim, onionGlobalLim,
4✔
2451
                        )
4✔
2452
                }
4✔
2453

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

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

2466
                cleanup.add(func() error {
4✔
2467
                        s.missionController.StopStoreTickers()
×
2468
                        return nil
×
2469
                })
×
2470
                s.missionController.RunStoreTickers()
4✔
2471

4✔
2472
                // Before we start the connMgr, we'll check to see if we have
4✔
2473
                // any backups to recover. We do this now as we want to ensure
4✔
2474
                // that have all the information we need to handle channel
4✔
2475
                // recovery _before_ we even accept connections from any peers.
4✔
2476
                chanRestorer := &chanDBRestorer{
4✔
2477
                        db:         s.chanStateDB,
4✔
2478
                        secretKeys: s.cc.KeyRing,
4✔
2479
                        chainArb:   s.chainArb,
4✔
2480
                }
4✔
2481
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
4✔
2482
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2483
                                s.chansToRestore.PackedSingleChanBackups,
×
2484
                                s.cc.KeyRing, chanRestorer, s,
×
2485
                        )
×
2486
                        if err != nil {
×
2487
                                startErr = fmt.Errorf("unable to unpack single "+
×
2488
                                        "backups: %v", err)
×
2489
                                return
×
2490
                        }
×
2491
                }
2492
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
8✔
2493
                        _, err := chanbackup.UnpackAndRecoverMulti(
4✔
2494
                                s.chansToRestore.PackedMultiChanBackup,
4✔
2495
                                s.cc.KeyRing, chanRestorer, s,
4✔
2496
                        )
4✔
2497
                        if err != nil {
4✔
2498
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2499
                                        "backup: %v", err)
×
2500
                                return
×
2501
                        }
×
2502
                }
2503

2504
                // chanSubSwapper must be started after the `channelNotifier`
2505
                // because it depends on channel events as a synchronization
2506
                // point.
2507
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
4✔
2508
                if err := s.chanSubSwapper.Start(); err != nil {
4✔
2509
                        startErr = err
×
2510
                        return
×
2511
                }
×
2512

2513
                if s.torController != nil {
4✔
2514
                        cleanup = cleanup.add(s.torController.Stop)
×
2515
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2516
                                startErr = err
×
2517
                                return
×
2518
                        }
×
2519
                }
2520

2521
                if s.natTraversal != nil {
4✔
2522
                        s.wg.Add(1)
×
2523
                        go s.watchExternalIP()
×
2524
                }
×
2525

2526
                // Start connmgr last to prevent connections before init.
2527
                cleanup = cleanup.add(func() error {
4✔
2528
                        s.connMgr.Stop()
×
2529
                        return nil
×
2530
                })
×
2531

2532
                // RESOLVE: s.connMgr.Start() is called here, but
2533
                // brontide.NewListener() is called in newServer. This means
2534
                // that we are actually listening and partially accepting
2535
                // inbound connections even before the connMgr starts.
2536
                //
2537
                // TODO(yy): move the log into the connMgr's `Start` method.
2538
                srvrLog.Info("connMgr starting...")
4✔
2539
                s.connMgr.Start()
4✔
2540
                srvrLog.Debug("connMgr started")
4✔
2541

4✔
2542
                // If peers are specified as a config option, we'll add those
4✔
2543
                // peers first.
4✔
2544
                for _, peerAddrCfg := range s.cfg.AddPeers {
8✔
2545
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
4✔
2546
                                peerAddrCfg,
4✔
2547
                        )
4✔
2548
                        if err != nil {
4✔
2549
                                startErr = fmt.Errorf("unable to parse peer "+
×
2550
                                        "pubkey from config: %v", err)
×
2551
                                return
×
2552
                        }
×
2553
                        addr, err := parseAddr(parsedHost, s.cfg.net)
4✔
2554
                        if err != nil {
4✔
2555
                                startErr = fmt.Errorf("unable to parse peer "+
×
2556
                                        "address provided as a config option: "+
×
2557
                                        "%v", err)
×
2558
                                return
×
2559
                        }
×
2560

2561
                        peerAddr := &lnwire.NetAddress{
4✔
2562
                                IdentityKey: parsedPubkey,
4✔
2563
                                Address:     addr,
4✔
2564
                                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
2565
                        }
4✔
2566

4✔
2567
                        err = s.ConnectToPeer(
4✔
2568
                                peerAddr, true,
4✔
2569
                                s.cfg.ConnectionTimeout,
4✔
2570
                        )
4✔
2571
                        if err != nil {
4✔
2572
                                startErr = fmt.Errorf("unable to connect to "+
×
2573
                                        "peer address provided as a config "+
×
2574
                                        "option: %v", err)
×
2575
                                return
×
2576
                        }
×
2577
                }
2578

2579
                // Subscribe to NodeAnnouncements that advertise new addresses
2580
                // our persistent peers.
2581
                if err := s.updatePersistentPeerAddrs(); err != nil {
4✔
2582
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2583
                                "addr: %v", err)
×
2584

×
2585
                        startErr = err
×
2586
                        return
×
2587
                }
×
2588

2589
                // With all the relevant sub-systems started, we'll now attempt
2590
                // to establish persistent connections to our direct channel
2591
                // collaborators within the network. Before doing so however,
2592
                // we'll prune our set of link nodes to ensure we don't
2593
                // reconnect to any nodes we no longer have open channels with.
2594
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
4✔
2595
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2596

×
2597
                        startErr = err
×
2598
                        return
×
2599
                }
×
2600

2601
                if err := s.establishPersistentConnections(ctx); err != nil {
4✔
2602
                        srvrLog.Errorf("Failed to establish persistent "+
×
2603
                                "connections: %v", err)
×
2604
                }
×
2605

2606
                // setSeedList is a helper function that turns multiple DNS seed
2607
                // server tuples from the command line or config file into the
2608
                // data structure we need and does a basic formal sanity check
2609
                // in the process.
2610
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
4✔
2611
                        if len(tuples) == 0 {
×
2612
                                return
×
2613
                        }
×
2614

2615
                        result := make([][2]string, len(tuples))
×
2616
                        for idx, tuple := range tuples {
×
2617
                                tuple = strings.TrimSpace(tuple)
×
2618
                                if len(tuple) == 0 {
×
2619
                                        return
×
2620
                                }
×
2621

2622
                                servers := strings.Split(tuple, ",")
×
2623
                                if len(servers) > 2 || len(servers) == 0 {
×
2624
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2625
                                                "seed tuple: %v", servers)
×
2626
                                        return
×
2627
                                }
×
2628

2629
                                copy(result[idx][:], servers)
×
2630
                        }
2631

2632
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2633
                }
2634

2635
                // Let users overwrite the DNS seed nodes. We only allow them
2636
                // for bitcoin mainnet/testnet/signet.
2637
                if s.cfg.Bitcoin.MainNet {
4✔
2638
                        setSeedList(
×
2639
                                s.cfg.Bitcoin.DNSSeeds,
×
2640
                                chainreg.BitcoinMainnetGenesis,
×
2641
                        )
×
2642
                }
×
2643
                if s.cfg.Bitcoin.TestNet3 {
4✔
2644
                        setSeedList(
×
2645
                                s.cfg.Bitcoin.DNSSeeds,
×
2646
                                chainreg.BitcoinTestnetGenesis,
×
2647
                        )
×
2648
                }
×
2649
                if s.cfg.Bitcoin.TestNet4 {
4✔
2650
                        setSeedList(
×
2651
                                s.cfg.Bitcoin.DNSSeeds,
×
2652
                                chainreg.BitcoinTestnet4Genesis,
×
2653
                        )
×
2654
                }
×
2655
                if s.cfg.Bitcoin.SigNet {
4✔
2656
                        setSeedList(
×
2657
                                s.cfg.Bitcoin.DNSSeeds,
×
2658
                                chainreg.BitcoinSignetGenesis,
×
2659
                        )
×
2660
                }
×
2661

2662
                // If network bootstrapping hasn't been disabled, then we'll
2663
                // configure the set of active bootstrappers, and launch a
2664
                // dedicated goroutine to maintain a set of persistent
2665
                // connections.
2666
                if !s.cfg.NoNetBootstrap {
8✔
2667
                        bootstrappers, err := initNetworkBootstrappers(s)
4✔
2668
                        if err != nil {
4✔
2669
                                startErr = err
×
2670
                                return
×
2671
                        }
×
2672

2673
                        s.wg.Add(1)
4✔
2674
                        go s.peerBootstrapper(
4✔
2675
                                ctx, defaultMinPeers, bootstrappers,
4✔
2676
                        )
4✔
2677
                } else {
4✔
2678
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
4✔
2679
                }
4✔
2680

2681
                // Start the blockbeat after all other subsystems have been
2682
                // started so they are ready to receive new blocks.
2683
                cleanup = cleanup.add(func() error {
4✔
2684
                        s.blockbeatDispatcher.Stop()
×
2685
                        return nil
×
2686
                })
×
2687
                if err := s.blockbeatDispatcher.Start(); err != nil {
4✔
2688
                        startErr = err
×
2689
                        return
×
2690
                }
×
2691

2692
                // Set the active flag now that we've completed the full
2693
                // startup.
2694
                atomic.StoreInt32(&s.active, 1)
4✔
2695
        })
2696

2697
        if startErr != nil {
4✔
2698
                cleanup.run()
×
2699
        }
×
2700
        return startErr
4✔
2701
}
2702

2703
// Stop gracefully shutsdown the main daemon server. This function will signal
2704
// any active goroutines, or helper objects to exit, then blocks until they've
2705
// all successfully exited. Additionally, any/all listeners are closed.
2706
// NOTE: This function is safe for concurrent access.
2707
func (s *server) Stop() error {
4✔
2708
        s.stop.Do(func() {
8✔
2709
                atomic.StoreInt32(&s.stopping, 1)
4✔
2710

4✔
2711
                ctx := context.Background()
4✔
2712

4✔
2713
                close(s.quit)
4✔
2714

4✔
2715
                // Shutdown connMgr first to prevent conns during shutdown.
4✔
2716
                s.connMgr.Stop()
4✔
2717

4✔
2718
                // Stop dispatching blocks to other systems immediately.
4✔
2719
                s.blockbeatDispatcher.Stop()
4✔
2720

4✔
2721
                // Shutdown the onion router for onion messaging.
4✔
2722
                s.sphinxOnionMsg.Stop()
4✔
2723

4✔
2724
                // Shutdown the wallet, funding manager, and the rpc server.
4✔
2725
                if err := s.chanStatusMgr.Stop(); err != nil {
4✔
2726
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2727
                }
×
2728
                if err := s.htlcSwitch.Stop(); err != nil {
4✔
2729
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2730
                }
×
2731
                if err := s.sphinxPayment.Stop(); err != nil {
4✔
2732
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2733
                }
×
2734
                if err := s.invoices.Stop(); err != nil {
4✔
2735
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2736
                }
×
2737
                if err := s.interceptableSwitch.Stop(); err != nil {
4✔
2738
                        srvrLog.Warnf("failed to stop interceptable "+
×
2739
                                "switch: %v", err)
×
2740
                }
×
2741
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
4✔
2742
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2743
                                "modifier: %v", err)
×
2744
                }
×
2745
                if err := s.chanRouter.Stop(); err != nil {
4✔
2746
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2747
                }
×
2748
                if err := s.graphBuilder.Stop(); err != nil {
4✔
2749
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2750
                }
×
2751
                if err := s.graphDB.Stop(); err != nil {
4✔
2752
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2753
                }
×
2754
                if err := s.chainArb.Stop(); err != nil {
4✔
2755
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2756
                }
×
2757
                if err := s.fundingMgr.Stop(); err != nil {
4✔
2758
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2759
                }
×
2760
                if err := s.breachArbitrator.Stop(); err != nil {
4✔
2761
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2762
                                err)
×
2763
                }
×
2764
                if err := s.utxoNursery.Stop(); err != nil {
4✔
2765
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2766
                }
×
2767
                if err := s.authGossiper.Stop(); err != nil {
4✔
2768
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2769
                }
×
2770
                if err := s.sweeper.Stop(); err != nil {
4✔
2771
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2772
                }
×
2773
                if err := s.txPublisher.Stop(); err != nil {
4✔
2774
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2775
                }
×
2776
                if err := s.channelNotifier.Stop(); err != nil {
4✔
2777
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2778
                }
×
2779
                if err := s.peerNotifier.Stop(); err != nil {
4✔
2780
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2781
                }
×
2782
                if err := s.htlcNotifier.Stop(); err != nil {
4✔
2783
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2784
                }
×
2785

2786
                // Update channel.backup file. Make sure to do it before
2787
                // stopping chanSubSwapper.
2788
                singles, err := chanbackup.FetchStaticChanBackups(
4✔
2789
                        ctx, s.chanStateDB, s.addrSource,
4✔
2790
                )
4✔
2791
                if err != nil {
4✔
2792
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2793
                                err)
×
2794
                } else {
4✔
2795
                        err := s.chanSubSwapper.ManualUpdate(singles)
4✔
2796
                        if err != nil {
8✔
2797
                                srvrLog.Warnf("Manual update of channel "+
4✔
2798
                                        "backup failed: %v", err)
4✔
2799
                        }
4✔
2800
                }
2801

2802
                if err := s.chanSubSwapper.Stop(); err != nil {
4✔
2803
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2804
                }
×
2805
                if err := s.cc.ChainNotifier.Stop(); err != nil {
4✔
2806
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2807
                }
×
2808
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
4✔
2809
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2810
                                err)
×
2811
                }
×
2812
                if err := s.chanEventStore.Stop(); err != nil {
4✔
2813
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2814
                                err)
×
2815
                }
×
2816
                s.missionController.StopStoreTickers()
4✔
2817

4✔
2818
                // Disconnect from each active peers to ensure that
4✔
2819
                // peerTerminationWatchers signal completion to each peer.
4✔
2820
                for _, peer := range s.Peers() {
8✔
2821
                        err := s.DisconnectPeer(peer.IdentityKey())
4✔
2822
                        if err != nil {
4✔
2823
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2824
                                        "received error: %v", peer.IdentityKey(),
×
2825
                                        err,
×
2826
                                )
×
2827
                        }
×
2828
                }
2829

2830
                // Now that all connections have been torn down, stop the tower
2831
                // client which will reliably flush all queued states to the
2832
                // tower. If this is halted for any reason, the force quit timer
2833
                // will kick in and abort to allow this method to return.
2834
                if s.towerClientMgr != nil {
8✔
2835
                        if err := s.towerClientMgr.Stop(); err != nil {
4✔
2836
                                srvrLog.Warnf("Unable to shut down tower "+
×
2837
                                        "client manager: %v", err)
×
2838
                        }
×
2839
                }
2840

2841
                if s.hostAnn != nil {
4✔
2842
                        if err := s.hostAnn.Stop(); err != nil {
×
2843
                                srvrLog.Warnf("unable to shut down host "+
×
2844
                                        "annoucner: %v", err)
×
2845
                        }
×
2846
                }
2847

2848
                if s.livenessMonitor != nil {
8✔
2849
                        if err := s.livenessMonitor.Stop(); err != nil {
4✔
2850
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2851
                                        "monitor: %v", err)
×
2852
                        }
×
2853
                }
2854

2855
                // Wait for all lingering goroutines to quit.
2856
                srvrLog.Debug("Waiting for server to shutdown...")
4✔
2857
                s.wg.Wait()
4✔
2858

4✔
2859
                srvrLog.Debug("Stopping buffer pools...")
4✔
2860
                s.sigPool.Stop()
4✔
2861
                s.writePool.Stop()
4✔
2862
                s.readPool.Stop()
4✔
2863

4✔
2864
                // Shut down the actor system last so any in-flight actor work
4✔
2865
                // triggered by the subsystems above has a chance to complete.
4✔
2866
                if err := s.actorSystem.Shutdown(); err != nil {
4✔
2867
                        srvrLog.Warnf("failed to stop actor system: %v", err)
×
2868
                }
×
2869
        })
2870

2871
        return nil
4✔
2872
}
2873

2874
// Stopped returns true if the server has been instructed to shutdown.
2875
// NOTE: This function is safe for concurrent access.
2876
func (s *server) Stopped() bool {
4✔
2877
        return atomic.LoadInt32(&s.stopping) != 0
4✔
2878
}
4✔
2879

2880
// configurePortForwarding attempts to set up port forwarding for the different
2881
// ports that the server will be listening on.
2882
//
2883
// NOTE: This should only be used when using some kind of NAT traversal to
2884
// automatically set up forwarding rules.
2885
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2886
        ip, err := s.natTraversal.ExternalIP()
×
2887
        if err != nil {
×
2888
                return nil, err
×
2889
        }
×
2890
        s.lastDetectedIP = ip
×
2891

×
2892
        externalIPs := make([]string, 0, len(ports))
×
2893
        for _, port := range ports {
×
2894
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2895
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2896
                        continue
×
2897
                }
2898

2899
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2900
                externalIPs = append(externalIPs, hostIP)
×
2901
        }
2902

2903
        return externalIPs, nil
×
2904
}
2905

2906
// removePortForwarding attempts to clear the forwarding rules for the different
2907
// ports the server is currently listening on.
2908
//
2909
// NOTE: This should only be used when using some kind of NAT traversal to
2910
// automatically set up forwarding rules.
2911
func (s *server) removePortForwarding() {
×
2912
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2913
        for _, port := range forwardedPorts {
×
2914
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2915
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2916
                                "port %d: %v", port, err)
×
2917
                }
×
2918
        }
2919
}
2920

2921
// watchExternalIP continuously checks for an updated external IP address every
2922
// 15 minutes. Once a new IP address has been detected, it will automatically
2923
// handle port forwarding rules and send updated node announcements to the
2924
// currently connected peers.
2925
//
2926
// NOTE: This MUST be run as a goroutine.
2927
func (s *server) watchExternalIP() {
×
2928
        defer s.wg.Done()
×
2929

×
2930
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2931
        // up by the server.
×
2932
        defer s.removePortForwarding()
×
2933

×
2934
        // Keep track of the external IPs set by the user to avoid replacing
×
2935
        // them when detecting a new IP.
×
2936
        ipsSetByUser := make(map[string]struct{})
×
2937
        for _, ip := range s.cfg.ExternalIPs {
×
2938
                ipsSetByUser[ip.String()] = struct{}{}
×
2939
        }
×
2940

2941
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2942

×
2943
        ticker := time.NewTicker(15 * time.Minute)
×
2944
        defer ticker.Stop()
×
2945
out:
×
2946
        for {
×
2947
                select {
×
2948
                case <-ticker.C:
×
2949
                        // We'll start off by making sure a new IP address has
×
2950
                        // been detected.
×
2951
                        ip, err := s.natTraversal.ExternalIP()
×
2952
                        if err != nil {
×
2953
                                srvrLog.Debugf("Unable to retrieve the "+
×
2954
                                        "external IP address: %v", err)
×
2955
                                continue
×
2956
                        }
2957

2958
                        // Periodically renew the NAT port forwarding.
2959
                        for _, port := range forwardedPorts {
×
2960
                                err := s.natTraversal.AddPortMapping(port)
×
2961
                                if err != nil {
×
2962
                                        srvrLog.Warnf("Unable to automatically "+
×
2963
                                                "re-create port forwarding using %s: %v",
×
2964
                                                s.natTraversal.Name(), err)
×
2965
                                } else {
×
2966
                                        srvrLog.Debugf("Automatically re-created "+
×
2967
                                                "forwarding for port %d using %s to "+
×
2968
                                                "advertise external IP",
×
2969
                                                port, s.natTraversal.Name())
×
2970
                                }
×
2971
                        }
2972

2973
                        if ip.Equal(s.lastDetectedIP) {
×
2974
                                continue
×
2975
                        }
2976

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

×
2979
                        // Next, we'll craft the new addresses that will be
×
2980
                        // included in the new node announcement and advertised
×
2981
                        // to the network. Each address will consist of the new
×
2982
                        // IP detected and one of the currently advertised
×
2983
                        // ports.
×
2984
                        var newAddrs []net.Addr
×
2985
                        for _, port := range forwardedPorts {
×
2986
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2987
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2988
                                if err != nil {
×
2989
                                        srvrLog.Debugf("Unable to resolve "+
×
2990
                                                "host %v: %v", addr, err)
×
2991
                                        continue
×
2992
                                }
2993

2994
                                newAddrs = append(newAddrs, addr)
×
2995
                        }
2996

2997
                        // Skip the update if we weren't able to resolve any of
2998
                        // the new addresses.
2999
                        if len(newAddrs) == 0 {
×
3000
                                srvrLog.Debug("Skipping node announcement " +
×
3001
                                        "update due to not being able to " +
×
3002
                                        "resolve any new addresses")
×
3003
                                continue
×
3004
                        }
3005

3006
                        // Now, we'll need to update the addresses in our node's
3007
                        // announcement in order to propagate the update
3008
                        // throughout the network. We'll only include addresses
3009
                        // that have a different IP from the previous one, as
3010
                        // the previous IP is no longer valid.
3011
                        currentNodeAnn := s.getNodeAnnouncement()
×
3012

×
3013
                        for _, addr := range currentNodeAnn.Addresses {
×
3014
                                host, _, err := net.SplitHostPort(addr.String())
×
3015
                                if err != nil {
×
3016
                                        srvrLog.Debugf("Unable to determine "+
×
3017
                                                "host from address %v: %v",
×
3018
                                                addr, err)
×
3019
                                        continue
×
3020
                                }
3021

3022
                                // We'll also make sure to include external IPs
3023
                                // set manually by the user.
3024
                                _, setByUser := ipsSetByUser[addr.String()]
×
3025
                                if setByUser || host != s.lastDetectedIP.String() {
×
3026
                                        newAddrs = append(newAddrs, addr)
×
3027
                                }
×
3028
                        }
3029

3030
                        // Then, we'll generate a new timestamped node
3031
                        // announcement with the updated addresses and broadcast
3032
                        // it to our peers.
3033
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3034
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3035
                        )
×
3036
                        if err != nil {
×
3037
                                srvrLog.Debugf("Unable to generate new node "+
×
3038
                                        "announcement: %v", err)
×
3039
                                continue
×
3040
                        }
3041

3042
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3043
                        if err != nil {
×
3044
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3045
                                        "announcement to peers: %v", err)
×
3046
                                continue
×
3047
                        }
3048

3049
                        // Finally, update the last IP seen to the current one.
3050
                        s.lastDetectedIP = ip
×
3051
                case <-s.quit:
×
3052
                        break out
×
3053
                }
3054
        }
3055
}
3056

3057
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3058
// based on the server, and currently active bootstrap mechanisms as defined
3059
// within the current configuration.
3060
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
4✔
3061
        srvrLog.Infof("Initializing peer network bootstrappers!")
4✔
3062

4✔
3063
        var bootStrappers []discovery.NetworkPeerBootstrapper
4✔
3064

4✔
3065
        // First, we'll create an instance of the ChannelGraphBootstrapper as
4✔
3066
        // this can be used by default if we've already partially seeded the
4✔
3067
        // network.
4✔
3068
        chanGraph := autopilot.ChannelGraphFromDatabase(s.v1Graph)
4✔
3069
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
4✔
3070
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
4✔
3071
        )
4✔
3072
        if err != nil {
4✔
3073
                return nil, err
×
3074
        }
×
3075
        bootStrappers = append(bootStrappers, graphBootstrapper)
4✔
3076

4✔
3077
        // If this isn't using simnet or regtest mode, then one of our
4✔
3078
        // additional bootstrapping sources will be the set of running DNS
4✔
3079
        // seeds.
4✔
3080
        if !s.cfg.Bitcoin.IsLocalNetwork() {
4✔
3081
                //nolint:ll
×
3082
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3083

×
3084
                // If we have a set of DNS seeds for this chain, then we'll add
×
3085
                // it as an additional bootstrapping source.
×
3086
                if ok {
×
3087
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3088
                                "seeds: %v", dnsSeeds)
×
3089

×
3090
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3091
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3092
                        )
×
3093
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3094
                }
×
3095
        }
3096

3097
        return bootStrappers, nil
4✔
3098
}
3099

3100
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3101
// needs to ignore, which is made of three parts,
3102
//   - the node itself needs to be skipped as it doesn't make sense to connect
3103
//     to itself.
3104
//   - the peers that already have connections with, as in s.peersByPub.
3105
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3106
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
4✔
3107
        s.mu.RLock()
4✔
3108
        defer s.mu.RUnlock()
4✔
3109

4✔
3110
        ignore := make(map[autopilot.NodeID]struct{})
4✔
3111

4✔
3112
        // We should ignore ourselves from bootstrapping.
4✔
3113
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
4✔
3114
        ignore[selfKey] = struct{}{}
4✔
3115

4✔
3116
        // Ignore all connected peers.
4✔
3117
        for _, peer := range s.peersByPub {
4✔
3118
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3119
                ignore[nID] = struct{}{}
×
3120
        }
×
3121

3122
        // Ignore all persistent peers as they have a dedicated reconnecting
3123
        // process.
3124
        for pubKeyStr := range s.persistentPeers {
4✔
3125
                var nID autopilot.NodeID
×
3126
                copy(nID[:], []byte(pubKeyStr))
×
3127
                ignore[nID] = struct{}{}
×
3128
        }
×
3129

3130
        return ignore
4✔
3131
}
3132

3133
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3134
// and maintain a target minimum number of outbound connections. With this
3135
// invariant, we ensure that our node is connected to a diverse set of peers
3136
// and that nodes newly joining the network receive an up to date network view
3137
// as soon as possible.
3138
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3139
        bootstrappers []discovery.NetworkPeerBootstrapper) {
4✔
3140

4✔
3141
        defer s.wg.Done()
4✔
3142

4✔
3143
        // Before we continue, init the ignore peers map.
4✔
3144
        ignoreList := s.createBootstrapIgnorePeers()
4✔
3145

4✔
3146
        // We'll start off by aggressively attempting connections to peers in
4✔
3147
        // order to be a part of the network as soon as possible.
4✔
3148
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
4✔
3149

4✔
3150
        // Once done, we'll attempt to maintain our target minimum number of
4✔
3151
        // peers.
4✔
3152
        //
4✔
3153
        // We'll use a 15 second backoff, and double the time every time an
4✔
3154
        // epoch fails up to a ceiling.
4✔
3155
        backOff := time.Second * 15
4✔
3156

4✔
3157
        // We'll create a new ticker to wake us up every 15 seconds so we can
4✔
3158
        // see if we've reached our minimum number of peers.
4✔
3159
        sampleTicker := time.NewTicker(backOff)
4✔
3160
        defer sampleTicker.Stop()
4✔
3161

4✔
3162
        // We'll use the number of attempts and errors to determine if we need
4✔
3163
        // to increase the time between discovery epochs.
4✔
3164
        var epochErrors uint32 // To be used atomically.
4✔
3165
        var epochAttempts uint32
4✔
3166

4✔
3167
        for {
8✔
3168
                select {
4✔
3169
                // The ticker has just woken us up, so we'll need to check if
3170
                // we need to attempt to connect our to any more peers.
3171
                case <-sampleTicker.C:
×
3172
                        // Obtain the current number of peers, so we can gauge
×
3173
                        // if we need to sample more peers or not.
×
3174
                        s.mu.RLock()
×
3175
                        numActivePeers := uint32(len(s.peersByPub))
×
3176
                        s.mu.RUnlock()
×
3177

×
3178
                        // If we have enough peers, then we can loop back
×
3179
                        // around to the next round as we're done here.
×
3180
                        if numActivePeers >= numTargetPeers {
×
3181
                                continue
×
3182
                        }
3183

3184
                        // If all of our attempts failed during this last back
3185
                        // off period, then will increase our backoff to 5
3186
                        // minute ceiling to avoid an excessive number of
3187
                        // queries
3188
                        //
3189
                        // TODO(roasbeef): add reverse policy too?
3190

3191
                        if epochAttempts > 0 &&
×
3192
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3193

×
3194
                                sampleTicker.Stop()
×
3195

×
3196
                                backOff *= 2
×
3197
                                if backOff > bootstrapBackOffCeiling {
×
3198
                                        backOff = bootstrapBackOffCeiling
×
3199
                                }
×
3200

3201
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3202
                                        "%v", backOff)
×
3203
                                sampleTicker = time.NewTicker(backOff)
×
3204
                                continue
×
3205
                        }
3206

3207
                        atomic.StoreUint32(&epochErrors, 0)
×
3208
                        epochAttempts = 0
×
3209

×
3210
                        // Since we know need more peers, we'll compute the
×
3211
                        // exact number we need to reach our threshold.
×
3212
                        numNeeded := numTargetPeers - numActivePeers
×
3213

×
3214
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3215
                                "peers", numNeeded)
×
3216

×
3217
                        // With the number of peers we need calculated, we'll
×
3218
                        // query the network bootstrappers to sample a set of
×
3219
                        // random addrs for us.
×
3220
                        //
×
3221
                        // Before we continue, get a copy of the ignore peers
×
3222
                        // map.
×
3223
                        ignoreList = s.createBootstrapIgnorePeers()
×
3224

×
3225
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3226
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3227
                        )
×
3228
                        if err != nil {
×
3229
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3230
                                        "peers: %v", err)
×
3231
                                continue
×
3232
                        }
3233

3234
                        // Finally, we'll launch a new goroutine for each
3235
                        // prospective peer candidates.
3236
                        for _, addr := range peerAddrs {
×
3237
                                epochAttempts++
×
3238

×
3239
                                go func(a *lnwire.NetAddress) {
×
3240
                                        // TODO(roasbeef): can do AS, subnet,
×
3241
                                        // country diversity, etc
×
3242
                                        errChan := make(chan error, 1)
×
3243
                                        s.connectToPeer(
×
3244
                                                a, errChan,
×
3245
                                                s.cfg.ConnectionTimeout,
×
3246
                                        )
×
3247
                                        select {
×
3248
                                        case err := <-errChan:
×
3249
                                                if err == nil {
×
3250
                                                        return
×
3251
                                                }
×
3252

3253
                                                srvrLog.Errorf("Unable to "+
×
3254
                                                        "connect to %v: %v",
×
3255
                                                        a, err)
×
3256
                                                atomic.AddUint32(&epochErrors, 1)
×
3257
                                        case <-s.quit:
×
3258
                                        }
3259
                                }(addr)
3260
                        }
3261
                case <-s.quit:
4✔
3262
                        return
4✔
3263
                }
3264
        }
3265
}
3266

3267
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3268
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3269
// query back off each time we encounter a failure.
3270
const bootstrapBackOffCeiling = time.Minute * 5
3271

3272
// initialPeerBootstrap attempts to continuously connect to peers on startup
3273
// until the target number of peers has been reached. This ensures that nodes
3274
// receive an up to date network view as soon as possible.
3275
func (s *server) initialPeerBootstrap(ctx context.Context,
3276
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3277
        bootstrappers []discovery.NetworkPeerBootstrapper) {
4✔
3278

4✔
3279
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
4✔
3280
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
4✔
3281

4✔
3282
        // We'll start off by waiting 2 seconds between failed attempts, then
4✔
3283
        // double each time we fail until we hit the bootstrapBackOffCeiling.
4✔
3284
        var delaySignal <-chan time.Time
4✔
3285
        delayTime := time.Second * 2
4✔
3286

4✔
3287
        // As want to be more aggressive, we'll use a lower back off celling
4✔
3288
        // then the main peer bootstrap logic.
4✔
3289
        backOffCeiling := bootstrapBackOffCeiling / 5
4✔
3290

4✔
3291
        for attempts := 0; ; attempts++ {
8✔
3292
                // Check if the server has been requested to shut down in order
4✔
3293
                // to prevent blocking.
4✔
3294
                if s.Stopped() {
4✔
3295
                        return
×
3296
                }
×
3297

3298
                // We can exit our aggressive initial peer bootstrapping stage
3299
                // if we've reached out target number of peers.
3300
                s.mu.RLock()
4✔
3301
                numActivePeers := uint32(len(s.peersByPub))
4✔
3302
                s.mu.RUnlock()
4✔
3303

4✔
3304
                if numActivePeers >= numTargetPeers {
8✔
3305
                        return
4✔
3306
                }
4✔
3307

3308
                if attempts > 0 {
4✔
UNCOV
3309
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3310
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3311
                                attempts)
×
UNCOV
3312

×
UNCOV
3313
                        // We've completed at least one iterating and haven't
×
UNCOV
3314
                        // finished, so we'll start to insert a delay period
×
UNCOV
3315
                        // between each attempt.
×
UNCOV
3316
                        delaySignal = time.After(delayTime)
×
UNCOV
3317
                        select {
×
UNCOV
3318
                        case <-delaySignal:
×
UNCOV
3319
                        case <-s.quit:
×
UNCOV
3320
                                return
×
3321
                        }
3322

3323
                        // After our delay, we'll double the time we wait up to
3324
                        // the max back off period.
UNCOV
3325
                        delayTime *= 2
×
UNCOV
3326
                        if delayTime > backOffCeiling {
×
3327
                                delayTime = backOffCeiling
×
3328
                        }
×
3329
                }
3330

3331
                // Otherwise, we'll request for the remaining number of peers
3332
                // in order to reach our target.
3333
                peersNeeded := numTargetPeers - numActivePeers
4✔
3334
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
4✔
3335
                        ctx, ignore, peersNeeded, bootstrappers...,
4✔
3336
                )
4✔
3337
                if err != nil {
4✔
UNCOV
3338
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3339
                                "peers: %v", err)
×
UNCOV
3340
                        continue
×
3341
                }
3342

3343
                // Then, we'll attempt to establish a connection to the
3344
                // different peer addresses retrieved by our bootstrappers.
3345
                var wg sync.WaitGroup
4✔
3346
                for _, bootstrapAddr := range bootstrapAddrs {
8✔
3347
                        wg.Add(1)
4✔
3348
                        go func(addr *lnwire.NetAddress) {
8✔
3349
                                defer wg.Done()
4✔
3350

4✔
3351
                                errChan := make(chan error, 1)
4✔
3352
                                go s.connectToPeer(
4✔
3353
                                        addr, errChan, s.cfg.ConnectionTimeout,
4✔
3354
                                )
4✔
3355

4✔
3356
                                // We'll only allow this connection attempt to
4✔
3357
                                // take up to 3 seconds. This allows us to move
4✔
3358
                                // quickly by discarding peers that are slowing
4✔
3359
                                // us down.
4✔
3360
                                select {
4✔
3361
                                case err := <-errChan:
4✔
3362
                                        if err == nil {
8✔
3363
                                                return
4✔
3364
                                        }
4✔
3365
                                        srvrLog.Errorf("Unable to connect to "+
×
3366
                                                "%v: %v", addr, err)
×
3367
                                // TODO: tune timeout? 3 seconds might be *too*
3368
                                // aggressive but works well.
3369
                                case <-time.After(3 * time.Second):
×
3370
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3371
                                                "to not establishing a "+
×
3372
                                                "connection within 3 seconds",
×
3373
                                                addr)
×
3374
                                case <-s.quit:
×
3375
                                }
3376
                        }(bootstrapAddr)
3377
                }
3378

3379
                wg.Wait()
4✔
3380
        }
3381
}
3382

3383
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3384
// order to listen for inbound connections over Tor.
3385
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3386
        // Determine the different ports the server is listening on. The onion
×
3387
        // service's virtual port will map to these ports and one will be picked
×
3388
        // at random when the onion service is being accessed.
×
3389
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3390
        for _, listenAddr := range s.listenAddrs {
×
3391
                port := listenAddr.(*net.TCPAddr).Port
×
3392
                listenPorts = append(listenPorts, port)
×
3393
        }
×
3394

3395
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3396
        if err != nil {
×
3397
                return err
×
3398
        }
×
3399

3400
        // Once the port mapping has been set, we can go ahead and automatically
3401
        // create our onion service. The service's private key will be saved to
3402
        // disk in order to regain access to this service when restarting `lnd`.
3403
        onionCfg := tor.AddOnionConfig{
×
3404
                VirtualPort: defaultPeerPort,
×
3405
                TargetPorts: listenPorts,
×
3406
                Store: tor.NewOnionFile(
×
3407
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3408
                        encrypter,
×
3409
                ),
×
3410
        }
×
3411

×
3412
        switch {
×
3413
        case s.cfg.Tor.V2:
×
3414
                onionCfg.Type = tor.V2
×
3415
        case s.cfg.Tor.V3:
×
3416
                onionCfg.Type = tor.V3
×
3417
        }
3418

3419
        addr, err := s.torController.AddOnion(onionCfg)
×
3420
        if err != nil {
×
3421
                return err
×
3422
        }
×
3423

3424
        // Now that the onion service has been created, we'll add the onion
3425
        // address it can be reached at to our list of advertised addresses.
3426
        newNodeAnn, err := s.genNodeAnnouncement(
×
3427
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3428
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3429
                },
×
3430
        )
3431
        if err != nil {
×
3432
                return fmt.Errorf("unable to generate new node "+
×
3433
                        "announcement: %v", err)
×
3434
        }
×
3435

3436
        // Finally, we'll update the on-disk version of our announcement so it
3437
        // will eventually propagate to nodes in the network.
3438
        selfNode := models.NewV1Node(
×
3439
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3440
                        Addresses:    newNodeAnn.Addresses,
×
3441
                        Features:     newNodeAnn.Features,
×
3442
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3443
                        Color:        newNodeAnn.RGBColor,
×
3444
                        Alias:        newNodeAnn.Alias.String(),
×
3445
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3446
                },
×
3447
        )
×
3448

×
3449
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3450
                return fmt.Errorf("can't set self node: %w", err)
×
3451
        }
×
3452

3453
        return nil
×
3454
}
3455

3456
// findChannel finds a channel given a public key and ChannelID. It is an
3457
// optimization that is quicker than seeking for a channel given only the
3458
// ChannelID.
3459
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3460
        *channeldb.OpenChannel, error) {
4✔
3461

4✔
3462
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
4✔
3463
        if err != nil {
4✔
3464
                return nil, err
×
3465
        }
×
3466

3467
        for _, channel := range nodeChans {
8✔
3468
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
8✔
3469
                        return channel, nil
4✔
3470
                }
4✔
3471
        }
3472

3473
        return nil, fmt.Errorf("unable to find channel")
4✔
3474
}
3475

3476
// getNodeAnnouncement fetches the current, fully signed node announcement.
3477
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
4✔
3478
        s.mu.Lock()
4✔
3479
        defer s.mu.Unlock()
4✔
3480

4✔
3481
        return *s.currentNodeAnn
4✔
3482
}
4✔
3483

3484
// genNodeAnnouncement generates and returns the current fully signed node
3485
// announcement. The time stamp of the announcement will be updated in order
3486
// to ensure it propagates through the network.
3487
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3488
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
4✔
3489

4✔
3490
        s.mu.Lock()
4✔
3491
        defer s.mu.Unlock()
4✔
3492

4✔
3493
        // Create a shallow copy of the current node announcement to work on.
4✔
3494
        // This ensures the original announcement remains unchanged
4✔
3495
        // until the new announcement is fully signed and valid.
4✔
3496
        newNodeAnn := *s.currentNodeAnn
4✔
3497

4✔
3498
        // First, try to update our feature manager with the updated set of
4✔
3499
        // features.
4✔
3500
        if features != nil {
8✔
3501
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
4✔
3502
                        feature.SetNodeAnn: features,
4✔
3503
                }
4✔
3504
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
4✔
3505
                if err != nil {
8✔
3506
                        return lnwire.NodeAnnouncement1{}, err
4✔
3507
                }
4✔
3508

3509
                // If we could successfully update our feature manager, add
3510
                // an update modifier to include these new features to our
3511
                // set.
3512
                modifiers = append(
4✔
3513
                        modifiers, netann.NodeAnnSetFeatures(features),
4✔
3514
                )
4✔
3515
        }
3516

3517
        // Always update the timestamp when refreshing to ensure the update
3518
        // propagates.
3519
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
4✔
3520

4✔
3521
        // Apply the requested changes to the node announcement.
4✔
3522
        for _, modifier := range modifiers {
8✔
3523
                modifier(&newNodeAnn)
4✔
3524
        }
4✔
3525

3526
        // The modifiers may have added duplicate addresses, so we need to
3527
        // de-duplicate them here.
3528
        uniqueAddrs := map[string]struct{}{}
4✔
3529
        dedupedAddrs := make([]net.Addr, 0)
4✔
3530
        for _, addr := range newNodeAnn.Addresses {
8✔
3531
                if _, ok := uniqueAddrs[addr.String()]; !ok {
8✔
3532
                        uniqueAddrs[addr.String()] = struct{}{}
4✔
3533
                        dedupedAddrs = append(dedupedAddrs, addr)
4✔
3534
                }
4✔
3535
        }
3536
        newNodeAnn.Addresses = dedupedAddrs
4✔
3537

4✔
3538
        // Sign a new update after applying all of the passed modifiers.
4✔
3539
        err := netann.SignNodeAnnouncement(
4✔
3540
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
4✔
3541
        )
4✔
3542
        if err != nil {
4✔
3543
                return lnwire.NodeAnnouncement1{}, err
×
3544
        }
×
3545

3546
        // If signing succeeds, update the current announcement.
3547
        *s.currentNodeAnn = newNodeAnn
4✔
3548

4✔
3549
        return *s.currentNodeAnn, nil
4✔
3550
}
3551

3552
// updateAndBroadcastSelfNode generates a new node announcement
3553
// applying the giving modifiers and updating the time stamp
3554
// to ensure it propagates through the network. Then it broadcasts
3555
// it to the network.
3556
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3557
        features *lnwire.RawFeatureVector,
3558
        modifiers ...netann.NodeAnnModifier) error {
4✔
3559

4✔
3560
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
4✔
3561
        if err != nil {
8✔
3562
                return fmt.Errorf("unable to generate new node "+
4✔
3563
                        "announcement: %v", err)
4✔
3564
        }
4✔
3565

3566
        // Update the on-disk version of our announcement.
3567
        // Load and modify self node istead of creating anew instance so we
3568
        // don't risk overwriting any existing values.
3569
        selfNode, err := s.v1Graph.SourceNode(ctx)
4✔
3570
        if err != nil {
4✔
3571
                return fmt.Errorf("unable to get current source node: %w", err)
×
3572
        }
×
3573

3574
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
4✔
3575
        selfNode.Addresses = newNodeAnn.Addresses
4✔
3576
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
4✔
3577
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
4✔
3578
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
4✔
3579
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
4✔
3580

4✔
3581
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
3582

4✔
3583
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
4✔
3584
                return fmt.Errorf("can't set self node: %w", err)
×
3585
        }
×
3586

3587
        // Finally, propagate it to the nodes in the network.
3588
        err = s.BroadcastMessage(nil, &newNodeAnn)
4✔
3589
        if err != nil {
4✔
3590
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3591
                        "announcement to peers: %v", err)
×
3592
                return err
×
3593
        }
×
3594

3595
        return nil
4✔
3596
}
3597

3598
type nodeAddresses struct {
3599
        pubKey    *btcec.PublicKey
3600
        addresses []net.Addr
3601
}
3602

3603
// establishPersistentConnections attempts to establish persistent connections
3604
// to all our direct channel collaborators. In order to promote liveness of our
3605
// active channels, we instruct the connection manager to attempt to establish
3606
// and maintain persistent connections to all our direct channel counterparties.
3607
func (s *server) establishPersistentConnections(ctx context.Context) error {
4✔
3608
        // nodeAddrsMap stores the combination of node public keys and addresses
4✔
3609
        // that we'll attempt to reconnect to. PubKey strings are used as keys
4✔
3610
        // since other PubKey forms can't be compared.
4✔
3611
        nodeAddrsMap := make(map[string]*nodeAddresses)
4✔
3612

4✔
3613
        // Iterate through the list of LinkNodes to find addresses we should
4✔
3614
        // attempt to connect to based on our set of previous connections. Set
4✔
3615
        // the reconnection port to the default peer port.
4✔
3616
        linkNodes, err := s.linkNodeDB.FetchAllLinkNodes()
4✔
3617
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
4✔
3618
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3619
        }
×
3620

3621
        for _, node := range linkNodes {
8✔
3622
                pubStr := string(node.IdentityPub.SerializeCompressed())
4✔
3623
                nodeAddrs := &nodeAddresses{
4✔
3624
                        pubKey:    node.IdentityPub,
4✔
3625
                        addresses: node.Addresses,
4✔
3626
                }
4✔
3627
                nodeAddrsMap[pubStr] = nodeAddrs
4✔
3628
        }
4✔
3629

3630
        // After checking our previous connections for addresses to connect to,
3631
        // iterate through the nodes in our channel graph to find addresses
3632
        // that have been added via NodeAnnouncement1 messages.
3633
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3634
        // each of the nodes.
3635
        graphAddrs := make(map[string]*nodeAddresses)
4✔
3636
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
4✔
3637
                havePolicy bool, channelPeer *models.Node) error {
8✔
3638

4✔
3639
                // If the remote party has announced the channel to us, but we
4✔
3640
                // haven't yet, then we won't have a policy. However, we don't
4✔
3641
                // need this to connect to the peer, so we'll log it and move on.
4✔
3642
                if !havePolicy {
4✔
3643
                        srvrLog.Warnf("No channel policy found for "+
×
3644
                                "ChannelPoint(%v): ", chanPoint)
×
3645
                }
×
3646

3647
                pubStr := string(channelPeer.PubKeyBytes[:])
4✔
3648

4✔
3649
                // Add all unique addresses from channel
4✔
3650
                // graph/NodeAnnouncements to the list of addresses we'll
4✔
3651
                // connect to for this peer.
4✔
3652
                addrSet := make(map[string]net.Addr)
4✔
3653
                for _, addr := range channelPeer.Addresses {
8✔
3654
                        switch addr.(type) {
4✔
3655
                        case *net.TCPAddr:
4✔
3656
                                addrSet[addr.String()] = addr
4✔
3657

3658
                        // We'll only attempt to connect to Tor addresses if Tor
3659
                        // outbound support is enabled.
3660
                        case *tor.OnionAddr:
×
3661
                                if s.cfg.Tor.Active {
×
3662
                                        addrSet[addr.String()] = addr
×
3663
                                }
×
3664
                        }
3665
                }
3666

3667
                // If this peer is also recorded as a link node, we'll add any
3668
                // additional addresses that have not already been selected.
3669
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
4✔
3670
                if ok {
8✔
3671
                        for _, lnAddress := range linkNodeAddrs.addresses {
8✔
3672
                                switch lnAddress.(type) {
4✔
3673
                                case *net.TCPAddr:
4✔
3674
                                        addrSet[lnAddress.String()] = lnAddress
4✔
3675

3676
                                // We'll only attempt to connect to Tor
3677
                                // addresses if Tor outbound support is enabled.
3678
                                case *tor.OnionAddr:
×
3679
                                        if s.cfg.Tor.Active {
×
3680
                                                //nolint:ll
×
3681
                                                addrSet[lnAddress.String()] = lnAddress
×
3682
                                        }
×
3683
                                }
3684
                        }
3685
                }
3686

3687
                // Construct a slice of the deduped addresses.
3688
                var addrs []net.Addr
4✔
3689
                for _, addr := range addrSet {
8✔
3690
                        addrs = append(addrs, addr)
4✔
3691
                }
4✔
3692

3693
                n := &nodeAddresses{
4✔
3694
                        addresses: addrs,
4✔
3695
                }
4✔
3696
                n.pubKey, err = channelPeer.PubKey()
4✔
3697
                if err != nil {
4✔
3698
                        return err
×
3699
                }
×
3700

3701
                graphAddrs[pubStr] = n
4✔
3702
                return nil
4✔
3703
        }
3704

3705
        // TODO(elle): for now, we only fetch our V1 channels. This should be
3706
        //  updated to fetch channels across all versions.
3707
        err = s.v1Graph.ForEachSourceNodeChannel(
4✔
3708
                ctx, forEachSrcNodeChan, func() {
8✔
3709
                        clear(graphAddrs)
4✔
3710
                },
4✔
3711
        )
3712
        if err != nil {
4✔
3713
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3714
                        "%v", err)
×
3715

×
3716
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3717
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3718

×
3719
                        return err
×
3720
                }
×
3721
        }
3722

3723
        // Combine the addresses from the link nodes and the channel graph.
3724
        for pubStr, nodeAddr := range graphAddrs {
8✔
3725
                nodeAddrsMap[pubStr] = nodeAddr
4✔
3726
        }
4✔
3727

3728
        srvrLog.Debugf("Establishing %v persistent connections on start",
4✔
3729
                len(nodeAddrsMap))
4✔
3730

4✔
3731
        // Acquire and hold server lock until all persistent connection requests
4✔
3732
        // have been recorded and sent to the connection manager.
4✔
3733
        s.mu.Lock()
4✔
3734
        defer s.mu.Unlock()
4✔
3735

4✔
3736
        // Iterate through the combined list of addresses from prior links and
4✔
3737
        // node announcements and attempt to reconnect to each node.
4✔
3738
        var numOutboundConns int
4✔
3739
        for pubStr, nodeAddr := range nodeAddrsMap {
8✔
3740
                // Add this peer to the set of peers we should maintain a
4✔
3741
                // persistent connection with. We set the value to false to
4✔
3742
                // indicate that we should not continue to reconnect if the
4✔
3743
                // number of channels returns to zero, since this peer has not
4✔
3744
                // been requested as perm by the user.
4✔
3745
                s.persistentPeers[pubStr] = false
4✔
3746
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
8✔
3747
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
4✔
3748
                }
4✔
3749

3750
                for _, address := range nodeAddr.addresses {
8✔
3751
                        // Create a wrapper address which couples the IP and
4✔
3752
                        // the pubkey so the brontide authenticated connection
4✔
3753
                        // can be established.
4✔
3754
                        lnAddr := &lnwire.NetAddress{
4✔
3755
                                IdentityKey: nodeAddr.pubKey,
4✔
3756
                                Address:     address,
4✔
3757
                        }
4✔
3758

4✔
3759
                        s.persistentPeerAddrs[pubStr] = append(
4✔
3760
                                s.persistentPeerAddrs[pubStr], lnAddr)
4✔
3761
                }
4✔
3762

3763
                // We'll connect to the first 10 peers immediately, then
3764
                // randomly stagger any remaining connections if the
3765
                // stagger initial reconnect flag is set. This ensures
3766
                // that mobile nodes or nodes with a small number of
3767
                // channels obtain connectivity quickly, but larger
3768
                // nodes are able to disperse the costs of connecting to
3769
                // all peers at once.
3770
                if numOutboundConns < numInstantInitReconnect ||
4✔
3771
                        !s.cfg.StaggerInitialReconnect {
8✔
3772

4✔
3773
                        go s.connectToPersistentPeer(pubStr)
4✔
3774
                } else {
4✔
3775
                        go s.delayInitialReconnect(pubStr)
×
3776
                }
×
3777

3778
                numOutboundConns++
4✔
3779
        }
3780

3781
        return nil
4✔
3782
}
3783

3784
// delayInitialReconnect will attempt a reconnection to the given peer after
3785
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3786
//
3787
// NOTE: This method MUST be run as a goroutine.
3788
func (s *server) delayInitialReconnect(pubStr string) {
×
3789
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3790
        select {
×
3791
        case <-time.After(delay):
×
3792
                s.connectToPersistentPeer(pubStr)
×
3793
        case <-s.quit:
×
3794
        }
3795
}
3796

3797
// prunePersistentPeerConnection removes all internal state related to
3798
// persistent connections to a peer within the server. This is used to avoid
3799
// persistent connection retries to peers we do not have any open channels with.
3800
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
4✔
3801
        pubKeyStr := string(compressedPubKey[:])
4✔
3802

4✔
3803
        s.mu.Lock()
4✔
3804
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
8✔
3805
                delete(s.persistentPeers, pubKeyStr)
4✔
3806
                delete(s.persistentPeersBackoff, pubKeyStr)
4✔
3807
                delete(s.persistentPeerAddrs, pubKeyStr)
4✔
3808
                s.cancelConnReqs(pubKeyStr, nil)
4✔
3809
                s.mu.Unlock()
4✔
3810

4✔
3811
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
4✔
3812
                        "peer has no open channels", compressedPubKey)
4✔
3813

4✔
3814
                return
4✔
3815
        }
4✔
3816
        s.mu.Unlock()
4✔
3817
}
3818

3819
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3820
// is instead used to remove persistent peer state for a peer that has been
3821
// disconnected for good cause by the server. Currently, a gossip ban from
3822
// sending garbage and the server running out of restricted-access
3823
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3824
// future, this function may expand when more ban criteria is added.
3825
//
3826
// NOTE: The server's write lock MUST be held when this is called.
3827
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3828
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3829
                delete(s.persistentPeers, remotePub)
×
3830
                delete(s.persistentPeersBackoff, remotePub)
×
3831
                delete(s.persistentPeerAddrs, remotePub)
×
3832
                s.cancelConnReqs(remotePub, nil)
×
3833
        }
×
3834
}
3835

3836
// BroadcastMessage sends a request to the server to broadcast a set of
3837
// messages to all peers other than the one specified by the `skips` parameter.
3838
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3839
// the target peers.
3840
//
3841
// NOTE: This function is safe for concurrent access.
3842
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3843
        msgs ...lnwire.Message) error {
4✔
3844

4✔
3845
        // Filter out peers found in the skips map. We synchronize access to
4✔
3846
        // peersByPub throughout this process to ensure we deliver messages to
4✔
3847
        // exact set of peers present at the time of invocation.
4✔
3848
        s.mu.RLock()
4✔
3849
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
3850
        for pubStr, sPeer := range s.peersByPub {
8✔
3851
                if skips != nil {
8✔
3852
                        if _, ok := skips[sPeer.PubKey()]; ok {
8✔
3853
                                srvrLog.Tracef("Skipping %x in broadcast with "+
4✔
3854
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
4✔
3855
                                continue
4✔
3856
                        }
3857
                }
3858

3859
                peers = append(peers, sPeer)
4✔
3860
        }
3861
        s.mu.RUnlock()
4✔
3862

4✔
3863
        // Iterate over all known peers, dispatching a go routine to enqueue
4✔
3864
        // all messages to each of peers.
4✔
3865
        var wg sync.WaitGroup
4✔
3866
        for _, sPeer := range peers {
8✔
3867
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
4✔
3868
                        sPeer.PubKey())
4✔
3869

4✔
3870
                // Dispatch a go routine to enqueue all messages to this peer.
4✔
3871
                wg.Add(1)
4✔
3872
                s.wg.Add(1)
4✔
3873
                go func(p lnpeer.Peer) {
8✔
3874
                        defer s.wg.Done()
4✔
3875
                        defer wg.Done()
4✔
3876

4✔
3877
                        p.SendMessageLazy(false, msgs...)
4✔
3878
                }(sPeer)
4✔
3879
        }
3880

3881
        // Wait for all messages to have been dispatched before returning to
3882
        // caller.
3883
        wg.Wait()
4✔
3884

4✔
3885
        return nil
4✔
3886
}
3887

3888
// NotifyWhenOnline can be called by other subsystems to get notified when a
3889
// particular peer comes online. The peer itself is sent across the peerChan.
3890
//
3891
// NOTE: This function is safe for concurrent access.
3892
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3893
        peerChan chan<- lnpeer.Peer) {
4✔
3894

4✔
3895
        s.mu.Lock()
4✔
3896

4✔
3897
        // Compute the target peer's identifier.
4✔
3898
        pubStr := string(peerKey[:])
4✔
3899

4✔
3900
        // Check if peer is connected.
4✔
3901
        peer, ok := s.peersByPub[pubStr]
4✔
3902
        if ok {
8✔
3903
                // Unlock here so that the mutex isn't held while we are
4✔
3904
                // waiting for the peer to become active.
4✔
3905
                s.mu.Unlock()
4✔
3906

4✔
3907
                // Wait until the peer signals that it is actually active
4✔
3908
                // rather than only in the server's maps.
4✔
3909
                select {
4✔
3910
                case <-peer.ActiveSignal():
4✔
UNCOV
3911
                case <-peer.QuitSignal():
×
UNCOV
3912
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3913
                        // and return.
×
UNCOV
3914
                        s.mu.Lock()
×
UNCOV
3915
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3916
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3917
                        )
×
UNCOV
3918
                        s.mu.Unlock()
×
UNCOV
3919
                        return
×
3920
                }
3921

3922
                // Connected, can return early.
3923
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
4✔
3924

4✔
3925
                select {
4✔
3926
                case peerChan <- peer:
4✔
3927
                case <-s.quit:
×
3928
                }
3929

3930
                return
4✔
3931
        }
3932

3933
        // Not connected, store this listener such that it can be notified when
3934
        // the peer comes online.
3935
        s.peerConnectedListeners[pubStr] = append(
4✔
3936
                s.peerConnectedListeners[pubStr], peerChan,
4✔
3937
        )
4✔
3938
        s.mu.Unlock()
4✔
3939
}
3940

3941
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3942
// the given public key has been disconnected. The notification is signaled by
3943
// closing the channel returned.
3944
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
4✔
3945
        s.mu.Lock()
4✔
3946
        defer s.mu.Unlock()
4✔
3947

4✔
3948
        c := make(chan struct{})
4✔
3949

4✔
3950
        // If the peer is already offline, we can immediately trigger the
4✔
3951
        // notification.
4✔
3952
        peerPubKeyStr := string(peerPubKey[:])
4✔
3953
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
4✔
3954
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3955
                close(c)
×
3956
                return c
×
3957
        }
×
3958

3959
        // Otherwise, the peer is online, so we'll keep track of the channel to
3960
        // trigger the notification once the server detects the peer
3961
        // disconnects.
3962
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
4✔
3963
                s.peerDisconnectedListeners[peerPubKeyStr], c,
4✔
3964
        )
4✔
3965

4✔
3966
        return c
4✔
3967
}
3968

3969
// FindPeer will return the peer that corresponds to the passed in public key.
3970
// This function is used by the funding manager, allowing it to update the
3971
// daemon's local representation of the remote peer.
3972
//
3973
// NOTE: This function is safe for concurrent access.
3974
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
4✔
3975
        s.mu.RLock()
4✔
3976
        defer s.mu.RUnlock()
4✔
3977

4✔
3978
        pubStr := string(peerKey.SerializeCompressed())
4✔
3979

4✔
3980
        return s.findPeerByPubStr(pubStr)
4✔
3981
}
4✔
3982

3983
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3984
// which should be a string representation of the peer's serialized, compressed
3985
// public key.
3986
//
3987
// NOTE: This function is safe for concurrent access.
3988
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3989
        s.mu.RLock()
4✔
3990
        defer s.mu.RUnlock()
4✔
3991

4✔
3992
        return s.findPeerByPubStr(pubStr)
4✔
3993
}
4✔
3994

3995
// findPeerByPubStr is an internal method that retrieves the specified peer from
3996
// the server's internal state using.
3997
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
4✔
3998
        peer, ok := s.peersByPub[pubStr]
4✔
3999
        if !ok {
8✔
4000
                return nil, ErrPeerNotConnected
4✔
4001
        }
4✔
4002

4003
        return peer, nil
4✔
4004
}
4005

4006
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
4007
// exponential backoff. If no previous backoff was known, the default is
4008
// returned.
4009
func (s *server) nextPeerBackoff(pubStr string,
4010
        startTime time.Time) time.Duration {
4✔
4011

4✔
4012
        // Now, determine the appropriate backoff to use for the retry.
4✔
4013
        backoff, ok := s.persistentPeersBackoff[pubStr]
4✔
4014
        if !ok {
8✔
4015
                // If an existing backoff was unknown, use the default.
4✔
4016
                return s.cfg.MinBackoff
4✔
4017
        }
4✔
4018

4019
        // If the peer failed to start properly, we'll just use the previous
4020
        // backoff to compute the subsequent randomized exponential backoff
4021
        // duration. This will roughly double on average.
4022
        if startTime.IsZero() {
4✔
4023
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4024
        }
×
4025

4026
        // The peer succeeded in starting. If the connection didn't last long
4027
        // enough to be considered stable, we'll continue to back off retries
4028
        // with this peer.
4029
        connDuration := time.Since(startTime)
4✔
4030
        if connDuration < defaultStableConnDuration {
8✔
4031
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
4✔
4032
        }
4✔
4033

4034
        // The peer succeed in starting and this was stable peer, so we'll
4035
        // reduce the timeout duration by the length of the connection after
4036
        // applying randomized exponential backoff. We'll only apply this in the
4037
        // case that:
4038
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4039
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4040
        if relaxedBackoff > s.cfg.MinBackoff {
×
4041
                return relaxedBackoff
×
4042
        }
×
4043

4044
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4045
        // the stable connection lasted much longer than our previous backoff.
4046
        // To reward such good behavior, we'll reconnect after the default
4047
        // timeout.
4048
        return s.cfg.MinBackoff
×
4049
}
4050

4051
// shouldDropLocalConnection determines if our local connection to a remote peer
4052
// should be dropped in the case of concurrent connection establishment. In
4053
// order to deterministically decide which connection should be dropped, we'll
4054
// utilize the ordering of the local and remote public key. If we didn't use
4055
// such a tie breaker, then we risk _both_ connections erroneously being
4056
// dropped.
4057
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4058
        localPubBytes := local.SerializeCompressed()
×
4059
        remotePubPbytes := remote.SerializeCompressed()
×
4060

×
4061
        // The connection that comes from the node with a "smaller" pubkey
×
4062
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4063
        // should drop our established connection.
×
4064
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4065
}
×
4066

4067
// InboundPeerConnected initializes a new peer in response to a new inbound
4068
// connection.
4069
//
4070
// NOTE: This function is safe for concurrent access.
4071
func (s *server) InboundPeerConnected(conn net.Conn) {
4✔
4072
        // Exit early if we have already been instructed to shutdown, this
4✔
4073
        // prevents any delayed callbacks from accidentally registering peers.
4✔
4074
        if s.Stopped() {
4✔
4075
                return
×
4076
        }
×
4077

4078
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
4079
        pubSer := nodePub.SerializeCompressed()
4✔
4080
        pubStr := string(pubSer)
4✔
4081

4✔
4082
        var pubBytes [33]byte
4✔
4083
        copy(pubBytes[:], pubSer)
4✔
4084

4✔
4085
        s.mu.Lock()
4✔
4086
        defer s.mu.Unlock()
4✔
4087

4✔
4088
        // If we already have an outbound connection to this peer, then ignore
4✔
4089
        // this new connection.
4✔
4090
        if p, ok := s.outboundPeers[pubStr]; ok {
8✔
4091
                srvrLog.Debugf("Already have outbound connection for %v, "+
4✔
4092
                        "ignoring inbound connection from local=%v, remote=%v",
4✔
4093
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
4094

4✔
4095
                conn.Close()
4✔
4096
                return
4✔
4097
        }
4✔
4098

4099
        // If we already have a valid connection that is scheduled to take
4100
        // precedence once the prior peer has finished disconnecting, we'll
4101
        // ignore this connection.
4102
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
4103
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4104
                        "scheduled", conn.RemoteAddr(), p)
×
4105
                conn.Close()
×
4106
                return
×
4107
        }
×
4108

4109
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
4✔
4110

4✔
4111
        // Check to see if we already have a connection with this peer. If so,
4✔
4112
        // we may need to drop our existing connection. This prevents us from
4✔
4113
        // having duplicate connections to the same peer. We forgo adding a
4✔
4114
        // default case as we expect these to be the only error values returned
4✔
4115
        // from findPeerByPubStr.
4✔
4116
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
4117
        switch err {
4✔
4118
        case ErrPeerNotConnected:
4✔
4119
                // We were unable to locate an existing connection with the
4✔
4120
                // target peer, proceed to connect.
4✔
4121
                s.cancelConnReqs(pubStr, nil)
4✔
4122
                s.peerConnected(conn, nil, true)
4✔
4123

4124
        case nil:
4✔
4125
                ctx := btclog.WithCtx(
4✔
4126
                        context.TODO(),
4✔
4127
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
4✔
4128
                )
4✔
4129

4✔
4130
                // We already have a connection with the incoming peer. If the
4✔
4131
                // connection we've already established should be kept and is
4✔
4132
                // not of the same type of the new connection (inbound), then
4✔
4133
                // we'll close out the new connection s.t there's only a single
4✔
4134
                // connection between us.
4✔
4135
                localPub := s.identityECDH.PubKey()
4✔
4136
                if !connectedPeer.Inbound() &&
4✔
4137
                        !shouldDropLocalConnection(localPub, nodePub) {
4✔
4138

×
4139
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4140
                                "peer, but already have outbound "+
×
4141
                                "connection, dropping conn",
×
4142
                                fmt.Errorf("already have outbound conn"))
×
4143
                        conn.Close()
×
4144
                        return
×
4145
                }
×
4146

4147
                // Otherwise, if we should drop the connection, then we'll
4148
                // disconnect our already connected peer.
4149
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
4✔
4150

4✔
4151
                s.cancelConnReqs(pubStr, nil)
4✔
4152

4✔
4153
                // Remove the current peer from the server's internal state and
4✔
4154
                // signal that the peer termination watcher does not need to
4✔
4155
                // execute for this peer.
4✔
4156
                s.removePeerUnsafe(ctx, connectedPeer)
4✔
4157
                s.ignorePeerTermination[connectedPeer] = struct{}{}
4✔
4158
                s.scheduledPeerConnection[pubStr] = func() {
8✔
4159
                        s.peerConnected(conn, nil, true)
4✔
4160
                }
4✔
4161
        }
4162
}
4163

4164
// OutboundPeerConnected initializes a new peer in response to a new outbound
4165
// connection.
4166
// NOTE: This function is safe for concurrent access.
4167
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
4✔
4168
        // Exit early if we have already been instructed to shutdown, this
4✔
4169
        // prevents any delayed callbacks from accidentally registering peers.
4✔
4170
        if s.Stopped() {
4✔
4171
                return
×
4172
        }
×
4173

4174
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
4175
        pubSer := nodePub.SerializeCompressed()
4✔
4176
        pubStr := string(pubSer)
4✔
4177

4✔
4178
        var pubBytes [33]byte
4✔
4179
        copy(pubBytes[:], pubSer)
4✔
4180

4✔
4181
        s.mu.Lock()
4✔
4182
        defer s.mu.Unlock()
4✔
4183

4✔
4184
        // If we already have an inbound connection to this peer, then ignore
4✔
4185
        // this new connection.
4✔
4186
        if p, ok := s.inboundPeers[pubStr]; ok {
8✔
4187
                srvrLog.Debugf("Already have inbound connection for %v, "+
4✔
4188
                        "ignoring outbound connection from local=%v, remote=%v",
4✔
4189
                        p, conn.LocalAddr(), conn.RemoteAddr())
4✔
4190

4✔
4191
                if connReq != nil {
8✔
4192
                        s.connMgr.Remove(connReq.ID())
4✔
4193
                }
4✔
4194
                conn.Close()
4✔
4195
                return
4✔
4196
        }
4197
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
4✔
4198
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4199
                s.connMgr.Remove(connReq.ID())
×
4200
                conn.Close()
×
4201
                return
×
4202
        }
×
4203

4204
        // If we already have a valid connection that is scheduled to take
4205
        // precedence once the prior peer has finished disconnecting, we'll
4206
        // ignore this connection.
4207
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
4✔
4208
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4209

×
4210
                if connReq != nil {
×
4211
                        s.connMgr.Remove(connReq.ID())
×
4212
                }
×
4213

4214
                conn.Close()
×
4215
                return
×
4216
        }
4217

4218
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
4✔
4219
                conn.RemoteAddr())
4✔
4220

4✔
4221
        if connReq != nil {
8✔
4222
                // A successful connection was returned by the connmgr.
4✔
4223
                // Immediately cancel all pending requests, excluding the
4✔
4224
                // outbound connection we just established.
4✔
4225
                ignore := connReq.ID()
4✔
4226
                s.cancelConnReqs(pubStr, &ignore)
4✔
4227
        } else {
8✔
4228
                // This was a successful connection made by some other
4✔
4229
                // subsystem. Remove all requests being managed by the connmgr.
4✔
4230
                s.cancelConnReqs(pubStr, nil)
4✔
4231
        }
4✔
4232

4233
        // If we already have a connection with this peer, decide whether or not
4234
        // we need to drop the stale connection. We forgo adding a default case
4235
        // as we expect these to be the only error values returned from
4236
        // findPeerByPubStr.
4237
        connectedPeer, err := s.findPeerByPubStr(pubStr)
4✔
4238
        switch err {
4✔
4239
        case ErrPeerNotConnected:
4✔
4240
                // We were unable to locate an existing connection with the
4✔
4241
                // target peer, proceed to connect.
4✔
4242
                s.peerConnected(conn, connReq, false)
4✔
4243

4244
        case nil:
4✔
4245
                ctx := btclog.WithCtx(
4✔
4246
                        context.TODO(),
4✔
4247
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
4✔
4248
                )
4✔
4249

4✔
4250
                // We already have a connection with the incoming peer. If the
4✔
4251
                // connection we've already established should be kept and is
4✔
4252
                // not of the same type of the new connection (outbound), then
4✔
4253
                // we'll close out the new connection s.t there's only a single
4✔
4254
                // connection between us.
4✔
4255
                localPub := s.identityECDH.PubKey()
4✔
4256
                if connectedPeer.Inbound() &&
4✔
4257
                        shouldDropLocalConnection(localPub, nodePub) {
4✔
4258

×
4259
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4260
                                "to peer, but already have inbound "+
×
4261
                                "connection, dropping conn",
×
4262
                                fmt.Errorf("already have inbound conn"))
×
4263
                        if connReq != nil {
×
4264
                                s.connMgr.Remove(connReq.ID())
×
4265
                        }
×
4266
                        conn.Close()
×
4267
                        return
×
4268
                }
4269

4270
                // Otherwise, _their_ connection should be dropped. So we'll
4271
                // disconnect the peer and send the now obsolete peer to the
4272
                // server for garbage collection.
4273
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
4✔
4274

4✔
4275
                // Remove the current peer from the server's internal state and
4✔
4276
                // signal that the peer termination watcher does not need to
4✔
4277
                // execute for this peer.
4✔
4278
                s.removePeerUnsafe(ctx, connectedPeer)
4✔
4279
                s.ignorePeerTermination[connectedPeer] = struct{}{}
4✔
4280
                s.scheduledPeerConnection[pubStr] = func() {
8✔
4281
                        s.peerConnected(conn, connReq, false)
4✔
4282
                }
4✔
4283
        }
4284
}
4285

4286
// UnassignedConnID is the default connection ID that a request can have before
4287
// it actually is submitted to the connmgr.
4288
// TODO(conner): move into connmgr package, or better, add connmgr method for
4289
// generating atomic IDs
4290
const UnassignedConnID uint64 = 0
4291

4292
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4293
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4294
// Afterwards, each connection request removed from the connmgr. The caller can
4295
// optionally specify a connection ID to ignore, which prevents us from
4296
// canceling a successful request. All persistent connreqs for the provided
4297
// pubkey are discarded after the operationjw.
4298
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
4✔
4299
        // First, cancel any lingering persistent retry attempts, which will
4✔
4300
        // prevent retries for any with backoffs that are still maturing.
4✔
4301
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
8✔
4302
                close(cancelChan)
4✔
4303
                delete(s.persistentRetryCancels, pubStr)
4✔
4304
        }
4✔
4305

4306
        // Next, check to see if we have any outstanding persistent connection
4307
        // requests to this peer. If so, then we'll remove all of these
4308
        // connection requests, and also delete the entry from the map.
4309
        connReqs, ok := s.persistentConnReqs[pubStr]
4✔
4310
        if !ok {
8✔
4311
                return
4✔
4312
        }
4✔
4313

4314
        for _, connReq := range connReqs {
8✔
4315
                srvrLog.Tracef("Canceling %s:", connReqs)
4✔
4316

4✔
4317
                // Atomically capture the current request identifier.
4✔
4318
                connID := connReq.ID()
4✔
4319

4✔
4320
                // Skip any zero IDs, this indicates the request has not
4✔
4321
                // yet been schedule.
4✔
4322
                if connID == UnassignedConnID {
4✔
4323
                        continue
×
4324
                }
4325

4326
                // Skip a particular connection ID if instructed.
4327
                if skip != nil && connID == *skip {
8✔
4328
                        continue
4✔
4329
                }
4330

4331
                s.connMgr.Remove(connID)
4✔
4332
        }
4333

4334
        delete(s.persistentConnReqs, pubStr)
4✔
4335
}
4336

4337
// handleCustomMessage dispatches an incoming custom peers message to
4338
// subscribers.
4339
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
4✔
4340
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
4✔
4341
                peer, msg.Type)
4✔
4342

4✔
4343
        return s.customMessageServer.SendUpdate(&CustomMessage{
4✔
4344
                Peer: peer,
4✔
4345
                Msg:  msg,
4✔
4346
        })
4✔
4347
}
4✔
4348

4349
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4350
// messages.
4351
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
4✔
4352
        return s.customMessageServer.Subscribe()
4✔
4353
}
4✔
4354

4355
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4356
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
4✔
4357
        return s.onionMessageServer.Subscribe()
4✔
4358
}
4✔
4359

4360
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4361
// the channelNotifier's NotifyOpenChannelEvent.
4362
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4363
        remotePub *btcec.PublicKey) {
4✔
4364

4✔
4365
        // Call newOpenChan to update the access manager's maps for this peer.
4✔
4366
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
8✔
4367
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
4✔
4368
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
4✔
4369
        }
4✔
4370

4371
        // Notify subscribers about this open channel event.
4372
        s.channelNotifier.NotifyOpenChannelEvent(op)
4✔
4373
}
4374

4375
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4376
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4377
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4378
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
4✔
4379

4✔
4380
        // Call newPendingOpenChan to update the access manager's maps for this
4✔
4381
        // peer.
4✔
4382
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
4✔
4383
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4384
                        "channel[%v] pending open",
×
4385
                        remotePub.SerializeCompressed(), op)
×
4386
        }
×
4387

4388
        // Notify subscribers about this event.
4389
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
4✔
4390
}
4391

4392
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4393
// calls the channelNotifier's NotifyFundingTimeout.
4394
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4395
        remotePub *btcec.PublicKey) {
4✔
4396

4✔
4397
        // Call newPendingCloseChan to potentially demote the peer.
4✔
4398
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
4✔
4399
        if err != nil {
4✔
4400
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4401
                        "channel[%v] pending close",
×
4402
                        remotePub.SerializeCompressed(), op)
×
4403
        }
×
4404

4405
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
4✔
4406
                // If we encounter an error while attempting to disconnect the
×
4407
                // peer, log the error.
×
4408
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4409
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4410
                }
×
4411
        }
4412

4413
        // Notify subscribers about this event.
4414
        s.channelNotifier.NotifyFundingTimeout(op)
4✔
4415
}
4416

4417
// peerConnected is a function that handles initialization a newly connected
4418
// peer by adding it to the server's global list of all active peers, and
4419
// starting all the goroutines the peer needs to function properly. The inbound
4420
// boolean should be true if the peer initiated the connection to us.
4421
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4422
        inbound bool) {
4✔
4423

4✔
4424
        brontideConn := conn.(*brontide.Conn)
4✔
4425
        addr := conn.RemoteAddr()
4✔
4426
        pubKey := brontideConn.RemotePub()
4✔
4427

4✔
4428
        // Only restrict access for inbound connections, which means if the
4✔
4429
        // remote node's public key is banned or the restricted slots are used
4✔
4430
        // up, we will drop the connection.
4✔
4431
        //
4✔
4432
        // TODO(yy): Consider perform this check in
4✔
4433
        // `peerAccessMan.addPeerAccess`.
4✔
4434
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
4✔
4435
        if inbound && err != nil {
4✔
4436
                pubSer := pubKey.SerializeCompressed()
×
4437

×
4438
                // Clean up the persistent peer maps if we're dropping this
×
4439
                // connection.
×
4440
                s.bannedPersistentPeerConnection(string(pubSer))
×
4441

×
4442
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4443
                        "of restricted-access connection slots: %v.", pubSer,
×
4444
                        err)
×
4445

×
4446
                conn.Close()
×
4447

×
4448
                return
×
4449
        }
×
4450

4451
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4✔
4452
                pubKey.SerializeCompressed(), addr, inbound)
4✔
4453

4✔
4454
        peerAddr := &lnwire.NetAddress{
4✔
4455
                IdentityKey: pubKey,
4✔
4456
                Address:     addr,
4✔
4457
                ChainNet:    s.cfg.ActiveNetParams.Net,
4✔
4458
        }
4✔
4459

4✔
4460
        // With the brontide connection established, we'll now craft the feature
4✔
4461
        // vectors to advertise to the remote node.
4✔
4462
        initFeatures := s.featureMgr.Get(feature.SetInit)
4✔
4463
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4✔
4464

4✔
4465
        // Lookup past error caches for the peer in the server. If no buffer is
4✔
4466
        // found, create a fresh buffer.
4✔
4467
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
4✔
4468
        errBuffer, ok := s.peerErrors[pkStr]
4✔
4469
        if !ok {
8✔
4470
                var err error
4✔
4471
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
4✔
4472
                if err != nil {
4✔
4473
                        srvrLog.Errorf("unable to create peer %v", err)
×
4474
                        return
×
4475
                }
×
4476
        }
4477

4478
        // If we directly set the peer.Config TowerClient member to the
4479
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4480
        // the peer.Config's TowerClient member will not evaluate to nil even
4481
        // though the underlying value is nil. To avoid this gotcha which can
4482
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4483
        // TowerClient if needed.
4484
        var towerClient wtclient.ClientManager
4✔
4485
        if s.towerClientMgr != nil {
8✔
4486
                towerClient = s.towerClientMgr
4✔
4487
        }
4✔
4488

4489
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4✔
4490
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
4✔
4491

4✔
4492
        // Now that we've established a connection, create a peer, and it to the
4✔
4493
        // set of currently active peers. Configure the peer with the incoming
4✔
4494
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
4✔
4495
        // offered that would trigger channel closure. In case of outgoing
4✔
4496
        // htlcs, an extra block is added to prevent the channel from being
4✔
4497
        // closed when the htlc is outstanding and a new block comes in.
4✔
4498
        pCfg := peer.Config{
4✔
4499
                Conn:                    brontideConn,
4✔
4500
                ConnReq:                 connReq,
4✔
4501
                Addr:                    peerAddr,
4✔
4502
                Inbound:                 inbound,
4✔
4503
                Features:                initFeatures,
4✔
4504
                LegacyFeatures:          legacyFeatures,
4✔
4505
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
4✔
4506
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
4✔
4507
                ErrorBuffer:             errBuffer,
4✔
4508
                WritePool:               s.writePool,
4✔
4509
                ReadPool:                s.readPool,
4✔
4510
                Switch:                  s.htlcSwitch,
4✔
4511
                InterceptSwitch:         s.interceptableSwitch,
4✔
4512
                ChannelDB:               s.chanStateDB,
4✔
4513
                ChannelGraph:            s.graphDB,
4✔
4514
                ChainArb:                s.chainArb,
4✔
4515
                AuthGossiper:            s.authGossiper,
4✔
4516
                ChanStatusMgr:           s.chanStatusMgr,
4✔
4517
                ChainIO:                 s.cc.ChainIO,
4✔
4518
                FeeEstimator:            s.cc.FeeEstimator,
4✔
4519
                Signer:                  s.cc.Wallet.Cfg.Signer,
4✔
4520
                SigPool:                 s.sigPool,
4✔
4521
                Wallet:                  s.cc.Wallet,
4✔
4522
                ChainNotifier:           s.cc.ChainNotifier,
4✔
4523
                BestBlockView:           s.cc.BestBlockTracker,
4✔
4524
                RoutingPolicy:           s.cc.RoutingPolicy,
4✔
4525
                SphinxPayment:           s.sphinxPayment,
4✔
4526
                SpawnOnionActor:         s.onionActorFactory,
4✔
4527
                OnionLimiter:            s.onionLimiter,
4✔
4528
                OnionRelayAll:           s.cfg.ProtocolOptions.OnionMsgRelayAll,
4✔
4529
                OnionActorOpts: func(_ [33]byte) []actor.ActorOption[
4✔
4530
                        *onionmessage.Request, *onionmessage.Response,
4✔
4531
                ] {
8✔
4532

4✔
4533
                        return s.defaultOnionActorOpts
4✔
4534
                },
4✔
4535
                ActorSystem:     s.actorSystem,
4536
                WitnessBeacon:   s.witnessBeacon,
4537
                Invoices:        s.invoices,
4538
                ChannelNotifier: s.channelNotifier,
4539
                HtlcNotifier:    s.htlcNotifier,
4540
                TowerClient:     towerClient,
4541
                DisconnectPeer:  s.DisconnectPeer,
4542
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
4543
                        lnwire.NodeAnnouncement1, error) {
4✔
4544

4✔
4545
                        return s.genNodeAnnouncement(nil)
4✔
4546
                },
4✔
4547

4548
                PongBuf: s.pongBuf,
4549

4550
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4551

4552
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4553

4554
                FundingManager: s.fundingMgr,
4555

4556
                Hodl:                    s.cfg.Hodl,
4557
                UnsafeReplay:            s.cfg.UnsafeReplay,
4558
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4559
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4560
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4561
                ChannelCloseConfs:       s.cfg.Dev.ChannelCloseConfs(),
4562
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4563
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4564
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4565
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4566
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4567
                HandleCustomMessage:    s.handleCustomMessage,
4568
                GetAliases:             s.aliasMgr.GetAliases,
4569
                RequestAlias:           s.aliasMgr.RequestAlias,
4570
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4571
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4572
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4573
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4574
                MaxFeeExposure:         thresholdMSats,
4575
                Quit:                   s.quit,
4576
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4577
                AuxSigner:              s.implCfg.AuxSigner,
4578
                MsgRouter:              s.implCfg.MsgRouter,
4579
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4580
                AuxResolver:            s.implCfg.AuxContractResolver,
4581
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4582
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4583
                ShouldFwdExpAccountability: func() bool {
4✔
4584
                        return !s.cfg.ProtocolOptions.NoExpAccountability()
4✔
4585
                },
4✔
4586
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4587
        }
4588

4589
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
4✔
4590
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
4✔
4591

4✔
4592
        p := peer.NewBrontide(pCfg)
4✔
4593

4✔
4594
        // Update the access manager with the access permission for this peer.
4✔
4595
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
4✔
4596

4✔
4597
        // TODO(roasbeef): update IP address for link-node
4✔
4598
        //  * also mark last-seen, do it one single transaction?
4✔
4599

4✔
4600
        s.addPeer(p)
4✔
4601

4✔
4602
        // Once we have successfully added the peer to the server, we can
4✔
4603
        // delete the previous error buffer from the server's map of error
4✔
4604
        // buffers.
4✔
4605
        delete(s.peerErrors, pkStr)
4✔
4606

4✔
4607
        // Dispatch a goroutine to asynchronously start the peer. This process
4✔
4608
        // includes sending and receiving Init messages, which would be a DOS
4✔
4609
        // vector if we held the server's mutex throughout the procedure.
4✔
4610
        s.wg.Add(1)
4✔
4611
        go s.peerInitializer(p)
4✔
4612
}
4613

4614
// addPeer adds the passed peer to the server's global state of all active
4615
// peers.
4616
func (s *server) addPeer(p *peer.Brontide) {
4✔
4617
        if p == nil {
4✔
4618
                return
×
4619
        }
×
4620

4621
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4622

4✔
4623
        // Ignore new peers if we're shutting down.
4✔
4624
        if s.Stopped() {
4✔
4625
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4626
                        pubBytes)
×
4627
                p.Disconnect(ErrServerShuttingDown)
×
4628

×
4629
                return
×
4630
        }
×
4631

4632
        // Track the new peer in our indexes so we can quickly look it up either
4633
        // according to its public key, or its peer ID.
4634
        // TODO(roasbeef): pipe all requests through to the
4635
        // queryHandler/peerManager
4636

4637
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4638
        // be human-readable.
4639
        pubStr := string(pubBytes)
4✔
4640

4✔
4641
        s.peersByPub[pubStr] = p
4✔
4642

4✔
4643
        if p.Inbound() {
8✔
4644
                s.inboundPeers[pubStr] = p
4✔
4645
        } else {
8✔
4646
                s.outboundPeers[pubStr] = p
4✔
4647
        }
4✔
4648

4649
        // Inform the peer notifier of a peer online event so that it can be reported
4650
        // to clients listening for peer events.
4651
        var pubKey [33]byte
4✔
4652
        copy(pubKey[:], pubBytes)
4✔
4653
}
4654

4655
// peerInitializer asynchronously starts a newly connected peer after it has
4656
// been added to the server's peer map. This method sets up a
4657
// peerTerminationWatcher for the given peer, and ensures that it executes even
4658
// if the peer failed to start. In the event of a successful connection, this
4659
// method reads the negotiated, local feature-bits and spawns the appropriate
4660
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4661
// be signaled of the new peer once the method returns.
4662
//
4663
// NOTE: This MUST be launched as a goroutine.
4664
func (s *server) peerInitializer(p *peer.Brontide) {
4✔
4665
        defer s.wg.Done()
4✔
4666

4✔
4667
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4668

4✔
4669
        // Avoid initializing peers while the server is exiting.
4✔
4670
        if s.Stopped() {
4✔
4671
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4672
                        pubBytes)
×
4673
                return
×
4674
        }
×
4675

4676
        // Create a channel that will be used to signal a successful start of
4677
        // the link. This prevents the peer termination watcher from beginning
4678
        // its duty too early.
4679
        ready := make(chan struct{})
4✔
4680

4✔
4681
        // Before starting the peer, launch a goroutine to watch for the
4✔
4682
        // unexpected termination of this peer, which will ensure all resources
4✔
4683
        // are properly cleaned up, and re-establish persistent connections when
4✔
4684
        // necessary. The peer termination watcher will be short circuited if
4✔
4685
        // the peer is ever added to the ignorePeerTermination map, indicating
4✔
4686
        // that the server has already handled the removal of this peer.
4✔
4687
        s.wg.Add(1)
4✔
4688
        go s.peerTerminationWatcher(p, ready)
4✔
4689

4✔
4690
        // Start the peer! If an error occurs, we Disconnect the peer, which
4✔
4691
        // will unblock the peerTerminationWatcher.
4✔
4692
        if err := p.Start(); err != nil {
8✔
4693
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
4✔
4694

4✔
4695
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
4✔
4696
                return
4✔
4697
        }
4✔
4698

4699
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4700
        // was successful, and to begin watching the peer's wait group.
4701
        close(ready)
4✔
4702

4✔
4703
        s.mu.Lock()
4✔
4704
        defer s.mu.Unlock()
4✔
4705

4✔
4706
        // Check if there are listeners waiting for this peer to come online.
4✔
4707
        srvrLog.Debugf("Notifying that peer %v is online", p)
4✔
4708

4✔
4709
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4✔
4710
        // route.Vertex as the key type of peerConnectedListeners.
4✔
4711
        pubStr := string(pubBytes)
4✔
4712
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
8✔
4713
                select {
4✔
4714
                case peerChan <- p:
4✔
4715
                case <-s.quit:
×
4716
                        return
×
4717
                }
4718
        }
4719
        delete(s.peerConnectedListeners, pubStr)
4✔
4720

4✔
4721
        // Since the peer has been fully initialized, now it's time to notify
4✔
4722
        // the RPC about the peer online event.
4✔
4723
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
4✔
4724
}
4725

4726
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4727
// and then cleans up all resources allocated to the peer, notifies relevant
4728
// sub-systems of its demise, and finally handles re-connecting to the peer if
4729
// it's persistent. If the server intentionally disconnects a peer, it should
4730
// have a corresponding entry in the ignorePeerTermination map which will cause
4731
// the cleanup routine to exit early. The passed `ready` chan is used to
4732
// synchronize when WaitForDisconnect should begin watching on the peer's
4733
// waitgroup. The ready chan should only be signaled if the peer starts
4734
// successfully, otherwise the peer should be disconnected instead.
4735
//
4736
// NOTE: This MUST be launched as a goroutine.
4737
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
4✔
4738
        defer s.wg.Done()
4✔
4739

4✔
4740
        ctx := btclog.WithCtx(
4✔
4741
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
4✔
4742
        )
4✔
4743

4✔
4744
        p.WaitForDisconnect(ready)
4✔
4745

4✔
4746
        srvrLog.DebugS(ctx, "Peer has been disconnected")
4✔
4747

4✔
4748
        // If the server is exiting then we can bail out early ourselves as all
4✔
4749
        // the other sub-systems will already be shutting down.
4✔
4750
        if s.Stopped() {
8✔
4751
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
4✔
4752
                return
4✔
4753
        }
4✔
4754

4755
        // Next, we'll cancel all pending funding reservations with this node.
4756
        // If we tried to initiate any funding flows that haven't yet finished,
4757
        // then we need to unlock those committed outputs so they're still
4758
        // available for use.
4759
        s.fundingMgr.CancelPeerReservations(p.PubKey())
4✔
4760

4✔
4761
        pubKey := p.IdentityKey()
4✔
4762

4✔
4763
        // We'll also inform the gossiper that this peer is no longer active,
4✔
4764
        // so we don't need to maintain sync state for it any longer.
4✔
4765
        s.authGossiper.PruneSyncState(p.PubKey())
4✔
4766

4✔
4767
        // Tell the switch to remove all links associated with this peer.
4✔
4768
        // Passing nil as the target link indicates that all links associated
4✔
4769
        // with this interface should be closed.
4✔
4770
        //
4✔
4771
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4✔
4772
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4✔
4773
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4✔
4774
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4775
        }
×
4776

4777
        for _, link := range links {
8✔
4778
                s.htlcSwitch.RemoveLink(link.ChanID())
4✔
4779
        }
4✔
4780

4781
        s.mu.Lock()
4✔
4782
        defer s.mu.Unlock()
4✔
4783

4✔
4784
        // If there were any notification requests for when this peer
4✔
4785
        // disconnected, we can trigger them now.
4✔
4786
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
4✔
4787
        pubStr := string(pubKey.SerializeCompressed())
4✔
4788
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
8✔
4789
                close(offlineChan)
4✔
4790
        }
4✔
4791
        delete(s.peerDisconnectedListeners, pubStr)
4✔
4792

4✔
4793
        // If the server has already removed this peer, we can short circuit the
4✔
4794
        // peer termination watcher and skip cleanup.
4✔
4795
        if _, ok := s.ignorePeerTermination[p]; ok {
8✔
4796
                delete(s.ignorePeerTermination, p)
4✔
4797

4✔
4798
                // Ensure the onion peer actor is stopped even if Disconnect
4✔
4799
                // hasn't been called yet due to async execution.
4✔
4800
                p.StopOnionActorIfExists()
4✔
4801

4✔
4802
                pubKey := p.PubKey()
4✔
4803
                pubStr := string(pubKey[:])
4✔
4804

4✔
4805
                // If a connection callback is present, we'll go ahead and
4✔
4806
                // execute it now that previous peer has fully disconnected. If
4✔
4807
                // the callback is not present, this likely implies the peer was
4✔
4808
                // purposefully disconnected via RPC, and that no reconnect
4✔
4809
                // should be attempted.
4✔
4810
                connCallback, ok := s.scheduledPeerConnection[pubStr]
4✔
4811
                if ok {
8✔
4812
                        delete(s.scheduledPeerConnection, pubStr)
4✔
4813
                        connCallback()
4✔
4814
                }
4✔
4815
                return
4✔
4816
        }
4817

4818
        // First, cleanup any remaining state the server has regarding the peer
4819
        // in question.
4820
        s.removePeerUnsafe(ctx, p)
4✔
4821

4✔
4822
        // Next, check to see if this is a persistent peer or not.
4✔
4823
        if _, ok := s.persistentPeers[pubStr]; !ok {
8✔
4824
                return
4✔
4825
        }
4✔
4826

4827
        // Get the last address that we used to connect to the peer.
4828
        addrs := []net.Addr{
4✔
4829
                p.NetAddress().Address,
4✔
4830
        }
4✔
4831

4✔
4832
        // We'll ensure that we locate all the peers advertised addresses for
4✔
4833
        // reconnection purposes.
4✔
4834
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
4✔
4835
        switch {
4✔
4836
        // We found advertised addresses, so use them.
4837
        case err == nil:
4✔
4838
                addrs = advertisedAddrs
4✔
4839

4840
        // The peer doesn't have an advertised address.
4841
        case err == errNoAdvertisedAddr:
4✔
4842
                // If it is an outbound peer then we fall back to the existing
4✔
4843
                // peer address.
4✔
4844
                if !p.Inbound() {
8✔
4845
                        break
4✔
4846
                }
4847

4848
                // Fall back to the existing peer address if
4849
                // we're not accepting connections over Tor.
4850
                if s.torController == nil {
8✔
4851
                        break
4✔
4852
                }
4853

4854
                // If we are, the peer's address won't be known
4855
                // to us (we'll see a private address, which is
4856
                // the address used by our onion service to dial
4857
                // to lnd), so we don't have enough information
4858
                // to attempt a reconnect.
4859
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4860
                        "to inbound peer without advertised address")
×
4861
                return
×
4862

4863
        // We came across an error retrieving an advertised
4864
        // address, log it, and fall back to the existing peer
4865
        // address.
4866
        default:
4✔
4867
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
4✔
4868
                        "address for peer", err)
4✔
4869
        }
4870

4871
        // Make an easy lookup map so that we can check if an address
4872
        // is already in the address list that we have stored for this peer.
4873
        existingAddrs := make(map[string]bool)
4✔
4874
        for _, addr := range s.persistentPeerAddrs[pubStr] {
8✔
4875
                existingAddrs[addr.String()] = true
4✔
4876
        }
4✔
4877

4878
        // Add any missing addresses for this peer to persistentPeerAddr.
4879
        for _, addr := range addrs {
8✔
4880
                if existingAddrs[addr.String()] {
4✔
4881
                        continue
×
4882
                }
4883

4884
                s.persistentPeerAddrs[pubStr] = append(
4✔
4885
                        s.persistentPeerAddrs[pubStr],
4✔
4886
                        &lnwire.NetAddress{
4✔
4887
                                IdentityKey: p.IdentityKey(),
4✔
4888
                                Address:     addr,
4✔
4889
                                ChainNet:    p.NetAddress().ChainNet,
4✔
4890
                        },
4✔
4891
                )
4✔
4892
        }
4893

4894
        // Record the computed backoff in the backoff map.
4895
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4✔
4896
        s.persistentPeersBackoff[pubStr] = backoff
4✔
4897

4✔
4898
        // Initialize a retry canceller for this peer if one does not
4✔
4899
        // exist.
4✔
4900
        cancelChan, ok := s.persistentRetryCancels[pubStr]
4✔
4901
        if !ok {
8✔
4902
                cancelChan = make(chan struct{})
4✔
4903
                s.persistentRetryCancels[pubStr] = cancelChan
4✔
4904
        }
4✔
4905

4906
        // We choose not to wait group this go routine since the Connect
4907
        // call can stall for arbitrarily long if we shutdown while an
4908
        // outbound connection attempt is being made.
4909
        go func() {
8✔
4910
                srvrLog.DebugS(ctx, "Scheduling connection "+
4✔
4911
                        "re-establishment to persistent peer",
4✔
4912
                        "reconnecting_in", backoff)
4✔
4913

4✔
4914
                select {
4✔
4915
                case <-time.After(backoff):
4✔
4916
                case <-cancelChan:
4✔
4917
                        return
4✔
4918
                case <-s.quit:
4✔
4919
                        return
4✔
4920
                }
4921

4922
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
4✔
4923
                        "connection")
4✔
4924

4✔
4925
                s.connectToPersistentPeer(pubStr)
4✔
4926
        }()
4927
}
4928

4929
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4930
// to connect to the peer. It creates connection requests if there are
4931
// currently none for a given address and it removes old connection requests
4932
// if the associated address is no longer in the latest address list for the
4933
// peer.
4934
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4✔
4935
        s.mu.Lock()
4✔
4936
        defer s.mu.Unlock()
4✔
4937

4✔
4938
        // Create an easy lookup map of the addresses we have stored for the
4✔
4939
        // peer. We will remove entries from this map if we have existing
4✔
4940
        // connection requests for the associated address and then any leftover
4✔
4941
        // entries will indicate which addresses we should create new
4✔
4942
        // connection requests for.
4✔
4943
        addrMap := make(map[string]*lnwire.NetAddress)
4✔
4944
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
8✔
4945
                addrMap[addr.String()] = addr
4✔
4946
        }
4✔
4947

4948
        // Go through each of the existing connection requests and
4949
        // check if they correspond to the latest set of addresses. If
4950
        // there is a connection requests that does not use one of the latest
4951
        // advertised addresses then remove that connection request.
4952
        var updatedConnReqs []*connmgr.ConnReq
4✔
4953
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
8✔
4954
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
4✔
4955

4✔
4956
                switch _, ok := addrMap[lnAddr]; ok {
4✔
4957
                // If the existing connection request is using one of the
4958
                // latest advertised addresses for the peer then we add it to
4959
                // updatedConnReqs and remove the associated address from
4960
                // addrMap so that we don't recreate this connReq later on.
4961
                case true:
×
4962
                        updatedConnReqs = append(
×
4963
                                updatedConnReqs, connReq,
×
4964
                        )
×
4965
                        delete(addrMap, lnAddr)
×
4966

4967
                // If the existing connection request is using an address that
4968
                // is not one of the latest advertised addresses for the peer
4969
                // then we remove the connecting request from the connection
4970
                // manager.
4971
                case false:
4✔
4972
                        srvrLog.Info(
4✔
4973
                                "Removing conn req:", connReq.Addr.String(),
4✔
4974
                        )
4✔
4975
                        s.connMgr.Remove(connReq.ID())
4✔
4976
                }
4977
        }
4978

4979
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4980

4✔
4981
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
4✔
4982
        if !ok {
8✔
4983
                cancelChan = make(chan struct{})
4✔
4984
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4✔
4985
        }
4✔
4986

4987
        // Any addresses left in addrMap are new ones that we have not made
4988
        // connection requests for. So create new connection requests for those.
4989
        // If there is more than one address in the address map, stagger the
4990
        // creation of the connection requests for those.
4991
        go func() {
8✔
4992
                ticker := time.NewTicker(multiAddrConnectionStagger)
4✔
4993
                defer ticker.Stop()
4✔
4994

4✔
4995
                for _, addr := range addrMap {
8✔
4996
                        // Send the persistent connection request to the
4✔
4997
                        // connection manager, saving the request itself so we
4✔
4998
                        // can cancel/restart the process as needed.
4✔
4999
                        connReq := &connmgr.ConnReq{
4✔
5000
                                Addr:      addr,
4✔
5001
                                Permanent: true,
4✔
5002
                        }
4✔
5003

4✔
5004
                        s.mu.Lock()
4✔
5005
                        s.persistentConnReqs[pubKeyStr] = append(
4✔
5006
                                s.persistentConnReqs[pubKeyStr], connReq,
4✔
5007
                        )
4✔
5008
                        s.mu.Unlock()
4✔
5009

4✔
5010
                        srvrLog.Debugf("Attempting persistent connection to "+
4✔
5011
                                "channel peer %v", addr)
4✔
5012

4✔
5013
                        go s.connMgr.Connect(connReq)
4✔
5014

4✔
5015
                        select {
4✔
5016
                        case <-s.quit:
4✔
5017
                                return
4✔
5018
                        case <-cancelChan:
4✔
5019
                                return
4✔
5020
                        case <-ticker.C:
4✔
5021
                        }
5022
                }
5023
        }()
5024
}
5025

5026
// removePeerUnsafe removes the passed peer from the server's state of all
5027
// active peers.
5028
//
5029
// NOTE: Server mutex must be held when calling this function.
5030
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
4✔
5031
        if p == nil {
4✔
5032
                return
×
5033
        }
×
5034

5035
        srvrLog.DebugS(ctx, "Removing peer")
4✔
5036

4✔
5037
        // Exit early if we have already been instructed to shutdown, the peers
4✔
5038
        // will be disconnected in the server shutdown process.
4✔
5039
        if s.Stopped() {
4✔
5040
                return
×
5041
        }
×
5042

5043
        // Capture the peer's public key and string representation.
5044
        pKey := p.PubKey()
4✔
5045
        pubSer := pKey[:]
4✔
5046
        pubStr := string(pubSer)
4✔
5047

4✔
5048
        delete(s.peersByPub, pubStr)
4✔
5049

4✔
5050
        if p.Inbound() {
8✔
5051
                delete(s.inboundPeers, pubStr)
4✔
5052
        } else {
8✔
5053
                delete(s.outboundPeers, pubStr)
4✔
5054
        }
4✔
5055

5056
        // When removing the peer we make sure to disconnect it asynchronously
5057
        // to avoid blocking the main server goroutine because it is holding the
5058
        // server's mutex. Disconnecting the peer might block and wait until the
5059
        // peer has fully started up. This can happen if an inbound and outbound
5060
        // race condition occurs.
5061
        s.wg.Add(1)
4✔
5062
        go func() {
8✔
5063
                defer s.wg.Done()
4✔
5064

4✔
5065
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
4✔
5066

4✔
5067
                // If this peer had an active persistent connection request,
4✔
5068
                // remove it.
4✔
5069
                if p.ConnReq() != nil {
8✔
5070
                        s.connMgr.Remove(p.ConnReq().ID())
4✔
5071
                }
4✔
5072

5073
                // Remove the peer's access permission from the access manager.
5074
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
4✔
5075
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
4✔
5076

4✔
5077
                // Copy the peer's error buffer across to the server if it has
4✔
5078
                // any items in it so that we can restore peer errors across
4✔
5079
                // connections. We need to look up the error after the peer has
4✔
5080
                // been disconnected because we write the error in the
4✔
5081
                // `Disconnect` method.
4✔
5082
                s.mu.Lock()
4✔
5083
                if p.ErrorBuffer().Total() > 0 {
8✔
5084
                        s.peerErrors[pubStr] = p.ErrorBuffer()
4✔
5085
                }
4✔
5086
                s.mu.Unlock()
4✔
5087

4✔
5088
                // Inform the peer notifier of a peer offline event so that it
4✔
5089
                // can be reported to clients listening for peer events.
4✔
5090
                var pubKey [33]byte
4✔
5091
                copy(pubKey[:], pubSer)
4✔
5092

4✔
5093
                s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
5094
        }()
5095
}
5096

5097
// ConnectToPeer requests that the server connect to a Lightning Network peer
5098
// at the specified address. This function will *block* until either a
5099
// connection is established, or the initial handshake process fails.
5100
//
5101
// NOTE: This function is safe for concurrent access.
5102
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5103
        perm bool, timeout time.Duration) error {
4✔
5104

4✔
5105
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
5106

4✔
5107
        // Acquire mutex, but use explicit unlocking instead of defer for
4✔
5108
        // better granularity.  In certain conditions, this method requires
4✔
5109
        // making an outbound connection to a remote peer, which requires the
4✔
5110
        // lock to be released, and subsequently reacquired.
4✔
5111
        s.mu.Lock()
4✔
5112

4✔
5113
        // Ensure we're not already connected to this peer.
4✔
5114
        peer, err := s.findPeerByPubStr(targetPub)
4✔
5115

4✔
5116
        // When there's no error it means we already have a connection with this
4✔
5117
        // peer. If this is a dev environment with the `--unsafeconnect` flag
4✔
5118
        // set, we will ignore the existing connection and continue.
4✔
5119
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
8✔
5120
                s.mu.Unlock()
4✔
5121
                return &errPeerAlreadyConnected{peer: peer}
4✔
5122
        }
4✔
5123

5124
        // Peer was not found, continue to pursue connection with peer.
5125

5126
        // If there's already a pending connection request for this pubkey,
5127
        // then we ignore this request to ensure we don't create a redundant
5128
        // connection.
5129
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
8✔
5130
                srvrLog.Warnf("Already have %d persistent connection "+
4✔
5131
                        "requests for %v, connecting anyway.", len(reqs), addr)
4✔
5132
        }
4✔
5133

5134
        // If there's not already a pending or active connection to this node,
5135
        // then instruct the connection manager to attempt to establish a
5136
        // persistent connection to the peer.
5137
        srvrLog.Debugf("Connecting to %v", addr)
4✔
5138
        if perm {
8✔
5139
                connReq := &connmgr.ConnReq{
4✔
5140
                        Addr:      addr,
4✔
5141
                        Permanent: true,
4✔
5142
                }
4✔
5143

4✔
5144
                // Since the user requested a permanent connection, we'll set
4✔
5145
                // the entry to true which will tell the server to continue
4✔
5146
                // reconnecting even if the number of channels with this peer is
4✔
5147
                // zero.
4✔
5148
                s.persistentPeers[targetPub] = true
4✔
5149
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
8✔
5150
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
4✔
5151
                }
4✔
5152
                s.persistentConnReqs[targetPub] = append(
4✔
5153
                        s.persistentConnReqs[targetPub], connReq,
4✔
5154
                )
4✔
5155
                s.mu.Unlock()
4✔
5156

4✔
5157
                go s.connMgr.Connect(connReq)
4✔
5158

4✔
5159
                return nil
4✔
5160
        }
5161
        s.mu.Unlock()
4✔
5162

4✔
5163
        // If we're not making a persistent connection, then we'll attempt to
4✔
5164
        // connect to the target peer. If the we can't make the connection, or
4✔
5165
        // the crypto negotiation breaks down, then return an error to the
4✔
5166
        // caller.
4✔
5167
        errChan := make(chan error, 1)
4✔
5168
        s.connectToPeer(addr, errChan, timeout)
4✔
5169

4✔
5170
        select {
4✔
5171
        case err := <-errChan:
4✔
5172
                return err
4✔
5173
        case <-s.quit:
×
5174
                return ErrServerShuttingDown
×
5175
        }
5176
}
5177

5178
// connectToPeer establishes a connection to a remote peer. errChan is used to
5179
// notify the caller if the connection attempt has failed. Otherwise, it will be
5180
// closed.
5181
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5182
        errChan chan<- error, timeout time.Duration) {
4✔
5183

4✔
5184
        conn, err := brontide.Dial(
4✔
5185
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
4✔
5186
        )
4✔
5187
        if err != nil {
8✔
5188
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
4✔
5189
                select {
4✔
5190
                case errChan <- err:
4✔
5191
                case <-s.quit:
×
5192
                }
5193
                return
4✔
5194
        }
5195

5196
        close(errChan)
4✔
5197

4✔
5198
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
4✔
5199
                conn.LocalAddr(), conn.RemoteAddr())
4✔
5200

4✔
5201
        s.OutboundPeerConnected(nil, conn)
4✔
5202
}
5203

5204
// DisconnectPeer sends the request to server to close the connection with peer
5205
// identified by public key.
5206
//
5207
// NOTE: This function is safe for concurrent access.
5208
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
4✔
5209
        pubBytes := pubKey.SerializeCompressed()
4✔
5210
        pubStr := string(pubBytes)
4✔
5211

4✔
5212
        s.mu.Lock()
4✔
5213
        defer s.mu.Unlock()
4✔
5214

4✔
5215
        // Check that were actually connected to this peer. If not, then we'll
4✔
5216
        // exit in an error as we can't disconnect from a peer that we're not
4✔
5217
        // currently connected to.
4✔
5218
        peer, err := s.findPeerByPubStr(pubStr)
4✔
5219
        if err == ErrPeerNotConnected {
8✔
5220
                return fmt.Errorf("peer %x is not connected", pubBytes)
4✔
5221
        }
4✔
5222

5223
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
5224

4✔
5225
        s.cancelConnReqs(pubStr, nil)
4✔
5226

4✔
5227
        // If this peer was formerly a persistent connection, then we'll remove
4✔
5228
        // them from this map so we don't attempt to re-connect after we
4✔
5229
        // disconnect.
4✔
5230
        delete(s.persistentPeers, pubStr)
4✔
5231
        delete(s.persistentPeersBackoff, pubStr)
4✔
5232

4✔
5233
        // Remove the peer by calling Disconnect. Previously this was done with
4✔
5234
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
4✔
5235
        //
4✔
5236
        // NOTE: We call it in a goroutine to avoid blocking the main server
4✔
5237
        // goroutine because we might hold the server's mutex.
4✔
5238
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
4✔
5239

4✔
5240
        return nil
4✔
5241
}
5242

5243
// OpenChannel sends a request to the server to open a channel to the specified
5244
// peer identified by nodeKey with the passed channel funding parameters.
5245
//
5246
// NOTE: This function is safe for concurrent access.
5247
func (s *server) OpenChannel(
5248
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4✔
5249

4✔
5250
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4✔
5251
        // + a ChanOpen update, and we want to make sure the funding process is
4✔
5252
        // not blocked if the caller is not reading the updates.
4✔
5253
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
4✔
5254
        req.Err = make(chan error, 1)
4✔
5255

4✔
5256
        // First attempt to locate the target peer to open a channel with, if
4✔
5257
        // we're unable to locate the peer then this request will fail.
4✔
5258
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
4✔
5259
        s.mu.RLock()
4✔
5260
        peer, ok := s.peersByPub[string(pubKeyBytes)]
4✔
5261
        if !ok {
4✔
5262
                s.mu.RUnlock()
×
5263

×
5264
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5265
                return req.Updates, req.Err
×
5266
        }
×
5267
        req.Peer = peer
4✔
5268
        s.mu.RUnlock()
4✔
5269

4✔
5270
        // We'll wait until the peer is active before beginning the channel
4✔
5271
        // opening process.
4✔
5272
        select {
4✔
5273
        case <-peer.ActiveSignal():
4✔
5274
        case <-peer.QuitSignal():
×
5275
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5276
                return req.Updates, req.Err
×
5277
        case <-s.quit:
×
5278
                req.Err <- ErrServerShuttingDown
×
5279
                return req.Updates, req.Err
×
5280
        }
5281

5282
        // If the fee rate wasn't specified at this point we fail the funding
5283
        // because of the missing fee rate information. The caller of the
5284
        // `OpenChannel` method needs to make sure that default values for the
5285
        // fee rate are set beforehand.
5286
        if req.FundingFeePerKw == 0 {
4✔
5287
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5288
                        "the channel opening transaction")
×
5289

×
5290
                return req.Updates, req.Err
×
5291
        }
×
5292

5293
        // Spawn a goroutine to send the funding workflow request to the funding
5294
        // manager. This allows the server to continue handling queries instead
5295
        // of blocking on this request which is exported as a synchronous
5296
        // request to the outside world.
5297
        go s.fundingMgr.InitFundingWorkflow(req)
4✔
5298

4✔
5299
        return req.Updates, req.Err
4✔
5300
}
5301

5302
// Peers returns a slice of all active peers.
5303
//
5304
// NOTE: This function is safe for concurrent access.
5305
func (s *server) Peers() []*peer.Brontide {
4✔
5306
        s.mu.RLock()
4✔
5307
        defer s.mu.RUnlock()
4✔
5308

4✔
5309
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
4✔
5310
        for _, peer := range s.peersByPub {
8✔
5311
                peers = append(peers, peer)
4✔
5312
        }
4✔
5313

5314
        return peers
4✔
5315
}
5316

5317
// computeNextBackoff uses a truncated exponential backoff to compute the next
5318
// backoff using the value of the exiting backoff. The returned duration is
5319
// randomized in either direction by 1/20 to prevent tight loops from
5320
// stabilizing.
5321
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
4✔
5322
        // Double the current backoff, truncating if it exceeds our maximum.
4✔
5323
        nextBackoff := 2 * currBackoff
4✔
5324
        if nextBackoff > maxBackoff {
8✔
5325
                nextBackoff = maxBackoff
4✔
5326
        }
4✔
5327

5328
        // Using 1/10 of our duration as a margin, compute a random offset to
5329
        // avoid the nodes entering connection cycles.
5330
        margin := nextBackoff / 10
4✔
5331

4✔
5332
        var wiggle big.Int
4✔
5333
        wiggle.SetUint64(uint64(margin))
4✔
5334
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4✔
5335
                // Randomizing is not mission critical, so we'll just return the
×
5336
                // current backoff.
×
5337
                return nextBackoff
×
5338
        }
×
5339

5340
        // Otherwise add in our wiggle, but subtract out half of the margin so
5341
        // that the backoff can tweaked by 1/20 in either direction.
5342
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4✔
5343
}
5344

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

5349
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5350
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5351
        pub *btcec.PublicKey) ([]net.Addr, error) {
4✔
5352

4✔
5353
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
4✔
5354
        if err != nil {
4✔
5355
                return nil, err
×
5356
        }
×
5357

5358
        node, err := s.v1Graph.FetchNode(ctx, vertex)
4✔
5359
        if err != nil {
8✔
5360
                return nil, err
4✔
5361
        }
4✔
5362

5363
        if len(node.Addresses) == 0 {
8✔
5364
                return nil, errNoAdvertisedAddr
4✔
5365
        }
4✔
5366

5367
        return node.Addresses, nil
4✔
5368
}
5369

5370
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5371
// channel update for a target channel.
5372
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5373
        *lnwire.ChannelUpdate1, error) {
4✔
5374

4✔
5375
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
4✔
5376
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
8✔
5377
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
4✔
5378
                if err != nil {
8✔
5379
                        return nil, err
4✔
5380
                }
4✔
5381

5382
                return netann.ExtractChannelUpdate(
4✔
5383
                        ourPubKey[:], info, edge1, edge2,
4✔
5384
                )
4✔
5385
        }
5386
}
5387

5388
// applyChannelUpdate applies the channel update to the different sub-systems of
5389
// the server. The useAlias boolean denotes whether or not to send an alias in
5390
// place of the real SCID.
5391
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5392
        op *wire.OutPoint, useAlias bool) error {
4✔
5393

4✔
5394
        var (
4✔
5395
                peerAlias    *lnwire.ShortChannelID
4✔
5396
                defaultAlias lnwire.ShortChannelID
4✔
5397
        )
4✔
5398

4✔
5399
        chanID := lnwire.NewChanIDFromOutPoint(*op)
4✔
5400

4✔
5401
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
4✔
5402
        // in the ChannelUpdate if it hasn't been announced yet.
4✔
5403
        if useAlias {
8✔
5404
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
4✔
5405
                if foundAlias != defaultAlias {
8✔
5406
                        peerAlias = &foundAlias
4✔
5407
                }
4✔
5408
        }
5409

5410
        fut := s.authGossiper.ProcessLocalAnnouncement(
4✔
5411
                update, discovery.RemoteAlias(peerAlias),
4✔
5412
        )
4✔
5413

4✔
5414
        ctx, cancel := lnutils.ContextFromQuit(s.quit)
4✔
5415
        defer cancel()
4✔
5416

4✔
5417
        return discovery.AwaitGossipResult(ctx, fut)
4✔
5418
}
5419

5420
// SendCustomMessage sends a custom message to the peer with the specified
5421
// pubkey.
5422
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5423
        msgType lnwire.MessageType, data []byte) error {
4✔
5424

4✔
5425
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
5426
        if err != nil {
8✔
5427
                return err
4✔
5428
        }
4✔
5429

5430
        // We'll wait until the peer is active, but also listen for
5431
        // cancellation.
5432
        select {
4✔
5433
        case <-peer.ActiveSignal():
4✔
5434
        case <-peer.QuitSignal():
×
5435
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5436
        case <-s.quit:
×
5437
                return ErrServerShuttingDown
×
5438
        case <-ctx.Done():
×
5439
                return ctx.Err()
×
5440
        }
5441

5442
        msg, err := lnwire.NewCustom(msgType, data)
4✔
5443
        if err != nil {
8✔
5444
                return err
4✔
5445
        }
4✔
5446

5447
        // Send the message as low-priority. For now we assume that all
5448
        // application-defined message are low priority.
5449
        return peer.SendMessageLazy(true, msg)
4✔
5450
}
5451

5452
// SendOnionMessage sends a custom message to the peer with the specified
5453
// pubkey.
5454
// TODO(gijs): change this message to include path finding.
5455
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5456
        pathKey *btcec.PublicKey, onion []byte) error {
4✔
5457

4✔
5458
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
4✔
5459
        if err != nil {
4✔
5460
                return err
×
5461
        }
×
5462

5463
        // We'll wait until the peer is active, but also listen for
5464
        // cancellation.
5465
        select {
4✔
5466
        case <-peer.ActiveSignal():
4✔
5467
        case <-peer.QuitSignal():
×
5468
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5469
        case <-s.quit:
×
5470
                return ErrServerShuttingDown
×
5471
        case <-ctx.Done():
×
5472
                return ctx.Err()
×
5473
        }
5474

5475
        msg := lnwire.NewOnionMessage(pathKey, onion)
4✔
5476

4✔
5477
        // Send the message as low-priority. For now we assume that all
4✔
5478
        // application-defined message are low priority.
4✔
5479
        return peer.SendMessageLazy(true, msg)
4✔
5480
}
5481

5482
// SendToPeer sends an onion message to the peer identified by the given
5483
// compressed public key. This implements the onionmessage.PeerMessageSender
5484
// interface and is used by the onion peer actor when forwarding messages.
5485
func (s *server) SendToPeer(pubKey [33]byte,
5486
        msg *lnwire.OnionMessage) error {
4✔
5487

4✔
5488
        peer, err := s.FindPeerByPubStr(string(pubKey[:]))
4✔
5489
        if err != nil {
4✔
5490
                return err
×
5491
        }
×
5492

5493
        return peer.SendMessageLazy(true, msg)
4✔
5494
}
5495

5496
// newSweepPkScriptGen creates closure that generates a new public key script
5497
// which should be used to sweep any funds into the on-chain wallet.
5498
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5499
// (p2wkh) output.
5500
func newSweepPkScriptGen(
5501
        wallet lnwallet.WalletController,
5502
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
4✔
5503

4✔
5504
        return func() fn.Result[lnwallet.AddrWithKey] {
8✔
5505
                sweepAddr, err := wallet.NewAddress(
4✔
5506
                        lnwallet.TaprootPubkey, false,
4✔
5507
                        lnwallet.DefaultAccountName,
4✔
5508
                )
4✔
5509
                if err != nil {
4✔
5510
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5511
                }
×
5512

5513
                addr, err := txscript.PayToAddrScript(sweepAddr)
4✔
5514
                if err != nil {
4✔
5515
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5516
                }
×
5517

5518
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
4✔
5519
                        wallet, netParams, addr,
4✔
5520
                )
4✔
5521
                if err != nil {
4✔
5522
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5523
                }
×
5524

5525
                return fn.Ok(lnwallet.AddrWithKey{
4✔
5526
                        DeliveryAddress: addr,
4✔
5527
                        InternalKey:     internalKeyDesc,
4✔
5528
                })
4✔
5529
        }
5530
}
5531

5532
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5533
// finished.
5534
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
4✔
5535
        // Get a list of closed channels.
4✔
5536
        channels, err := s.chanStateDB.FetchClosedChannels(false)
4✔
5537
        if err != nil {
4✔
5538
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5539
                return nil
×
5540
        }
×
5541

5542
        // Save the SCIDs in a map.
5543
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
4✔
5544
        for _, c := range channels {
8✔
5545
                // If the channel is not pending, its FC has been finalized.
4✔
5546
                if !c.IsPending {
8✔
5547
                        closedSCIDs[c.ShortChanID] = struct{}{}
4✔
5548
                }
4✔
5549
        }
5550

5551
        // Double check whether the reported closed channel has indeed finished
5552
        // closing.
5553
        //
5554
        // NOTE: There are misalignments regarding when a channel's FC is
5555
        // marked as finalized. We double check the pending channels to make
5556
        // sure the returned SCIDs are indeed terminated.
5557
        //
5558
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5559
        pendings, err := s.chanStateDB.FetchPendingChannels()
4✔
5560
        if err != nil {
4✔
5561
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5562
                return nil
×
5563
        }
×
5564

5565
        for _, c := range pendings {
8✔
5566
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
8✔
5567
                        continue
4✔
5568
                }
5569

5570
                // If the channel is still reported as pending, remove it from
5571
                // the map.
5572
                delete(closedSCIDs, c.ShortChannelID)
×
5573

×
5574
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5575
                        c.ShortChannelID)
×
5576
        }
5577

5578
        return closedSCIDs
4✔
5579
}
5580

5581
// getStartingBeat returns the current beat. This is used during the startup to
5582
// initialize blockbeat consumers.
5583
func (s *server) getStartingBeat() (*chainio.Beat, error) {
4✔
5584
        // beat is the current blockbeat.
4✔
5585
        var beat *chainio.Beat
4✔
5586

4✔
5587
        // If the node is configured with nochainbackend mode (remote signer),
4✔
5588
        // we will skip fetching the best block.
4✔
5589
        if s.cfg.Bitcoin.Node == "nochainbackend" {
4✔
5590
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5591
                        "mode")
×
5592

×
5593
                return &chainio.Beat{}, nil
×
5594
        }
×
5595

5596
        // We should get a notification with the current best block immediately
5597
        // by passing a nil block.
5598
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
4✔
5599
        if err != nil {
4✔
5600
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5601
        }
×
5602
        defer blockEpochs.Cancel()
4✔
5603

4✔
5604
        // We registered for the block epochs with a nil request. The notifier
4✔
5605
        // should send us the current best block immediately. So we need to
4✔
5606
        // wait for it here because we need to know the current best height.
4✔
5607
        select {
4✔
5608
        case bestBlock := <-blockEpochs.Epochs:
4✔
5609
                srvrLog.Infof("Received initial block %v at height %d",
4✔
5610
                        bestBlock.Hash, bestBlock.Height)
4✔
5611

4✔
5612
                // Update the current blockbeat.
4✔
5613
                beat = chainio.NewBeat(*bestBlock)
4✔
5614

5615
        case <-s.quit:
×
5616
                srvrLog.Debug("LND shutting down")
×
5617
        }
5618

5619
        return beat, nil
4✔
5620
}
5621

5622
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5623
// point has an active RBF chan closer.
5624
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5625
        chanPoint wire.OutPoint) bool {
4✔
5626

4✔
5627
        pubBytes := peerPub.SerializeCompressed()
4✔
5628

4✔
5629
        s.mu.RLock()
4✔
5630
        targetPeer, ok := s.peersByPub[string(pubBytes)]
4✔
5631
        s.mu.RUnlock()
4✔
5632
        if !ok {
4✔
5633
                return false
×
5634
        }
×
5635

5636
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
4✔
5637
}
5638

5639
// calculateNodeAnnouncementTimestamp returns the timestamp to use for a node
5640
// announcement, ensuring it's at least one second after the previously
5641
// persisted timestamp. This ensures BOLT-07 compliance, which requires node
5642
// announcements to have strictly increasing timestamps.
5643
func calculateNodeAnnouncementTimestamp(persistedTime,
5644
        currentTime time.Time) time.Time {
13✔
5645

13✔
5646
        if persistedTime.Unix() >= currentTime.Unix() {
23✔
5647
                return persistedTime.Add(time.Second)
10✔
5648
        }
10✔
5649

5650
        return currentTime
7✔
5651
}
5652

5653
// setSelfNode configures and sets the server's self node. It sets the node
5654
// announcement, signs it, and updates the source node in the graph. When
5655
// determining values such as color and alias, the method prioritizes values
5656
// set in the config, then values previously persisted on disk, and finally
5657
// falls back to the defaults.
5658
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5659
        listenAddrs []net.Addr) error {
4✔
5660

4✔
5661
        // If we were requested to automatically configure port forwarding,
4✔
5662
        // we'll use the ports that the server will be listening on.
4✔
5663
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
4✔
5664
        for _, ip := range s.cfg.ExternalIPs {
8✔
5665
                externalIPStrings = append(externalIPStrings, ip.String())
4✔
5666
        }
4✔
5667
        if s.natTraversal != nil {
4✔
5668
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5669
                for _, listenAddr := range listenAddrs {
×
5670
                        // At this point, the listen addresses should have
×
5671
                        // already been normalized, so it's safe to ignore the
×
5672
                        // errors.
×
5673
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5674
                        port, _ := strconv.Atoi(portStr)
×
5675

×
5676
                        listenPorts = append(listenPorts, uint16(port))
×
5677
                }
×
5678

5679
                ips, err := s.configurePortForwarding(listenPorts...)
×
5680
                if err != nil {
×
5681
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5682
                                "forwarding using %s: %v",
×
5683
                                s.natTraversal.Name(), err)
×
5684
                } else {
×
5685
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5686
                                "using %s to advertise external IP",
×
5687
                                s.natTraversal.Name())
×
5688
                        externalIPStrings = append(externalIPStrings, ips...)
×
5689
                }
×
5690
        }
5691

5692
        // Normalize the external IP strings to net.Addr.
5693
        addrs, err := lncfg.NormalizeAddresses(
4✔
5694
                externalIPStrings, strconv.Itoa(defaultPeerPort),
4✔
5695
                s.cfg.net.ResolveTCPAddr,
4✔
5696
        )
4✔
5697
        if err != nil {
4✔
5698
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5699
        }
×
5700

5701
        // Parse the color from config. We will update this later if the config
5702
        // color is not changed from default (#3399FF) and we have a value in
5703
        // the source node.
5704
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
4✔
5705
        if err != nil {
4✔
5706
                return fmt.Errorf("unable to parse color: %w", err)
×
5707
        }
×
5708

5709
        var (
4✔
5710
                alias          = s.cfg.Alias
4✔
5711
                nodeLastUpdate = time.Now()
4✔
5712
        )
4✔
5713

4✔
5714
        srcNode, err := s.v1Graph.SourceNode(ctx)
4✔
5715
        switch {
4✔
5716
        case err == nil:
4✔
5717
                // If we have a source node persisted in the DB already, then we
4✔
5718
                // just need to make sure that the new LastUpdate time is at
4✔
5719
                // least one second after the last update time.
4✔
5720
                nodeLastUpdate = calculateNodeAnnouncementTimestamp(
4✔
5721
                        srcNode.LastUpdate, nodeLastUpdate,
4✔
5722
                )
4✔
5723

4✔
5724
                // If the color is not changed from default, it means that we
4✔
5725
                // didn't specify a different color in the config. We'll use the
4✔
5726
                // source node's color.
4✔
5727
                if s.cfg.Color == defaultColor {
8✔
5728
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
8✔
5729
                                nodeColor = rgba
4✔
5730
                        })
4✔
5731
                }
5732

5733
                // If an alias is not specified in the config, we'll use the
5734
                // source node's alias.
5735
                if alias == "" {
8✔
5736
                        srcNode.Alias.WhenSome(func(s string) {
8✔
5737
                                alias = s
4✔
5738
                        })
4✔
5739
                }
5740

5741
                // If the `externalip` is not specified in the config, it means
5742
                // `addrs` will be empty, we'll use the source node's addresses.
5743
                if len(s.cfg.ExternalIPs) == 0 {
8✔
5744
                        addrs = srcNode.Addresses
4✔
5745
                }
4✔
5746

5747
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
4✔
5748
                // If an alias is not specified in the config, we'll use the
4✔
5749
                // default, which is the first 10 bytes of the serialized
4✔
5750
                // pubkey.
4✔
5751
                if alias == "" {
8✔
5752
                        alias = hex.EncodeToString(nodePub[:10])
4✔
5753
                }
4✔
5754

5755
        // If the above cases are not matched, then we have an unhandled non
5756
        // nil error.
5757
        default:
×
5758
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5759
        }
5760

5761
        nodeAlias, err := lnwire.NewNodeAlias(alias)
4✔
5762
        if err != nil {
4✔
5763
                return err
×
5764
        }
×
5765

5766
        // TODO(abdulkbk): potentially find a way to use the source node's
5767
        // features in the self node.
5768
        selfNode := models.NewV1Node(
4✔
5769
                nodePub, &models.NodeV1Fields{
4✔
5770
                        Alias:      nodeAlias.String(),
4✔
5771
                        Color:      nodeColor,
4✔
5772
                        LastUpdate: nodeLastUpdate,
4✔
5773
                        Addresses:  addrs,
4✔
5774
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
4✔
5775
                },
4✔
5776
        )
4✔
5777

4✔
5778
        // Based on the disk representation of the node announcement generated
4✔
5779
        // above, we'll generate a node announcement that can go out on the
4✔
5780
        // network so we can properly sign it.
4✔
5781
        nodeAnn, err := selfNode.NodeAnnouncement(false)
4✔
5782
        if err != nil {
4✔
5783
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5784
        }
×
5785

5786
        // With the announcement generated, we'll sign it to properly
5787
        // authenticate the message on the network.
5788
        authSig, err := netann.SignAnnouncement(
4✔
5789
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
4✔
5790
        )
4✔
5791
        if err != nil {
4✔
5792
                return fmt.Errorf("unable to generate signature for self node "+
×
5793
                        "announcement: %v", err)
×
5794
        }
×
5795

5796
        selfNode.AuthSigBytes = authSig.Serialize()
4✔
5797
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
4✔
5798
                selfNode.AuthSigBytes,
4✔
5799
        )
4✔
5800
        if err != nil {
4✔
5801
                return err
×
5802
        }
×
5803

5804
        // Finally, we'll update the representation on disk, and update our
5805
        // cached in-memory version as well.
5806
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
4✔
5807
                return fmt.Errorf("can't set self node: %w", err)
×
5808
        }
×
5809

5810
        s.currentNodeAnn = nodeAnn
4✔
5811

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

© 2026 Coveralls, Inc