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

lightningnetwork / lnd / 20317897109

17 Dec 2025 09:31PM UTC coverage: 65.27% (+0.08%) from 65.195%
20317897109

Pull #10089

github

web-flow
Merge e066ba6ed into 91423ee51
Pull Request #10089: Onion message forwarding

1101 of 1361 new or added lines in 22 files covered. (80.9%)

103 existing lines in 23 files now uncovered.

138855 of 212741 relevant lines covered (65.27%)

20630.32 hits per line

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

69.41
/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/clock"
42
        "github.com/lightningnetwork/lnd/cluster"
43
        "github.com/lightningnetwork/lnd/contractcourt"
44
        "github.com/lightningnetwork/lnd/discovery"
45
        "github.com/lightningnetwork/lnd/feature"
46
        "github.com/lightningnetwork/lnd/fn/v2"
47
        "github.com/lightningnetwork/lnd/funding"
48
        "github.com/lightningnetwork/lnd/graph"
49
        graphdb "github.com/lightningnetwork/lnd/graph/db"
50
        "github.com/lightningnetwork/lnd/graph/db/models"
51
        "github.com/lightningnetwork/lnd/healthcheck"
52
        "github.com/lightningnetwork/lnd/htlcswitch"
53
        "github.com/lightningnetwork/lnd/htlcswitch/hop"
54
        "github.com/lightningnetwork/lnd/input"
55
        "github.com/lightningnetwork/lnd/invoices"
56
        "github.com/lightningnetwork/lnd/keychain"
57
        "github.com/lightningnetwork/lnd/lncfg"
58
        "github.com/lightningnetwork/lnd/lnencrypt"
59
        "github.com/lightningnetwork/lnd/lnpeer"
60
        "github.com/lightningnetwork/lnd/lnrpc"
61
        "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
62
        "github.com/lightningnetwork/lnd/lnutils"
63
        "github.com/lightningnetwork/lnd/lnwallet"
64
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
65
        "github.com/lightningnetwork/lnd/lnwallet/chancloser"
66
        "github.com/lightningnetwork/lnd/lnwallet/chanfunding"
67
        "github.com/lightningnetwork/lnd/lnwallet/rpcwallet"
68
        "github.com/lightningnetwork/lnd/lnwire"
69
        "github.com/lightningnetwork/lnd/nat"
70
        "github.com/lightningnetwork/lnd/netann"
71
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
72
        "github.com/lightningnetwork/lnd/peer"
73
        "github.com/lightningnetwork/lnd/peernotifier"
74
        "github.com/lightningnetwork/lnd/pool"
75
        "github.com/lightningnetwork/lnd/queue"
76
        "github.com/lightningnetwork/lnd/routing"
77
        "github.com/lightningnetwork/lnd/routing/localchans"
78
        "github.com/lightningnetwork/lnd/routing/route"
79
        "github.com/lightningnetwork/lnd/subscribe"
80
        "github.com/lightningnetwork/lnd/sweep"
81
        "github.com/lightningnetwork/lnd/ticker"
82
        "github.com/lightningnetwork/lnd/tor"
83
        "github.com/lightningnetwork/lnd/walletunlocker"
84
        "github.com/lightningnetwork/lnd/watchtower/blob"
85
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
86
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
87
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
88
)
89

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

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

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

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

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

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

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

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

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

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

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

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

160
        // ErrNoPeerScore is returned when we expect to find a score in
161
        // peerScores, but one does not exist.
162
        ErrNoPeerScore = errors.New("peer score not found")
163

164
        // ErrNoPendingPeerInfo is returned when we couldn't find any pending
165
        // peer info.
166
        ErrNoPendingPeerInfo = errors.New("no pending peer info")
167
)
168

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

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

182
// peerAccessStatus denotes the p2p access status of a given peer. This will be
183
// used to assign peer ban scores that determine an action the server will
184
// take.
185
type peerAccessStatus int
186

187
const (
188
        // peerStatusRestricted indicates that the peer only has access to the
189
        // limited number of "free" reserved slots.
190
        peerStatusRestricted peerAccessStatus = iota
191

192
        // peerStatusTemporary indicates that the peer only has temporary p2p
193
        // access to the server.
194
        peerStatusTemporary
195

196
        // peerStatusProtected indicates that the peer has been granted
197
        // permanent p2p access to the server. The peer can still have its
198
        // access revoked.
199
        peerStatusProtected
200
)
201

202
// String returns a human-readable representation of the status code.
203
func (p peerAccessStatus) String() string {
3✔
204
        switch p {
3✔
205
        case peerStatusRestricted:
3✔
206
                return "restricted"
3✔
207

208
        case peerStatusTemporary:
3✔
209
                return "temporary"
3✔
210

211
        case peerStatusProtected:
3✔
212
                return "protected"
3✔
213

214
        default:
×
215
                return "unknown"
×
216
        }
217
}
218

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

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

234
        start sync.Once
235
        stop  sync.Once
236

237
        cfg *Config
238

239
        implCfg *ImplementationCfg
240

241
        // identityECDH is an ECDH capable wrapper for the private key used
242
        // to authenticate any incoming connections.
243
        identityECDH keychain.SingleKeyECDH
244

245
        // identityKeyLoc is the key locator for the above wrapped identity key.
246
        identityKeyLoc keychain.KeyLocator
247

248
        // nodeSigner is an implementation of the MessageSigner implementation
249
        // that's backed by the identity private key of the running lnd node.
250
        nodeSigner *netann.NodeSigner
251

252
        chanStatusMgr *netann.ChanStatusManager
253

254
        // listenAddrs is the list of addresses the server is currently
255
        // listening on.
256
        listenAddrs []net.Addr
257

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

264
        // natTraversal is the specific NAT traversal technique used to
265
        // automatically set up port forwarding rules in order to advertise to
266
        // the network that the node is accepting inbound connections.
267
        natTraversal nat.Traversal
268

269
        // lastDetectedIP is the last IP detected by the NAT traversal technique
270
        // above. This IP will be watched periodically in a goroutine in order
271
        // to handle dynamic IP changes.
272
        lastDetectedIP net.IP
273

274
        mu sync.RWMutex
275

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

285
        inboundPeers  map[string]*peer.Brontide
286
        outboundPeers map[string]*peer.Brontide
287

288
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
289
        peerDisconnectedListeners map[string][]chan<- struct{}
290

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

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

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

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

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

326
        cc *chainreg.ChainControl
327

328
        fundingMgr *funding.Manager
329

330
        graphDB *graphdb.ChannelGraph
331

332
        chanStateDB *channeldb.ChannelStateDB
333

334
        addrSource channeldb.AddrSource
335

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

340
        invoicesDB invoices.InvoiceDB
341

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

346
        aliasMgr *aliasmgr.Manager
347

348
        htlcSwitch *htlcswitch.Switch
349

350
        interceptableSwitch *htlcswitch.InterceptableSwitch
351

352
        invoices *invoices.InvoiceRegistry
353

354
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
355

356
        channelNotifier *channelnotifier.ChannelNotifier
357

358
        peerNotifier *peernotifier.PeerNotifier
359

360
        htlcNotifier *htlcswitch.HtlcNotifier
361

362
        witnessBeacon contractcourt.WitnessBeacon
363

364
        breachArbitrator *contractcourt.BreachArbitrator
365

366
        missionController *routing.MissionController
367
        defaultMC         *routing.MissionControl
368

369
        graphBuilder *graph.Builder
370

371
        chanRouter *routing.ChannelRouter
372

373
        controlTower routing.ControlTower
374

375
        authGossiper *discovery.AuthenticatedGossiper
376

377
        localChanMgr *localchans.Manager
378

379
        utxoNursery *contractcourt.UtxoNursery
380

381
        sweeper *sweep.UtxoSweeper
382

383
        chainArb *contractcourt.ChainArbitrator
384

385
        sphinx *hop.OnionProcessor
386

387
        sphinxRouterNoReplayLog *sphinx.Router
388

389
        towerClientMgr *wtclient.Manager
390

391
        connMgr *connmgr.ConnManager
392

393
        sigPool *lnwallet.SigPool
394

395
        writePool *pool.Write
396

397
        readPool *pool.Read
398

399
        tlsManager *TLSManager
400

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

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

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

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

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

423
        hostAnn *netann.HostAnnouncer
424

425
        // livenessMonitor monitors that lnd has access to critical resources.
426
        livenessMonitor *healthcheck.Monitor
427

428
        customMessageServer *subscribe.Server
429

430
        onionMessageServer *subscribe.Server
431

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

436
        // txPublisher is a publisher with fee-bumping capability.
437
        txPublisher *sweep.TxPublisher
438

439
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
440
        // of new blocks.
441
        blockbeatDispatcher *chainio.BlockbeatDispatcher
442

443
        // peerAccessMan implements peer access controls.
444
        peerAccessMan *accessMan
445

446
        quit chan struct{}
447

448
        wg sync.WaitGroup
449
}
450

451
// updatePersistentPeerAddrs subscribes to topology changes and stores
452
// advertised addresses for any NodeAnnouncements from our persisted peers.
453
func (s *server) updatePersistentPeerAddrs() error {
3✔
454
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
455
        if err != nil {
3✔
456
                return err
×
457
        }
×
458

459
        s.wg.Add(1)
3✔
460
        go func() {
6✔
461
                defer func() {
6✔
462
                        graphSub.Cancel()
3✔
463
                        s.wg.Done()
3✔
464
                }()
3✔
465

466
                for {
6✔
467
                        select {
3✔
468
                        case <-s.quit:
3✔
469
                                return
3✔
470

471
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
472
                                // If the router is shutting down, then we will
3✔
473
                                // as well.
3✔
474
                                if !ok {
3✔
475
                                        return
×
476
                                }
×
477

478
                                for _, update := range topChange.NodeUpdates {
6✔
479
                                        pubKeyStr := string(
3✔
480
                                                update.IdentityKey.
3✔
481
                                                        SerializeCompressed(),
3✔
482
                                        )
3✔
483

3✔
484
                                        // We only care about updates from
3✔
485
                                        // our persistentPeers.
3✔
486
                                        s.mu.RLock()
3✔
487
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
488
                                        s.mu.RUnlock()
3✔
489
                                        if !ok {
6✔
490
                                                continue
3✔
491
                                        }
492

493
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
494
                                                len(update.Addresses))
3✔
495

3✔
496
                                        for _, addr := range update.Addresses {
6✔
497
                                                addrs = append(addrs,
3✔
498
                                                        &lnwire.NetAddress{
3✔
499
                                                                IdentityKey: update.IdentityKey,
3✔
500
                                                                Address:     addr,
3✔
501
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
502
                                                        },
3✔
503
                                                )
3✔
504
                                        }
3✔
505

506
                                        s.mu.Lock()
3✔
507

3✔
508
                                        // Update the stored addresses for this
3✔
509
                                        // to peer to reflect the new set.
3✔
510
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
511

3✔
512
                                        // If there are no outstanding
3✔
513
                                        // connection requests for this peer
3✔
514
                                        // then our work is done since we are
3✔
515
                                        // not currently trying to connect to
3✔
516
                                        // them.
3✔
517
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
518
                                                s.mu.Unlock()
3✔
519
                                                continue
3✔
520
                                        }
521

522
                                        s.mu.Unlock()
3✔
523

3✔
524
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
525
                                }
526
                        }
527
                }
528
        }()
529

530
        return nil
3✔
531
}
532

533
// CustomMessage is a custom message that is received from a peer.
534
type CustomMessage struct {
535
        // Peer is the peer pubkey
536
        Peer [33]byte
537

538
        // Msg is the custom wire message.
539
        Msg *lnwire.Custom
540
}
541

542
// parseAddr parses an address from its string format to a net.Addr.
543
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
544
        var (
3✔
545
                host string
3✔
546
                port int
3✔
547
        )
3✔
548

3✔
549
        // Split the address into its host and port components.
3✔
550
        h, p, err := net.SplitHostPort(address)
3✔
551
        if err != nil {
3✔
552
                // If a port wasn't specified, we'll assume the address only
×
553
                // contains the host so we'll use the default port.
×
554
                host = address
×
555
                port = defaultPeerPort
×
556
        } else {
3✔
557
                // Otherwise, we'll note both the host and ports.
3✔
558
                host = h
3✔
559
                portNum, err := strconv.Atoi(p)
3✔
560
                if err != nil {
3✔
561
                        return nil, err
×
562
                }
×
563
                port = portNum
3✔
564
        }
565

566
        if tor.IsOnionHost(host) {
3✔
567
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
568
        }
×
569

570
        // If the host is part of a TCP address, we'll use the network
571
        // specific ResolveTCPAddr function in order to resolve these
572
        // addresses over Tor in order to prevent leaking your real IP
573
        // address.
574
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
575
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
576
}
577

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

3✔
583
        return func(a net.Addr) (net.Conn, error) {
6✔
584
                lnAddr := a.(*lnwire.NetAddress)
3✔
585
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
586
        }
3✔
587
}
588

589
// newServer creates a new instance of the server which is to listen using the
590
// passed listener address.
591
//
592
//nolint:funlen
593
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
594
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
595
        nodeKeyDesc *keychain.KeyDescriptor,
596
        chansToRestore walletunlocker.ChannelsToRecover,
597
        chanPredicate chanacceptor.ChannelAcceptor,
598
        torController *tor.Controller, tlsManager *TLSManager,
599
        leaderElector cluster.LeaderElector,
600
        implCfg *ImplementationCfg) (*server, error) {
3✔
601

3✔
602
        var (
3✔
603
                err         error
3✔
604
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
605

3✔
606
                // We just derived the full descriptor, so we know the public
3✔
607
                // key is set on it.
3✔
608
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
609
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
610
                )
3✔
611
        )
3✔
612

3✔
613
        netParams := cfg.ActiveNetParams.Params
3✔
614

3✔
615
        // Initialize the sphinx router.
3✔
616
        replayLog := htlcswitch.NewDecayedLog(
3✔
617
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
618
        )
3✔
619
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
620

3✔
621
        // TODO(gijs): remove the memory replay log once lightning-onion
3✔
622
        // supports it.
3✔
623
        sphinxRouterNoReplayLog := sphinx.NewRouter(
3✔
624
                nodeKeyECDH, sphinx.NewMemoryReplayLog(),
3✔
625
        )
3✔
626

3✔
627
        writeBufferPool := pool.NewWriteBuffer(
3✔
628
                pool.DefaultWriteBufferGCInterval,
3✔
629
                pool.DefaultWriteBufferExpiryInterval,
3✔
630
        )
3✔
631

3✔
632
        writePool := pool.NewWrite(
3✔
633
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
634
        )
3✔
635

3✔
636
        readBufferPool := pool.NewReadBuffer(
3✔
637
                pool.DefaultReadBufferGCInterval,
3✔
638
                pool.DefaultReadBufferExpiryInterval,
3✔
639
        )
3✔
640

3✔
641
        readPool := pool.NewRead(
3✔
642
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
643
        )
3✔
644

3✔
645
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
646
        // controller, then we'll exit as this is incompatible.
3✔
647
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
648
                implCfg.AuxFundingController.IsNone() {
3✔
649

×
650
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
651
                        "overlay channels are not supported " +
×
652
                        "in a standalone lnd build")
×
653
        }
×
654

655
        //nolint:ll
656
        featureMgr, err := feature.NewManager(feature.Config{
3✔
657
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
658
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
659
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
660
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
661
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
662
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
663
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
664
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
665
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
666
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
667
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
668
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
669
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
670
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
671
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
672
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
673
        })
3✔
674
        if err != nil {
3✔
675
                return nil, err
×
676
        }
×
677

678
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
679
        registryConfig := invoices.RegistryConfig{
3✔
680
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
681
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
682
                Clock:                       clock.NewDefaultClock(),
3✔
683
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
684
                AcceptAMP:                   cfg.AcceptAMP,
3✔
685
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
686
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
687
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
688
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
689
        }
3✔
690

3✔
691
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
692

3✔
693
        s := &server{
3✔
694
                cfg:            cfg,
3✔
695
                implCfg:        implCfg,
3✔
696
                graphDB:        dbs.GraphDB,
3✔
697
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
698
                addrSource:     addrSource,
3✔
699
                miscDB:         dbs.ChanStateDB,
3✔
700
                invoicesDB:     dbs.InvoiceDB,
3✔
701
                paymentsDB:     dbs.PaymentsDB,
3✔
702
                cc:             cc,
3✔
703
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
704
                writePool:      writePool,
3✔
705
                readPool:       readPool,
3✔
706
                chansToRestore: chansToRestore,
3✔
707

3✔
708
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
709
                        cc.ChainNotifier,
3✔
710
                ),
3✔
711
                channelNotifier: channelnotifier.New(
3✔
712
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
713
                ),
3✔
714

3✔
715
                identityECDH:   nodeKeyECDH,
3✔
716
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
717
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
718

3✔
719
                listenAddrs: listenAddrs,
3✔
720

3✔
721
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
722
                // schedule
3✔
723
                sphinx:                  hop.NewOnionProcessor(sphinxRouter),
3✔
724
                sphinxRouterNoReplayLog: sphinxRouterNoReplayLog,
3✔
725

3✔
726
                torController: torController,
3✔
727

3✔
728
                persistentPeers:         make(map[string]bool),
3✔
729
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
730
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
731
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
732
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
733
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
734
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
735
                scheduledPeerConnection: make(map[string]func()),
3✔
736
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
737

3✔
738
                peersByPub:                make(map[string]*peer.Brontide),
3✔
739
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
740
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
741
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
742
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
743

3✔
744
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
745

3✔
746
                customMessageServer: subscribe.NewServer(),
3✔
747

3✔
748
                onionMessageServer: subscribe.NewServer(),
3✔
749

3✔
750
                actorSystem: actor.NewActorSystem(),
3✔
751

3✔
752
                tlsManager: tlsManager,
3✔
753

3✔
754
                featureMgr: featureMgr,
3✔
755
                quit:       make(chan struct{}),
3✔
756
        }
3✔
757

3✔
758
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
759
        if err != nil {
3✔
760
                return nil, err
×
761
        }
×
762

763
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
764
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
765
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
766
        )
3✔
767
        s.invoices = invoices.NewRegistry(
3✔
768
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
769
        )
3✔
770

3✔
771
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
772

3✔
773
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
774
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
775

3✔
776
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
777
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
778
                if err != nil {
3✔
779
                        return err
×
780
                }
×
781

782
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
783

3✔
784
                return nil
3✔
785
        }
786

787
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
788
        if err != nil {
3✔
789
                return nil, err
×
790
        }
×
791

792
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
793
                DB:                   dbs.ChanStateDB,
3✔
794
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
795
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
796
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
797
                LocalChannelClose: func(pubKey []byte,
3✔
798
                        request *htlcswitch.ChanClose) {
6✔
799

3✔
800
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
801
                        if err != nil {
3✔
802
                                srvrLog.Errorf("unable to close channel, peer"+
×
803
                                        " with %v id can't be found: %v",
×
804
                                        pubKey, err,
×
805
                                )
×
806
                                return
×
807
                        }
×
808

809
                        peer.HandleLocalCloseChanReqs(request)
3✔
810
                },
811
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
812
                SwitchPackager:         channeldb.NewSwitchPackager(),
813
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
814
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
815
                Notifier:               s.cc.ChainNotifier,
816
                HtlcNotifier:           s.htlcNotifier,
817
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
818
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
819
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
820
                AllowCircularRoute:     cfg.AllowCircularRoute,
821
                RejectHTLC:             cfg.RejectHTLC,
822
                Clock:                  clock.NewDefaultClock(),
823
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
824
                MaxFeeExposure:         thresholdMSats,
825
                SignAliasUpdate:        s.signAliasUpdate,
826
                IsAlias:                aliasmgr.IsAlias,
827
        }, uint32(currentHeight))
828
        if err != nil {
3✔
829
                return nil, err
×
830
        }
×
831
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
832
                &htlcswitch.InterceptableSwitchConfig{
3✔
833
                        Switch:             s.htlcSwitch,
3✔
834
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
835
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
836
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
837
                        Notifier:           s.cc.ChainNotifier,
3✔
838
                },
3✔
839
        )
3✔
840
        if err != nil {
3✔
841
                return nil, err
×
842
        }
×
843

844
        s.witnessBeacon = newPreimageBeacon(
3✔
845
                dbs.ChanStateDB.NewWitnessCache(),
3✔
846
                s.interceptableSwitch.ForwardPacket,
3✔
847
        )
3✔
848

3✔
849
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
850
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
851
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
852
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
853
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
854
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
855
                MessageSigner:            s.nodeSigner,
3✔
856
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
857
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
858
                DB:                       s.chanStateDB,
3✔
859
                Graph:                    dbs.GraphDB,
3✔
860
        }
3✔
861

3✔
862
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
863
        if err != nil {
3✔
864
                return nil, err
×
865
        }
×
866
        s.chanStatusMgr = chanStatusMgr
3✔
867

3✔
868
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
869
        // port forwarding for users behind a NAT.
3✔
870
        if cfg.NAT {
3✔
871
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
872

×
873
                discoveryTimeout := time.Duration(10 * time.Second)
×
874

×
875
                ctx, cancel := context.WithTimeout(
×
876
                        context.Background(), discoveryTimeout,
×
877
                )
×
878
                defer cancel()
×
879
                upnp, err := nat.DiscoverUPnP(ctx)
×
880
                if err == nil {
×
881
                        s.natTraversal = upnp
×
882
                } else {
×
883
                        // If we were not able to discover a UPnP enabled device
×
884
                        // on the local network, we'll fall back to attempting
×
885
                        // to discover a NAT-PMP enabled device.
×
886
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
887
                                "device on the local network: %v", err)
×
888

×
889
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
890
                                "enabled device")
×
891

×
892
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
893
                        if err != nil {
×
894
                                err := fmt.Errorf("unable to discover a "+
×
895
                                        "NAT-PMP enabled device on the local "+
×
896
                                        "network: %v", err)
×
897
                                srvrLog.Error(err)
×
898
                                return nil, err
×
899
                        }
×
900

901
                        s.natTraversal = pmp
×
902
                }
903
        }
904

905
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
3✔
906
        // Set the self node which represents our node in the graph.
3✔
907
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
3✔
908
        if err != nil {
3✔
909
                return nil, err
×
910
        }
×
911

912
        // The router will get access to the payment ID sequencer, such that it
913
        // can generate unique payment IDs.
914
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
915
        if err != nil {
3✔
916
                return nil, err
×
917
        }
×
918

919
        // Instantiate mission control with config from the sub server.
920
        //
921
        // TODO(joostjager): When we are further in the process of moving to sub
922
        // servers, the mission control instance itself can be moved there too.
923
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
924

3✔
925
        // We only initialize a probability estimator if there's no custom one.
3✔
926
        var estimator routing.Estimator
3✔
927
        if cfg.Estimator != nil {
3✔
928
                estimator = cfg.Estimator
×
929
        } else {
3✔
930
                switch routingConfig.ProbabilityEstimatorType {
3✔
931
                case routing.AprioriEstimatorName:
3✔
932
                        aCfg := routingConfig.AprioriConfig
3✔
933
                        aprioriConfig := routing.AprioriConfig{
3✔
934
                                AprioriHopProbability: aCfg.HopProbability,
3✔
935
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
936
                                AprioriWeight:         aCfg.Weight,
3✔
937
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
938
                        }
3✔
939

3✔
940
                        estimator, err = routing.NewAprioriEstimator(
3✔
941
                                aprioriConfig,
3✔
942
                        )
3✔
943
                        if err != nil {
3✔
944
                                return nil, err
×
945
                        }
×
946

947
                case routing.BimodalEstimatorName:
×
948
                        bCfg := routingConfig.BimodalConfig
×
949
                        bimodalConfig := routing.BimodalConfig{
×
950
                                BimodalNodeWeight: bCfg.NodeWeight,
×
951
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
952
                                        bCfg.Scale,
×
953
                                ),
×
954
                                BimodalDecayTime: bCfg.DecayTime,
×
955
                        }
×
956

×
957
                        estimator, err = routing.NewBimodalEstimator(
×
958
                                bimodalConfig,
×
959
                        )
×
960
                        if err != nil {
×
961
                                return nil, err
×
962
                        }
×
963

964
                default:
×
965
                        return nil, fmt.Errorf("unknown estimator type %v",
×
966
                                routingConfig.ProbabilityEstimatorType)
×
967
                }
968
        }
969

970
        mcCfg := &routing.MissionControlConfig{
3✔
971
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
972
                Estimator:               estimator,
3✔
973
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
974
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
975
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
976
        }
3✔
977

3✔
978
        s.missionController, err = routing.NewMissionController(
3✔
979
                dbs.ChanStateDB, nodePubKey, mcCfg,
3✔
980
        )
3✔
981
        if err != nil {
3✔
982
                return nil, fmt.Errorf("can't create mission control "+
×
983
                        "manager: %w", err)
×
984
        }
×
985
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
986
                routing.DefaultMissionControlNamespace,
3✔
987
        )
3✔
988
        if err != nil {
3✔
989
                return nil, fmt.Errorf("can't create mission control in the "+
×
990
                        "default namespace: %w", err)
×
991
        }
×
992

993
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
994
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
995
                int64(routingConfig.AttemptCost),
3✔
996
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
997
                routingConfig.MinRouteProbability)
3✔
998

3✔
999
        pathFindingConfig := routing.PathFindingConfig{
3✔
1000
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1001
                        routingConfig.AttemptCost,
3✔
1002
                ),
3✔
1003
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1004
                MinProbability: routingConfig.MinRouteProbability,
3✔
1005
        }
3✔
1006

3✔
1007
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1008
        if err != nil {
3✔
1009
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1010
        }
×
1011
        paymentSessionSource := &routing.SessionSource{
3✔
1012
                GraphSessionFactory: dbs.GraphDB,
3✔
1013
                SourceNode:          sourceNode,
3✔
1014
                MissionControl:      s.defaultMC,
3✔
1015
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1016
                PathFindingConfig:   pathFindingConfig,
3✔
1017
        }
3✔
1018

3✔
1019
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
3✔
1020

3✔
1021
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1022
                cfg.Routing.StrictZombiePruning
3✔
1023

3✔
1024
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1025
                SelfNode:            nodePubKey,
3✔
1026
                Graph:               dbs.GraphDB,
3✔
1027
                Chain:               cc.ChainIO,
3✔
1028
                ChainView:           cc.ChainView,
3✔
1029
                Notifier:            cc.ChainNotifier,
3✔
1030
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1031
                GraphPruneInterval:  time.Hour,
3✔
1032
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1033
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1034
                StrictZombiePruning: strictPruning,
3✔
1035
                IsAlias:             aliasmgr.IsAlias,
3✔
1036
        })
3✔
1037
        if err != nil {
3✔
1038
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1039
        }
×
1040

1041
        s.chanRouter, err = routing.New(routing.Config{
3✔
1042
                SelfNode:           nodePubKey,
3✔
1043
                RoutingGraph:       dbs.GraphDB,
3✔
1044
                Chain:              cc.ChainIO,
3✔
1045
                Payer:              s.htlcSwitch,
3✔
1046
                Control:            s.controlTower,
3✔
1047
                MissionControl:     s.defaultMC,
3✔
1048
                SessionSource:      paymentSessionSource,
3✔
1049
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1050
                NextPaymentID:      sequencer.NextID,
3✔
1051
                PathFindingConfig:  pathFindingConfig,
3✔
1052
                Clock:              clock.NewDefaultClock(),
3✔
1053
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1054
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1055
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1056
        })
3✔
1057
        if err != nil {
3✔
1058
                return nil, fmt.Errorf("can't create router: %w", err)
×
1059
        }
×
1060

1061
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1062
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1063
        if err != nil {
3✔
1064
                return nil, err
×
1065
        }
×
1066
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1067
        if err != nil {
3✔
1068
                return nil, err
×
1069
        }
×
1070

1071
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1072

3✔
1073
        s.authGossiper = discovery.New(discovery.Config{
3✔
1074
                Graph:                 s.graphBuilder,
3✔
1075
                ChainIO:               s.cc.ChainIO,
3✔
1076
                Notifier:              s.cc.ChainNotifier,
3✔
1077
                ChainParams:           s.cfg.ActiveNetParams.Params,
3✔
1078
                Broadcast:             s.BroadcastMessage,
3✔
1079
                ChanSeries:            chanSeries,
3✔
1080
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1081
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1082
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1083
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
3✔
1084
                        error) {
3✔
1085

×
1086
                        return s.genNodeAnnouncement(nil)
×
1087
                },
×
1088
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1089
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1090
                RetransmitTicker:        ticker.New(time.Minute * 30),
1091
                RebroadcastInterval:     time.Hour * 24,
1092
                WaitingProofStore:       waitingProofStore,
1093
                MessageStore:            gossipMessageStore,
1094
                AnnSigner:               s.nodeSigner,
1095
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1096
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1097
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1098
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1099
                MinimumBatchSize:        10,
1100
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1101
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1102
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1103
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1104
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1105
                IsAlias:                 aliasmgr.IsAlias,
1106
                SignAliasUpdate:         s.signAliasUpdate,
1107
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1108
                GetAlias:                s.aliasMgr.GetPeerAlias,
1109
                FindChannel:             s.findChannel,
1110
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1111
                ScidCloser:              scidCloserMan,
1112
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1113
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1114
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1115
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1116
                BanThreshold:            cfg.Gossip.BanThreshold,
1117
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1118
        }, nodeKeyDesc)
1119

1120
        accessCfg := &accessManConfig{
3✔
1121
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1122
                        error) {
6✔
1123

3✔
1124
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1125
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1126
                                genesisHash[:],
3✔
1127
                        )
3✔
1128
                },
3✔
1129
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1130
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1131
        }
1132

1133
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1134
        if err != nil {
3✔
1135
                return nil, err
×
1136
        }
×
1137

1138
        s.peerAccessMan = peerAccessMan
3✔
1139

3✔
1140
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1141
        //nolint:ll
3✔
1142
        s.localChanMgr = &localchans.Manager{
3✔
1143
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1144
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1145
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1146
                        cb func(*models.ChannelEdgeInfo,
3✔
1147
                                *models.ChannelEdgePolicy) error,
3✔
1148
                        reset func()) error {
6✔
1149

3✔
1150
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1151
                                func(c *models.ChannelEdgeInfo,
3✔
1152
                                        e *models.ChannelEdgePolicy,
3✔
1153
                                        _ *models.ChannelEdgePolicy) error {
6✔
1154

3✔
1155
                                        // NOTE: The invoked callback here may
3✔
1156
                                        // receive a nil channel policy.
3✔
1157
                                        return cb(c, e)
3✔
1158
                                }, reset,
3✔
1159
                        )
1160
                },
1161
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1162
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1163
                FetchChannel:              s.chanStateDB.FetchChannel,
1164
                AddEdge: func(ctx context.Context,
1165
                        edge *models.ChannelEdgeInfo) error {
×
1166

×
1167
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1168
                },
×
1169
        }
1170

1171
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1172
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1173
        )
3✔
1174
        if err != nil {
3✔
1175
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1176
                return nil, err
×
1177
        }
×
1178

1179
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1180
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1181
        )
3✔
1182
        if err != nil {
3✔
1183
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1184
                return nil, err
×
1185
        }
×
1186

1187
        aggregator := sweep.NewBudgetAggregator(
3✔
1188
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1189
                s.implCfg.AuxSweeper,
3✔
1190
        )
3✔
1191

3✔
1192
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1193
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1194
                Wallet:     cc.Wallet,
3✔
1195
                Estimator:  cc.FeeEstimator,
3✔
1196
                Notifier:   cc.ChainNotifier,
3✔
1197
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1198
        })
3✔
1199

3✔
1200
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1201
                FeeEstimator: cc.FeeEstimator,
3✔
1202
                GenSweepScript: newSweepPkScriptGen(
3✔
1203
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1204
                ),
3✔
1205
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1206
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1207
                Mempool:              cc.MempoolNotifier,
3✔
1208
                Notifier:             cc.ChainNotifier,
3✔
1209
                Store:                sweeperStore,
3✔
1210
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1211
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1212
                Aggregator:           aggregator,
3✔
1213
                Publisher:            s.txPublisher,
3✔
1214
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1215
        })
3✔
1216

3✔
1217
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1218
                ChainIO:             cc.ChainIO,
3✔
1219
                ConfDepth:           1,
3✔
1220
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1221
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1222
                Notifier:            cc.ChainNotifier,
3✔
1223
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1224
                Store:               utxnStore,
3✔
1225
                SweepInput:          s.sweeper.SweepInput,
3✔
1226
                Budget:              s.cfg.Sweeper.Budget,
3✔
1227
        })
3✔
1228

3✔
1229
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1230
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1231
                closureType contractcourt.ChannelCloseType) {
6✔
1232
                // TODO(conner): Properly respect the update and error channels
3✔
1233
                // returned by CloseLink.
3✔
1234

3✔
1235
                // Instruct the switch to close the channel.  Provide no close out
3✔
1236
                // delivery script or target fee per kw because user input is not
3✔
1237
                // available when the remote peer closes the channel.
3✔
1238
                s.htlcSwitch.CloseLink(
3✔
1239
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1240
                )
3✔
1241
        }
3✔
1242

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

3✔
1247
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1248
                &contractcourt.BreachConfig{
3✔
1249
                        CloseLink: closeLink,
3✔
1250
                        DB:        s.chanStateDB,
3✔
1251
                        Estimator: s.cc.FeeEstimator,
3✔
1252
                        GenSweepScript: newSweepPkScriptGen(
3✔
1253
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1254
                        ),
3✔
1255
                        Notifier:           cc.ChainNotifier,
3✔
1256
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1257
                        ContractBreaches:   contractBreaches,
3✔
1258
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1259
                        Store: contractcourt.NewRetributionStore(
3✔
1260
                                dbs.ChanStateDB,
3✔
1261
                        ),
3✔
1262
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1263
                },
3✔
1264
        )
3✔
1265

3✔
1266
        //nolint:ll
3✔
1267
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1268
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1269
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1270
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1271
                NewSweepAddr: func() ([]byte, error) {
3✔
1272
                        addr, err := newSweepPkScriptGen(
×
1273
                                cc.Wallet, netParams,
×
1274
                        )().Unpack()
×
1275
                        if err != nil {
×
1276
                                return nil, err
×
1277
                        }
×
1278

1279
                        return addr.DeliveryAddress, nil
×
1280
                },
1281
                PublishTx: cc.Wallet.PublishTransaction,
1282
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1283
                        for _, msg := range msgs {
6✔
1284
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1285
                                if err != nil {
3✔
1286
                                        return err
×
1287
                                }
×
1288
                        }
1289
                        return nil
3✔
1290
                },
1291
                IncubateOutputs: func(chanPoint wire.OutPoint,
1292
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1293
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1294
                        broadcastHeight uint32,
1295
                        deadlineHeight fn.Option[int32]) error {
3✔
1296

3✔
1297
                        return s.utxoNursery.IncubateOutputs(
3✔
1298
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1299
                                broadcastHeight, deadlineHeight,
3✔
1300
                        )
3✔
1301
                },
3✔
1302
                PreimageDB:   s.witnessBeacon,
1303
                Notifier:     cc.ChainNotifier,
1304
                Mempool:      cc.MempoolNotifier,
1305
                Signer:       cc.Wallet.Cfg.Signer,
1306
                FeeEstimator: cc.FeeEstimator,
1307
                ChainIO:      cc.ChainIO,
1308
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1309
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1310
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1311
                        return nil
3✔
1312
                },
3✔
1313
                IsOurAddress: cc.Wallet.IsOurAddress,
1314
                ContractBreach: func(chanPoint wire.OutPoint,
1315
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1316

3✔
1317
                        // processACK will handle the BreachArbitrator ACKing
3✔
1318
                        // the event.
3✔
1319
                        finalErr := make(chan error, 1)
3✔
1320
                        processACK := func(brarErr error) {
6✔
1321
                                if brarErr != nil {
3✔
1322
                                        finalErr <- brarErr
×
1323
                                        return
×
1324
                                }
×
1325

1326
                                // If the BreachArbitrator successfully handled
1327
                                // the event, we can signal that the handoff
1328
                                // was successful.
1329
                                finalErr <- nil
3✔
1330
                        }
1331

1332
                        event := &contractcourt.ContractBreachEvent{
3✔
1333
                                ChanPoint:         chanPoint,
3✔
1334
                                ProcessACK:        processACK,
3✔
1335
                                BreachRetribution: breachRet,
3✔
1336
                        }
3✔
1337

3✔
1338
                        // Send the contract breach event to the
3✔
1339
                        // BreachArbitrator.
3✔
1340
                        select {
3✔
1341
                        case contractBreaches <- event:
3✔
1342
                        case <-s.quit:
×
1343
                                return ErrServerShuttingDown
×
1344
                        }
1345

1346
                        // We'll wait for a final error to be available from
1347
                        // the BreachArbitrator.
1348
                        select {
3✔
1349
                        case err := <-finalErr:
3✔
1350
                                return err
3✔
1351
                        case <-s.quit:
×
1352
                                return ErrServerShuttingDown
×
1353
                        }
1354
                },
1355
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1356
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1357
                },
3✔
1358
                Sweeper:                       s.sweeper,
1359
                Registry:                      s.invoices,
1360
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1361
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1362
                OnionProcessor:                s.sphinx,
1363
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1364
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1365
                Clock:                         clock.NewDefaultClock(),
1366
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1367
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1368
                HtlcNotifier:                  s.htlcNotifier,
1369
                Budget:                        *s.cfg.Sweeper.Budget,
1370

1371
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1372
                QueryIncomingCircuit: func(
1373
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1374

3✔
1375
                        // Get the circuit map.
3✔
1376
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1377

3✔
1378
                        // Lookup the outgoing circuit.
3✔
1379
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1380
                        if pc == nil {
5✔
1381
                                return nil
2✔
1382
                        }
2✔
1383

1384
                        return &pc.Incoming
3✔
1385
                },
1386
                AuxLeafStore: implCfg.AuxLeafStore,
1387
                AuxSigner:    implCfg.AuxSigner,
1388
                AuxResolver:  implCfg.AuxContractResolver,
1389
        }, dbs.ChanStateDB)
1390

1391
        // Select the configuration and funding parameters for Bitcoin.
1392
        chainCfg := cfg.Bitcoin
3✔
1393
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1394
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1395

3✔
1396
        var chanIDSeed [32]byte
3✔
1397
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1398
                return nil, err
×
1399
        }
×
1400

1401
        // Wrap the DeleteChannelEdges method so that the funding manager can
1402
        // use it without depending on several layers of indirection.
1403
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1404
                *models.ChannelEdgePolicy, error) {
6✔
1405

3✔
1406
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1407
                        scid.ToUint64(),
3✔
1408
                )
3✔
1409
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1410
                        // This is unlikely but there is a slim chance of this
×
1411
                        // being hit if lnd was killed via SIGKILL and the
×
1412
                        // funding manager was stepping through the delete
×
1413
                        // alias edge logic.
×
1414
                        return nil, nil
×
1415
                } else if err != nil {
3✔
1416
                        return nil, err
×
1417
                }
×
1418

1419
                // Grab our key to find our policy.
1420
                var ourKey [33]byte
3✔
1421
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1422

3✔
1423
                var ourPolicy *models.ChannelEdgePolicy
3✔
1424
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1425
                        ourPolicy = e1
3✔
1426
                } else {
6✔
1427
                        ourPolicy = e2
3✔
1428
                }
3✔
1429

1430
                if ourPolicy == nil {
3✔
1431
                        // Something is wrong, so return an error.
×
1432
                        return nil, fmt.Errorf("we don't have an edge")
×
1433
                }
×
1434

1435
                err = s.graphDB.DeleteChannelEdges(
3✔
1436
                        false, false, scid.ToUint64(),
3✔
1437
                )
3✔
1438
                return ourPolicy, err
3✔
1439
        }
1440

1441
        // For the reservationTimeout and the zombieSweeperInterval different
1442
        // values are set in case we are in a dev environment so enhance test
1443
        // capacilities.
1444
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1445
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1446

3✔
1447
        // Get the development config for funding manager. If we are not in
3✔
1448
        // development mode, this would be nil.
3✔
1449
        var devCfg *funding.DevConfig
3✔
1450
        if lncfg.IsDevBuild() {
6✔
1451
                devCfg = &funding.DevConfig{
3✔
1452
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1453
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1454
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1455
                }
3✔
1456

3✔
1457
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1458
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1459

3✔
1460
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1461
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1462
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1463
        }
3✔
1464

1465
        // Attempt to parse the provided upfront-shutdown address (if any).
1466
        script, err := chancloser.ParseUpfrontShutdownAddress(
3✔
1467
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
3✔
1468
        )
3✔
1469
        if err != nil {
3✔
1470
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1471
                        err)
×
1472
        }
×
1473

1474
        //nolint:ll
1475
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1476
                Dev:                devCfg,
3✔
1477
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1478
                IDKey:              nodeKeyDesc.PubKey,
3✔
1479
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1480
                Wallet:             cc.Wallet,
3✔
1481
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1482
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1483
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1484
                },
3✔
1485
                Notifier:     cc.ChainNotifier,
1486
                ChannelDB:    s.chanStateDB,
1487
                FeeEstimator: cc.FeeEstimator,
1488
                SignMessage:  cc.MsgSigner.SignMessage,
1489
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1490
                        error) {
3✔
1491

3✔
1492
                        return s.genNodeAnnouncement(nil)
3✔
1493
                },
3✔
1494
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1495
                NotifyWhenOnline:     s.NotifyWhenOnline,
1496
                TempChanIDSeed:       chanIDSeed,
1497
                FindChannel:          s.findChannel,
1498
                DefaultRoutingPolicy: cc.RoutingPolicy,
1499
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1500
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1501
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1502
                        // For large channels we increase the number
3✔
1503
                        // of confirmations we require for the
3✔
1504
                        // channel to be considered open. As it is
3✔
1505
                        // always the responder that gets to choose
3✔
1506
                        // value, the pushAmt is value being pushed
3✔
1507
                        // to us. This means we have more to lose
3✔
1508
                        // in the case this gets re-orged out, and
3✔
1509
                        // we will require more confirmations before
3✔
1510
                        // we consider it open.
3✔
1511

3✔
1512
                        // In case the user has explicitly specified
3✔
1513
                        // a default value for the number of
3✔
1514
                        // confirmations, we use it.
3✔
1515
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1516
                        if defaultConf != 0 {
6✔
1517
                                return defaultConf
3✔
1518
                        }
3✔
1519

1520
                        minConf := uint64(3)
×
1521
                        maxConf := uint64(6)
×
1522

×
1523
                        // If this is a wumbo channel, then we'll require the
×
1524
                        // max amount of confirmations.
×
1525
                        if chanAmt > MaxFundingAmount {
×
1526
                                return uint16(maxConf)
×
1527
                        }
×
1528

1529
                        // If not we return a value scaled linearly
1530
                        // between 3 and 6, depending on channel size.
1531
                        // TODO(halseth): Use 1 as minimum?
1532
                        maxChannelSize := uint64(
×
1533
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1534
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1535
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1536
                        if conf < minConf {
×
1537
                                conf = minConf
×
1538
                        }
×
1539
                        if conf > maxConf {
×
1540
                                conf = maxConf
×
1541
                        }
×
1542
                        return uint16(conf)
×
1543
                },
1544
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1545
                        // We scale the remote CSV delay (the time the
3✔
1546
                        // remote have to claim funds in case of a unilateral
3✔
1547
                        // close) linearly from minRemoteDelay blocks
3✔
1548
                        // for small channels, to maxRemoteDelay blocks
3✔
1549
                        // for channels of size MaxFundingAmount.
3✔
1550

3✔
1551
                        // In case the user has explicitly specified
3✔
1552
                        // a default value for the remote delay, we
3✔
1553
                        // use it.
3✔
1554
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1555
                        if defaultDelay > 0 {
6✔
1556
                                return defaultDelay
3✔
1557
                        }
3✔
1558

1559
                        // If this is a wumbo channel, then we'll require the
1560
                        // max value.
1561
                        if chanAmt > MaxFundingAmount {
×
1562
                                return maxRemoteDelay
×
1563
                        }
×
1564

1565
                        // If not we scale according to channel size.
1566
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1567
                                chanAmt / MaxFundingAmount)
×
1568
                        if delay < minRemoteDelay {
×
1569
                                delay = minRemoteDelay
×
1570
                        }
×
1571
                        if delay > maxRemoteDelay {
×
1572
                                delay = maxRemoteDelay
×
1573
                        }
×
1574
                        return delay
×
1575
                },
1576
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1577
                        peerKey *btcec.PublicKey) error {
3✔
1578

3✔
1579
                        // First, we'll mark this new peer as a persistent peer
3✔
1580
                        // for re-connection purposes. If the peer is not yet
3✔
1581
                        // tracked or the user hasn't requested it to be perm,
3✔
1582
                        // we'll set false to prevent the server from continuing
3✔
1583
                        // to connect to this peer even if the number of
3✔
1584
                        // channels with this peer is zero.
3✔
1585
                        s.mu.Lock()
3✔
1586
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1587
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1588
                                s.persistentPeers[pubStr] = false
3✔
1589
                        }
3✔
1590
                        s.mu.Unlock()
3✔
1591

3✔
1592
                        // With that taken care of, we'll send this channel to
3✔
1593
                        // the chain arb so it can react to on-chain events.
3✔
1594
                        return s.chainArb.WatchNewChannel(channel)
3✔
1595
                },
1596
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1597
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1598
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1599
                },
3✔
1600
                RequiredRemoteChanReserve: func(chanAmt,
1601
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1602

3✔
1603
                        // By default, we'll require the remote peer to maintain
3✔
1604
                        // at least 1% of the total channel capacity at all
3✔
1605
                        // times. If this value ends up dipping below the dust
3✔
1606
                        // limit, then we'll use the dust limit itself as the
3✔
1607
                        // reserve as required by BOLT #2.
3✔
1608
                        reserve := chanAmt / 100
3✔
1609
                        if reserve < dustLimit {
6✔
1610
                                reserve = dustLimit
3✔
1611
                        }
3✔
1612

1613
                        return reserve
3✔
1614
                },
1615
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1616
                        // By default, we'll allow the remote peer to fully
3✔
1617
                        // utilize the full bandwidth of the channel, minus our
3✔
1618
                        // required reserve.
3✔
1619
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1620
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1621
                },
3✔
1622
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1623
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1624
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1625
                        }
3✔
1626

1627
                        // By default, we'll permit them to utilize the full
1628
                        // channel bandwidth.
1629
                        return uint16(input.MaxHTLCNumber / 2)
×
1630
                },
1631
                ZombieSweeperInterval:         zombieSweeperInterval,
1632
                ReservationTimeout:            reservationTimeout,
1633
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1634
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1635
                MaxPendingChannels:            cfg.MaxPendingChannels,
1636
                RejectPush:                    cfg.RejectPush,
1637
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1638
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1639
                OpenChannelPredicate:          chanPredicate,
1640
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1641
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1642
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1643
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1644
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1645
                DeleteAliasEdge:      deleteAliasEdge,
1646
                AliasManager:         s.aliasMgr,
1647
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1648
                AuxFundingController: implCfg.AuxFundingController,
1649
                AuxSigner:            implCfg.AuxSigner,
1650
                AuxResolver:          implCfg.AuxContractResolver,
1651
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1652
                ShutdownScript:       peer.ChooseAddr(script),
1653
        })
1654
        if err != nil {
3✔
1655
                return nil, err
×
1656
        }
×
1657

1658
        // Next, we'll assemble the sub-system that will maintain an on-disk
1659
        // static backup of the latest channel state.
1660
        chanNotifier := &channelNotifier{
3✔
1661
                chanNotifier: s.channelNotifier,
3✔
1662
                addrs:        s.addrSource,
3✔
1663
        }
3✔
1664
        backupFile := chanbackup.NewMultiFile(
3✔
1665
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1666
        )
3✔
1667
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1668
                ctx, s.chanStateDB, s.addrSource,
3✔
1669
        )
3✔
1670
        if err != nil {
3✔
1671
                return nil, err
×
1672
        }
×
1673
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1674
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1675
        )
3✔
1676
        if err != nil {
3✔
1677
                return nil, err
×
1678
        }
×
1679

1680
        // Assemble a peer notifier which will provide clients with subscriptions
1681
        // to peer online and offline events.
1682
        s.peerNotifier = peernotifier.New()
3✔
1683

3✔
1684
        // Create a channel event store which monitors all open channels.
3✔
1685
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1686
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1687
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1688
                },
3✔
1689
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1690
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1691
                },
3✔
1692
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1693
                Clock:           clock.NewDefaultClock(),
1694
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1695
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1696
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1697
        })
1698

1699
        if cfg.WtClient.Active {
6✔
1700
                policy := wtpolicy.DefaultPolicy()
3✔
1701
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1702

3✔
1703
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1704
                // protocol operations on sat/kw.
3✔
1705
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1706
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1707
                )
3✔
1708

3✔
1709
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1710

3✔
1711
                if err := policy.Validate(); err != nil {
3✔
1712
                        return nil, err
×
1713
                }
×
1714

1715
                // authDial is the wrapper around the btrontide.Dial for the
1716
                // watchtower.
1717
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1718
                        netAddr *lnwire.NetAddress,
3✔
1719
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1720

3✔
1721
                        return brontide.Dial(
3✔
1722
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1723
                        )
3✔
1724
                }
3✔
1725

1726
                // buildBreachRetribution is a call-back that can be used to
1727
                // query the BreachRetribution info and channel type given a
1728
                // channel ID and commitment height.
1729
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1730
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1731
                        channeldb.ChannelType, error) {
6✔
1732

3✔
1733
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1734
                                nil, chanID,
3✔
1735
                        )
3✔
1736
                        if err != nil {
3✔
1737
                                return nil, 0, err
×
1738
                        }
×
1739

1740
                        br, err := lnwallet.NewBreachRetribution(
3✔
1741
                                channel, commitHeight, 0, nil,
3✔
1742
                                implCfg.AuxLeafStore,
3✔
1743
                                implCfg.AuxContractResolver,
3✔
1744
                        )
3✔
1745
                        if err != nil {
3✔
1746
                                return nil, 0, err
×
1747
                        }
×
1748

1749
                        return br, channel.ChanType, nil
3✔
1750
                }
1751

1752
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1753

3✔
1754
                // Copy the policy for legacy channels and set the blob flag
3✔
1755
                // signalling support for anchor channels.
3✔
1756
                anchorPolicy := policy
3✔
1757
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1758

3✔
1759
                // Copy the policy for legacy channels and set the blob flag
3✔
1760
                // signalling support for taproot channels.
3✔
1761
                taprootPolicy := policy
3✔
1762
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1763
                        blob.FlagTaprootChannel,
3✔
1764
                )
3✔
1765

3✔
1766
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1767
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1768
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1769
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1770
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1771
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1772
                                error) {
6✔
1773

3✔
1774
                                return s.channelNotifier.
3✔
1775
                                        SubscribeChannelEvents()
3✔
1776
                        },
3✔
1777
                        Signer: cc.Wallet.Cfg.Signer,
1778
                        NewAddress: func() ([]byte, error) {
3✔
1779
                                addr, err := newSweepPkScriptGen(
3✔
1780
                                        cc.Wallet, netParams,
3✔
1781
                                )().Unpack()
3✔
1782
                                if err != nil {
3✔
1783
                                        return nil, err
×
1784
                                }
×
1785

1786
                                return addr.DeliveryAddress, nil
3✔
1787
                        },
1788
                        SecretKeyRing:      s.cc.KeyRing,
1789
                        Dial:               cfg.net.Dial,
1790
                        AuthDial:           authDial,
1791
                        DB:                 dbs.TowerClientDB,
1792
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1793
                        MinBackoff:         10 * time.Second,
1794
                        MaxBackoff:         5 * time.Minute,
1795
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1796
                }, policy, anchorPolicy, taprootPolicy)
1797
                if err != nil {
3✔
1798
                        return nil, err
×
1799
                }
×
1800
        }
1801

1802
        if len(cfg.ExternalHosts) != 0 {
3✔
1803
                advertisedIPs := make(map[string]struct{})
×
1804
                for _, addr := range s.currentNodeAnn.Addresses {
×
1805
                        advertisedIPs[addr.String()] = struct{}{}
×
1806
                }
×
1807

1808
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1809
                        Hosts:         cfg.ExternalHosts,
×
1810
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1811
                        LookupHost: func(host string) (net.Addr, error) {
×
1812
                                return lncfg.ParseAddressString(
×
1813
                                        host, strconv.Itoa(defaultPeerPort),
×
1814
                                        cfg.net.ResolveTCPAddr,
×
1815
                                )
×
1816
                        },
×
1817
                        AdvertisedIPs: advertisedIPs,
1818
                        AnnounceNewIPs: netann.IPAnnouncer(
1819
                                func(modifier ...netann.NodeAnnModifier) (
1820
                                        lnwire.NodeAnnouncement1, error) {
×
1821

×
1822
                                        return s.genNodeAnnouncement(
×
1823
                                                nil, modifier...,
×
1824
                                        )
×
1825
                                }),
×
1826
                })
1827
        }
1828

1829
        // Create liveness monitor.
1830
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1831

3✔
1832
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1833
        for i, listenAddr := range listenAddrs {
6✔
1834
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1835
                // doesn't need to call the general lndResolveTCP function
3✔
1836
                // since we are resolving a local address.
3✔
1837

3✔
1838
                // RESOLVE: We are actually partially accepting inbound
3✔
1839
                // connection requests when we call NewListener.
3✔
1840
                listeners[i], err = brontide.NewListener(
3✔
1841
                        nodeKeyECDH, listenAddr.String(),
3✔
1842
                        // TODO(yy): remove this check and unify the inbound
3✔
1843
                        // connection check inside `InboundPeerConnected`.
3✔
1844
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1845
                )
3✔
1846
                if err != nil {
3✔
1847
                        return nil, err
×
1848
                }
×
1849
        }
1850

1851
        // Create the connection manager which will be responsible for
1852
        // maintaining persistent outbound connections and also accepting new
1853
        // incoming connections
1854
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1855
                Listeners:      listeners,
3✔
1856
                OnAccept:       s.InboundPeerConnected,
3✔
1857
                RetryDuration:  time.Second * 5,
3✔
1858
                TargetOutbound: 100,
3✔
1859
                Dial: noiseDial(
3✔
1860
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1861
                ),
3✔
1862
                OnConnection: s.OutboundPeerConnected,
3✔
1863
        })
3✔
1864
        if err != nil {
3✔
1865
                return nil, err
×
1866
        }
×
1867
        s.connMgr = cmgr
3✔
1868

3✔
1869
        // Finally, register the subsystems in blockbeat.
3✔
1870
        s.registerBlockConsumers()
3✔
1871

3✔
1872
        return s, nil
3✔
1873
}
1874

1875
// UpdateRoutingConfig is a callback function to update the routing config
1876
// values in the main cfg.
1877
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1878
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1879

3✔
1880
        switch c := cfg.Estimator.Config().(type) {
3✔
1881
        case routing.AprioriConfig:
3✔
1882
                routerCfg.ProbabilityEstimatorType =
3✔
1883
                        routing.AprioriEstimatorName
3✔
1884

3✔
1885
                targetCfg := routerCfg.AprioriConfig
3✔
1886
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1887
                targetCfg.Weight = c.AprioriWeight
3✔
1888
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1889
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1890

1891
        case routing.BimodalConfig:
3✔
1892
                routerCfg.ProbabilityEstimatorType =
3✔
1893
                        routing.BimodalEstimatorName
3✔
1894

3✔
1895
                targetCfg := routerCfg.BimodalConfig
3✔
1896
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1897
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1898
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1899
        }
1900

1901
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1902
}
1903

1904
// registerBlockConsumers registers the subsystems that consume block events.
1905
// By calling `RegisterQueue`, a list of subsystems are registered in the
1906
// blockbeat for block notifications. When a new block arrives, the subsystems
1907
// in the same queue are notified sequentially, and different queues are
1908
// notified concurrently.
1909
//
1910
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1911
// a new `RegisterQueue` call.
1912
func (s *server) registerBlockConsumers() {
3✔
1913
        // In this queue, when a new block arrives, it will be received and
3✔
1914
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1915
        consumers := []chainio.Consumer{
3✔
1916
                s.chainArb,
3✔
1917
                s.sweeper,
3✔
1918
                s.txPublisher,
3✔
1919
        }
3✔
1920
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1921
}
3✔
1922

1923
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1924
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1925
// may differ from what is on disk.
1926
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1927
        error) {
3✔
1928

3✔
1929
        data, err := u.DataToSign()
3✔
1930
        if err != nil {
3✔
1931
                return nil, err
×
1932
        }
×
1933

1934
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1935
}
1936

1937
// createLivenessMonitor creates a set of health checks using our configured
1938
// values and uses these checks to create a liveness monitor. Available
1939
// health checks,
1940
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1941
//   - diskCheck
1942
//   - tlsHealthCheck
1943
//   - torController, only created when tor is enabled.
1944
//
1945
// If a health check has been disabled by setting attempts to 0, our monitor
1946
// will not run it.
1947
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1948
        leaderElector cluster.LeaderElector) {
3✔
1949

3✔
1950
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1951
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1952
                srvrLog.Info("Disabling chain backend checks for " +
×
1953
                        "nochainbackend mode")
×
1954

×
1955
                chainBackendAttempts = 0
×
1956
        }
×
1957

1958
        chainHealthCheck := healthcheck.NewObservation(
3✔
1959
                "chain backend",
3✔
1960
                cc.HealthCheck,
3✔
1961
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1962
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1963
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1964
                chainBackendAttempts,
3✔
1965
        )
3✔
1966

3✔
1967
        diskCheck := healthcheck.NewObservation(
3✔
1968
                "disk space",
3✔
1969
                func() error {
3✔
1970
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1971
                                cfg.LndDir,
×
1972
                        )
×
1973
                        if err != nil {
×
1974
                                return err
×
1975
                        }
×
1976

1977
                        // If we have more free space than we require,
1978
                        // we return a nil error.
1979
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1980
                                return nil
×
1981
                        }
×
1982

1983
                        return fmt.Errorf("require: %v free space, got: %v",
×
1984
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1985
                                free)
×
1986
                },
1987
                cfg.HealthChecks.DiskCheck.Interval,
1988
                cfg.HealthChecks.DiskCheck.Timeout,
1989
                cfg.HealthChecks.DiskCheck.Backoff,
1990
                cfg.HealthChecks.DiskCheck.Attempts,
1991
        )
1992

1993
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1994
                "tls",
3✔
1995
                func() error {
3✔
1996
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1997
                                s.cc.KeyRing,
×
1998
                        )
×
1999
                        if err != nil {
×
2000
                                return err
×
2001
                        }
×
2002
                        if expired {
×
2003
                                return fmt.Errorf("TLS certificate is "+
×
2004
                                        "expired as of %v", expTime)
×
2005
                        }
×
2006

2007
                        // If the certificate is not outdated, no error needs
2008
                        // to be returned
2009
                        return nil
×
2010
                },
2011
                cfg.HealthChecks.TLSCheck.Interval,
2012
                cfg.HealthChecks.TLSCheck.Timeout,
2013
                cfg.HealthChecks.TLSCheck.Backoff,
2014
                cfg.HealthChecks.TLSCheck.Attempts,
2015
        )
2016

2017
        checks := []*healthcheck.Observation{
3✔
2018
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2019
        }
3✔
2020

3✔
2021
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2022
        if s.torController != nil {
3✔
2023
                torConnectionCheck := healthcheck.NewObservation(
×
2024
                        "tor connection",
×
2025
                        func() error {
×
2026
                                return healthcheck.CheckTorServiceStatus(
×
2027
                                        s.torController,
×
2028
                                        func() error {
×
2029
                                                return s.createNewHiddenService(
×
2030
                                                        context.TODO(),
×
2031
                                                )
×
2032
                                        },
×
2033
                                )
2034
                        },
2035
                        cfg.HealthChecks.TorConnection.Interval,
2036
                        cfg.HealthChecks.TorConnection.Timeout,
2037
                        cfg.HealthChecks.TorConnection.Backoff,
2038
                        cfg.HealthChecks.TorConnection.Attempts,
2039
                )
2040
                checks = append(checks, torConnectionCheck)
×
2041
        }
2042

2043
        // If remote signing is enabled, add the healthcheck for the remote
2044
        // signing RPC interface.
2045
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2046
                // Because we have two cascading timeouts here, we need to add
3✔
2047
                // some slack to the "outer" one of them in case the "inner"
3✔
2048
                // returns exactly on time.
3✔
2049
                overhead := time.Millisecond * 10
3✔
2050

3✔
2051
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2052
                        "remote signer connection",
3✔
2053
                        rpcwallet.HealthCheck(
3✔
2054
                                s.cfg.RemoteSigner,
3✔
2055

3✔
2056
                                // For the health check we might to be even
3✔
2057
                                // stricter than the initial/normal connect, so
3✔
2058
                                // we use the health check timeout here.
3✔
2059
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2060
                        ),
3✔
2061
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2062
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2063
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2064
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2065
                )
3✔
2066
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2067
        }
3✔
2068

2069
        // If we have a leader elector, we add a health check to ensure we are
2070
        // still the leader. During normal operation, we should always be the
2071
        // leader, but there are circumstances where this may change, such as
2072
        // when we lose network connectivity for long enough expiring out lease.
2073
        if leaderElector != nil {
3✔
2074
                leaderCheck := healthcheck.NewObservation(
×
2075
                        "leader status",
×
2076
                        func() error {
×
2077
                                // Check if we are still the leader. Note that
×
2078
                                // we don't need to use a timeout context here
×
2079
                                // as the healthcheck observer will handle the
×
2080
                                // timeout case for us.
×
2081
                                timeoutCtx, cancel := context.WithTimeout(
×
2082
                                        context.Background(),
×
2083
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2084
                                )
×
2085
                                defer cancel()
×
2086

×
2087
                                leader, err := leaderElector.IsLeader(
×
2088
                                        timeoutCtx,
×
2089
                                )
×
2090
                                if err != nil {
×
2091
                                        return fmt.Errorf("unable to check if "+
×
2092
                                                "still leader: %v", err)
×
2093
                                }
×
2094

2095
                                if !leader {
×
2096
                                        srvrLog.Debug("Not the current leader")
×
2097
                                        return fmt.Errorf("not the current " +
×
2098
                                                "leader")
×
2099
                                }
×
2100

2101
                                return nil
×
2102
                        },
2103
                        cfg.HealthChecks.LeaderCheck.Interval,
2104
                        cfg.HealthChecks.LeaderCheck.Timeout,
2105
                        cfg.HealthChecks.LeaderCheck.Backoff,
2106
                        cfg.HealthChecks.LeaderCheck.Attempts,
2107
                )
2108

2109
                checks = append(checks, leaderCheck)
×
2110
        }
2111

2112
        // If we have not disabled all of our health checks, we create a
2113
        // liveness monitor with our configured checks.
2114
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2115
                &healthcheck.Config{
3✔
2116
                        Checks:   checks,
3✔
2117
                        Shutdown: srvrLog.Criticalf,
3✔
2118
                },
3✔
2119
        )
3✔
2120
}
2121

2122
// Started returns true if the server has been started, and false otherwise.
2123
// NOTE: This function is safe for concurrent access.
2124
func (s *server) Started() bool {
3✔
2125
        return atomic.LoadInt32(&s.active) != 0
3✔
2126
}
3✔
2127

2128
// cleaner is used to aggregate "cleanup" functions during an operation that
2129
// starts several subsystems. In case one of the subsystem fails to start
2130
// and a proper resource cleanup is required, the "run" method achieves this
2131
// by running all these added "cleanup" functions.
2132
type cleaner []func() error
2133

2134
// add is used to add a cleanup function to be called when
2135
// the run function is executed.
2136
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2137
        return append(c, cleanup)
3✔
2138
}
3✔
2139

2140
// run is used to run all the previousely added cleanup functions.
2141
func (c cleaner) run() {
×
2142
        for i := len(c) - 1; i >= 0; i-- {
×
2143
                if err := c[i](); err != nil {
×
2144
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2145
                }
×
2146
        }
2147
}
2148

2149
// Start starts the main daemon server, all requested listeners, and any helper
2150
// goroutines.
2151
// NOTE: This function is safe for concurrent access.
2152
//
2153
//nolint:funlen
2154
func (s *server) Start(ctx context.Context) error {
3✔
2155
        var startErr error
3✔
2156

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

3✔
2162
        s.start.Do(func() {
6✔
2163
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2164
                if err := s.customMessageServer.Start(); err != nil {
3✔
2165
                        startErr = err
×
2166
                        return
×
2167
                }
×
2168

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

2175
                if s.hostAnn != nil {
3✔
2176
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2177
                        if err := s.hostAnn.Start(); err != nil {
×
2178
                                startErr = err
×
2179
                                return
×
2180
                        }
×
2181
                }
2182

2183
                if s.livenessMonitor != nil {
6✔
2184
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2185
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2186
                                startErr = err
×
2187
                                return
×
2188
                        }
×
2189
                }
2190

2191
                // Start the notification server. This is used so channel
2192
                // management goroutines can be notified when a funding
2193
                // transaction reaches a sufficient number of confirmations, or
2194
                // when the input for the funding transaction is spent in an
2195
                // attempt at an uncooperative close by the counterparty.
2196
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2197
                if err := s.sigPool.Start(); err != nil {
3✔
2198
                        startErr = err
×
2199
                        return
×
2200
                }
×
2201

2202
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2203
                if err := s.writePool.Start(); err != nil {
3✔
2204
                        startErr = err
×
2205
                        return
×
2206
                }
×
2207

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

2214
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2215
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2216
                        startErr = err
×
2217
                        return
×
2218
                }
×
2219

2220
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2221
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2222
                        startErr = err
×
2223
                        return
×
2224
                }
×
2225

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

2232
                cleanup = cleanup.add(func() error {
3✔
2233
                        return s.peerNotifier.Stop()
×
2234
                })
×
2235
                if err := s.peerNotifier.Start(); err != nil {
3✔
2236
                        startErr = err
×
2237
                        return
×
2238
                }
×
2239

2240
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2241
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2242
                        startErr = err
×
2243
                        return
×
2244
                }
×
2245

2246
                if s.towerClientMgr != nil {
6✔
2247
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2248
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2249
                                startErr = err
×
2250
                                return
×
2251
                        }
×
2252
                }
2253

2254
                beat, err := s.getStartingBeat()
3✔
2255
                if err != nil {
3✔
2256
                        startErr = err
×
2257
                        return
×
2258
                }
×
2259

2260
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2261
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2262
                        startErr = err
×
2263
                        return
×
2264
                }
×
2265

2266
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2267
                if err := s.sweeper.Start(beat); err != nil {
3✔
2268
                        startErr = err
×
2269
                        return
×
2270
                }
×
2271

2272
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2273
                if err := s.utxoNursery.Start(); err != nil {
3✔
2274
                        startErr = err
×
2275
                        return
×
2276
                }
×
2277

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

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

2290
                // htlcSwitch must be started before chainArb since the latter
2291
                // relies on htlcSwitch to deliver resolution message upon
2292
                // start.
2293
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2294
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2295
                        startErr = err
×
2296
                        return
×
2297
                }
×
2298

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

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

2311
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2312
                if err := s.chainArb.Start(beat); err != nil {
3✔
2313
                        startErr = err
×
2314
                        return
×
2315
                }
×
2316

2317
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2318
                if err := s.graphDB.Start(); err != nil {
3✔
2319
                        startErr = err
×
2320
                        return
×
2321
                }
×
2322

2323
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2324
                if err := s.graphBuilder.Start(); err != nil {
3✔
2325
                        startErr = err
×
2326
                        return
×
2327
                }
×
2328

2329
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2330
                if err := s.chanRouter.Start(); err != nil {
3✔
2331
                        startErr = err
×
2332
                        return
×
2333
                }
×
2334
                // The authGossiper depends on the chanRouter and therefore
2335
                // should be started after it.
2336
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2337
                if err := s.authGossiper.Start(); err != nil {
3✔
2338
                        startErr = err
×
2339
                        return
×
2340
                }
×
2341

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

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

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

2363
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2364
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2365
                        startErr = err
×
2366
                        return
×
2367
                }
×
2368

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

2375
                cleanup.add(func() error {
3✔
2376
                        s.missionController.StopStoreTickers()
×
2377
                        return nil
×
2378
                })
×
2379
                s.missionController.RunStoreTickers()
3✔
2380

3✔
2381
                // Before we start the connMgr, we'll check to see if we have
3✔
2382
                // any backups to recover. We do this now as we want to ensure
3✔
2383
                // that have all the information we need to handle channel
3✔
2384
                // recovery _before_ we even accept connections from any peers.
3✔
2385
                chanRestorer := &chanDBRestorer{
3✔
2386
                        db:         s.chanStateDB,
3✔
2387
                        secretKeys: s.cc.KeyRing,
3✔
2388
                        chainArb:   s.chainArb,
3✔
2389
                }
3✔
2390
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2391
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2392
                                s.chansToRestore.PackedSingleChanBackups,
×
2393
                                s.cc.KeyRing, chanRestorer, s,
×
2394
                        )
×
2395
                        if err != nil {
×
2396
                                startErr = fmt.Errorf("unable to unpack single "+
×
2397
                                        "backups: %v", err)
×
2398
                                return
×
2399
                        }
×
2400
                }
2401
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2402
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2403
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2404
                                s.cc.KeyRing, chanRestorer, s,
3✔
2405
                        )
3✔
2406
                        if err != nil {
3✔
2407
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2408
                                        "backup: %v", err)
×
2409
                                return
×
2410
                        }
×
2411
                }
2412

2413
                // chanSubSwapper must be started after the `channelNotifier`
2414
                // because it depends on channel events as a synchronization
2415
                // point.
2416
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2417
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

2422
                if s.torController != nil {
3✔
2423
                        cleanup = cleanup.add(s.torController.Stop)
×
2424
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2425
                                startErr = err
×
2426
                                return
×
2427
                        }
×
2428
                }
2429

2430
                if s.natTraversal != nil {
3✔
2431
                        s.wg.Add(1)
×
2432
                        go s.watchExternalIP()
×
2433
                }
×
2434

2435
                // Start connmgr last to prevent connections before init.
2436
                cleanup = cleanup.add(func() error {
3✔
2437
                        s.connMgr.Stop()
×
2438
                        return nil
×
2439
                })
×
2440

2441
                // RESOLVE: s.connMgr.Start() is called here, but
2442
                // brontide.NewListener() is called in newServer. This means
2443
                // that we are actually listening and partially accepting
2444
                // inbound connections even before the connMgr starts.
2445
                //
2446
                // TODO(yy): move the log into the connMgr's `Start` method.
2447
                srvrLog.Info("connMgr starting...")
3✔
2448
                s.connMgr.Start()
3✔
2449
                srvrLog.Debug("connMgr started")
3✔
2450

3✔
2451
                // If peers are specified as a config option, we'll add those
3✔
2452
                // peers first.
3✔
2453
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2454
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2455
                                peerAddrCfg,
3✔
2456
                        )
3✔
2457
                        if err != nil {
3✔
2458
                                startErr = fmt.Errorf("unable to parse peer "+
×
2459
                                        "pubkey from config: %v", err)
×
2460
                                return
×
2461
                        }
×
2462
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2463
                        if err != nil {
3✔
2464
                                startErr = fmt.Errorf("unable to parse peer "+
×
2465
                                        "address provided as a config option: "+
×
2466
                                        "%v", err)
×
2467
                                return
×
2468
                        }
×
2469

2470
                        peerAddr := &lnwire.NetAddress{
3✔
2471
                                IdentityKey: parsedPubkey,
3✔
2472
                                Address:     addr,
3✔
2473
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2474
                        }
3✔
2475

3✔
2476
                        err = s.ConnectToPeer(
3✔
2477
                                peerAddr, true,
3✔
2478
                                s.cfg.ConnectionTimeout,
3✔
2479
                        )
3✔
2480
                        if err != nil {
3✔
2481
                                startErr = fmt.Errorf("unable to connect to "+
×
2482
                                        "peer address provided as a config "+
×
2483
                                        "option: %v", err)
×
2484
                                return
×
2485
                        }
×
2486
                }
2487

2488
                // Subscribe to NodeAnnouncements that advertise new addresses
2489
                // our persistent peers.
2490
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2491
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2492
                                "addr: %v", err)
×
2493

×
2494
                        startErr = err
×
2495
                        return
×
2496
                }
×
2497

2498
                // With all the relevant sub-systems started, we'll now attempt
2499
                // to establish persistent connections to our direct channel
2500
                // collaborators within the network. Before doing so however,
2501
                // we'll prune our set of link nodes found within the database
2502
                // to ensure we don't reconnect to any nodes we no longer have
2503
                // open channels with.
2504
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2505
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2506

×
2507
                        startErr = err
×
2508
                        return
×
2509
                }
×
2510

2511
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2512
                        srvrLog.Errorf("Failed to establish persistent "+
×
2513
                                "connections: %v", err)
×
2514
                }
×
2515

2516
                // setSeedList is a helper function that turns multiple DNS seed
2517
                // server tuples from the command line or config file into the
2518
                // data structure we need and does a basic formal sanity check
2519
                // in the process.
2520
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2521
                        if len(tuples) == 0 {
×
2522
                                return
×
2523
                        }
×
2524

2525
                        result := make([][2]string, len(tuples))
×
2526
                        for idx, tuple := range tuples {
×
2527
                                tuple = strings.TrimSpace(tuple)
×
2528
                                if len(tuple) == 0 {
×
2529
                                        return
×
2530
                                }
×
2531

2532
                                servers := strings.Split(tuple, ",")
×
2533
                                if len(servers) > 2 || len(servers) == 0 {
×
2534
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2535
                                                "seed tuple: %v", servers)
×
2536
                                        return
×
2537
                                }
×
2538

2539
                                copy(result[idx][:], servers)
×
2540
                        }
2541

2542
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2543
                }
2544

2545
                // Let users overwrite the DNS seed nodes. We only allow them
2546
                // for bitcoin mainnet/testnet/signet.
2547
                if s.cfg.Bitcoin.MainNet {
3✔
2548
                        setSeedList(
×
2549
                                s.cfg.Bitcoin.DNSSeeds,
×
2550
                                chainreg.BitcoinMainnetGenesis,
×
2551
                        )
×
2552
                }
×
2553
                if s.cfg.Bitcoin.TestNet3 {
3✔
2554
                        setSeedList(
×
2555
                                s.cfg.Bitcoin.DNSSeeds,
×
2556
                                chainreg.BitcoinTestnetGenesis,
×
2557
                        )
×
2558
                }
×
2559
                if s.cfg.Bitcoin.TestNet4 {
3✔
2560
                        setSeedList(
×
2561
                                s.cfg.Bitcoin.DNSSeeds,
×
2562
                                chainreg.BitcoinTestnet4Genesis,
×
2563
                        )
×
2564
                }
×
2565
                if s.cfg.Bitcoin.SigNet {
3✔
2566
                        setSeedList(
×
2567
                                s.cfg.Bitcoin.DNSSeeds,
×
2568
                                chainreg.BitcoinSignetGenesis,
×
2569
                        )
×
2570
                }
×
2571

2572
                // If network bootstrapping hasn't been disabled, then we'll
2573
                // configure the set of active bootstrappers, and launch a
2574
                // dedicated goroutine to maintain a set of persistent
2575
                // connections.
2576
                if !s.cfg.NoNetBootstrap {
6✔
2577
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2578
                        if err != nil {
3✔
2579
                                startErr = err
×
2580
                                return
×
2581
                        }
×
2582

2583
                        s.wg.Add(1)
3✔
2584
                        go s.peerBootstrapper(
3✔
2585
                                ctx, defaultMinPeers, bootstrappers,
3✔
2586
                        )
3✔
2587
                } else {
3✔
2588
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2589
                }
3✔
2590

2591
                // Start the blockbeat after all other subsystems have been
2592
                // started so they are ready to receive new blocks.
2593
                cleanup = cleanup.add(func() error {
3✔
2594
                        s.blockbeatDispatcher.Stop()
×
2595
                        return nil
×
2596
                })
×
2597
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2598
                        startErr = err
×
2599
                        return
×
2600
                }
×
2601

2602
                // Set the active flag now that we've completed the full
2603
                // startup.
2604
                atomic.StoreInt32(&s.active, 1)
3✔
2605
        })
2606

2607
        if startErr != nil {
3✔
2608
                cleanup.run()
×
2609
        }
×
2610
        return startErr
3✔
2611
}
2612

2613
// Stop gracefully shutsdown the main daemon server. This function will signal
2614
// any active goroutines, or helper objects to exit, then blocks until they've
2615
// all successfully exited. Additionally, any/all listeners are closed.
2616
// NOTE: This function is safe for concurrent access.
2617
func (s *server) Stop() error {
3✔
2618
        s.stop.Do(func() {
6✔
2619
                atomic.StoreInt32(&s.stopping, 1)
3✔
2620

3✔
2621
                ctx := context.Background()
3✔
2622

3✔
2623
                close(s.quit)
3✔
2624

3✔
2625
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2626
                s.connMgr.Stop()
3✔
2627

3✔
2628
                // Stop dispatching blocks to other systems immediately.
3✔
2629
                s.blockbeatDispatcher.Stop()
3✔
2630

3✔
2631
                // Shutdown the onion router for onion messaging.
3✔
2632
                s.sphinxRouterNoReplayLog.Stop()
3✔
2633

3✔
2634
                // Shutdown the actor system to stop all actors.
3✔
2635
                if err := s.actorSystem.Shutdown(); err != nil {
3✔
NEW
2636
                        srvrLog.Warnf("failed to stop actorSystem: %v", err)
×
NEW
2637
                }
×
2638

2639
                // Shutdown the wallet, funding manager, and the rpc server.
2640
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2641
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2642
                }
×
2643
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2644
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2645
                }
×
2646
                if err := s.sphinx.Stop(); err != nil {
3✔
2647
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2648
                }
×
2649
                if err := s.invoices.Stop(); err != nil {
3✔
2650
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2651
                }
×
2652
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2653
                        srvrLog.Warnf("failed to stop interceptable "+
×
2654
                                "switch: %v", err)
×
2655
                }
×
2656
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2657
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2658
                                "modifier: %v", err)
×
2659
                }
×
2660
                if err := s.chanRouter.Stop(); err != nil {
3✔
2661
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2662
                }
×
2663
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2664
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2665
                }
×
2666
                if err := s.graphDB.Stop(); err != nil {
3✔
2667
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2668
                }
×
2669
                if err := s.chainArb.Stop(); err != nil {
3✔
2670
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2671
                }
×
2672
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2673
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2674
                }
×
2675
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2676
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2677
                                err)
×
2678
                }
×
2679
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2680
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2681
                }
×
2682
                if err := s.authGossiper.Stop(); err != nil {
3✔
2683
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2684
                }
×
2685
                if err := s.sweeper.Stop(); err != nil {
3✔
2686
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2687
                }
×
2688
                if err := s.txPublisher.Stop(); err != nil {
3✔
2689
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2690
                }
×
2691
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2692
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2693
                }
×
2694
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2695
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2696
                }
×
2697
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2698
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2699
                }
×
2700

2701
                // Update channel.backup file. Make sure to do it before
2702
                // stopping chanSubSwapper.
2703
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2704
                        ctx, s.chanStateDB, s.addrSource,
3✔
2705
                )
3✔
2706
                if err != nil {
3✔
2707
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2708
                                err)
×
2709
                } else {
3✔
2710
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2711
                        if err != nil {
6✔
2712
                                srvrLog.Warnf("Manual update of channel "+
3✔
2713
                                        "backup failed: %v", err)
3✔
2714
                        }
3✔
2715
                }
2716

2717
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2718
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2719
                }
×
2720
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2721
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2722
                }
×
2723
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2724
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2725
                                err)
×
2726
                }
×
2727
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2728
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2729
                                err)
×
2730
                }
×
2731
                s.missionController.StopStoreTickers()
3✔
2732

3✔
2733
                // Disconnect from each active peers to ensure that
3✔
2734
                // peerTerminationWatchers signal completion to each peer.
3✔
2735
                for _, peer := range s.Peers() {
6✔
2736
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2737
                        if err != nil {
3✔
2738
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2739
                                        "received error: %v", peer.IdentityKey(),
×
2740
                                        err,
×
2741
                                )
×
2742
                        }
×
2743
                }
2744

2745
                // Now that all connections have been torn down, stop the tower
2746
                // client which will reliably flush all queued states to the
2747
                // tower. If this is halted for any reason, the force quit timer
2748
                // will kick in and abort to allow this method to return.
2749
                if s.towerClientMgr != nil {
6✔
2750
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2751
                                srvrLog.Warnf("Unable to shut down tower "+
×
2752
                                        "client manager: %v", err)
×
2753
                        }
×
2754
                }
2755

2756
                if s.hostAnn != nil {
3✔
2757
                        if err := s.hostAnn.Stop(); err != nil {
×
2758
                                srvrLog.Warnf("unable to shut down host "+
×
2759
                                        "annoucner: %v", err)
×
2760
                        }
×
2761
                }
2762

2763
                if s.livenessMonitor != nil {
6✔
2764
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2765
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2766
                                        "monitor: %v", err)
×
2767
                        }
×
2768
                }
2769

2770
                // Wait for all lingering goroutines to quit.
2771
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2772
                s.wg.Wait()
3✔
2773

3✔
2774
                srvrLog.Debug("Stopping buffer pools...")
3✔
2775
                s.sigPool.Stop()
3✔
2776
                s.writePool.Stop()
3✔
2777
                s.readPool.Stop()
3✔
2778
        })
2779

2780
        return nil
3✔
2781
}
2782

2783
// Stopped returns true if the server has been instructed to shutdown.
2784
// NOTE: This function is safe for concurrent access.
2785
func (s *server) Stopped() bool {
3✔
2786
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2787
}
3✔
2788

2789
// configurePortForwarding attempts to set up port forwarding for the different
2790
// ports that the server will be listening on.
2791
//
2792
// NOTE: This should only be used when using some kind of NAT traversal to
2793
// automatically set up forwarding rules.
2794
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2795
        ip, err := s.natTraversal.ExternalIP()
×
2796
        if err != nil {
×
2797
                return nil, err
×
2798
        }
×
2799
        s.lastDetectedIP = ip
×
2800

×
2801
        externalIPs := make([]string, 0, len(ports))
×
2802
        for _, port := range ports {
×
2803
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2804
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2805
                        continue
×
2806
                }
2807

2808
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2809
                externalIPs = append(externalIPs, hostIP)
×
2810
        }
2811

2812
        return externalIPs, nil
×
2813
}
2814

2815
// removePortForwarding attempts to clear the forwarding rules for the different
2816
// ports the server is currently listening on.
2817
//
2818
// NOTE: This should only be used when using some kind of NAT traversal to
2819
// automatically set up forwarding rules.
2820
func (s *server) removePortForwarding() {
×
2821
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2822
        for _, port := range forwardedPorts {
×
2823
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2824
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2825
                                "port %d: %v", port, err)
×
2826
                }
×
2827
        }
2828
}
2829

2830
// watchExternalIP continuously checks for an updated external IP address every
2831
// 15 minutes. Once a new IP address has been detected, it will automatically
2832
// handle port forwarding rules and send updated node announcements to the
2833
// currently connected peers.
2834
//
2835
// NOTE: This MUST be run as a goroutine.
2836
func (s *server) watchExternalIP() {
×
2837
        defer s.wg.Done()
×
2838

×
2839
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2840
        // up by the server.
×
2841
        defer s.removePortForwarding()
×
2842

×
2843
        // Keep track of the external IPs set by the user to avoid replacing
×
2844
        // them when detecting a new IP.
×
2845
        ipsSetByUser := make(map[string]struct{})
×
2846
        for _, ip := range s.cfg.ExternalIPs {
×
2847
                ipsSetByUser[ip.String()] = struct{}{}
×
2848
        }
×
2849

2850
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2851

×
2852
        ticker := time.NewTicker(15 * time.Minute)
×
2853
        defer ticker.Stop()
×
2854
out:
×
2855
        for {
×
2856
                select {
×
2857
                case <-ticker.C:
×
2858
                        // We'll start off by making sure a new IP address has
×
2859
                        // been detected.
×
2860
                        ip, err := s.natTraversal.ExternalIP()
×
2861
                        if err != nil {
×
2862
                                srvrLog.Debugf("Unable to retrieve the "+
×
2863
                                        "external IP address: %v", err)
×
2864
                                continue
×
2865
                        }
2866

2867
                        // Periodically renew the NAT port forwarding.
2868
                        for _, port := range forwardedPorts {
×
2869
                                err := s.natTraversal.AddPortMapping(port)
×
2870
                                if err != nil {
×
2871
                                        srvrLog.Warnf("Unable to automatically "+
×
2872
                                                "re-create port forwarding using %s: %v",
×
2873
                                                s.natTraversal.Name(), err)
×
2874
                                } else {
×
2875
                                        srvrLog.Debugf("Automatically re-created "+
×
2876
                                                "forwarding for port %d using %s to "+
×
2877
                                                "advertise external IP",
×
2878
                                                port, s.natTraversal.Name())
×
2879
                                }
×
2880
                        }
2881

2882
                        if ip.Equal(s.lastDetectedIP) {
×
2883
                                continue
×
2884
                        }
2885

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

×
2888
                        // Next, we'll craft the new addresses that will be
×
2889
                        // included in the new node announcement and advertised
×
2890
                        // to the network. Each address will consist of the new
×
2891
                        // IP detected and one of the currently advertised
×
2892
                        // ports.
×
2893
                        var newAddrs []net.Addr
×
2894
                        for _, port := range forwardedPorts {
×
2895
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2896
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2897
                                if err != nil {
×
2898
                                        srvrLog.Debugf("Unable to resolve "+
×
2899
                                                "host %v: %v", addr, err)
×
2900
                                        continue
×
2901
                                }
2902

2903
                                newAddrs = append(newAddrs, addr)
×
2904
                        }
2905

2906
                        // Skip the update if we weren't able to resolve any of
2907
                        // the new addresses.
2908
                        if len(newAddrs) == 0 {
×
2909
                                srvrLog.Debug("Skipping node announcement " +
×
2910
                                        "update due to not being able to " +
×
2911
                                        "resolve any new addresses")
×
2912
                                continue
×
2913
                        }
2914

2915
                        // Now, we'll need to update the addresses in our node's
2916
                        // announcement in order to propagate the update
2917
                        // throughout the network. We'll only include addresses
2918
                        // that have a different IP from the previous one, as
2919
                        // the previous IP is no longer valid.
2920
                        currentNodeAnn := s.getNodeAnnouncement()
×
2921

×
2922
                        for _, addr := range currentNodeAnn.Addresses {
×
2923
                                host, _, err := net.SplitHostPort(addr.String())
×
2924
                                if err != nil {
×
2925
                                        srvrLog.Debugf("Unable to determine "+
×
2926
                                                "host from address %v: %v",
×
2927
                                                addr, err)
×
2928
                                        continue
×
2929
                                }
2930

2931
                                // We'll also make sure to include external IPs
2932
                                // set manually by the user.
2933
                                _, setByUser := ipsSetByUser[addr.String()]
×
2934
                                if setByUser || host != s.lastDetectedIP.String() {
×
2935
                                        newAddrs = append(newAddrs, addr)
×
2936
                                }
×
2937
                        }
2938

2939
                        // Then, we'll generate a new timestamped node
2940
                        // announcement with the updated addresses and broadcast
2941
                        // it to our peers.
2942
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2943
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2944
                        )
×
2945
                        if err != nil {
×
2946
                                srvrLog.Debugf("Unable to generate new node "+
×
2947
                                        "announcement: %v", err)
×
2948
                                continue
×
2949
                        }
2950

2951
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2952
                        if err != nil {
×
2953
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2954
                                        "announcement to peers: %v", err)
×
2955
                                continue
×
2956
                        }
2957

2958
                        // Finally, update the last IP seen to the current one.
2959
                        s.lastDetectedIP = ip
×
2960
                case <-s.quit:
×
2961
                        break out
×
2962
                }
2963
        }
2964
}
2965

2966
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2967
// based on the server, and currently active bootstrap mechanisms as defined
2968
// within the current configuration.
2969
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
2970
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
2971

3✔
2972
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
2973

3✔
2974
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
2975
        // this can be used by default if we've already partially seeded the
3✔
2976
        // network.
3✔
2977
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
2978
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
2979
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
2980
        )
3✔
2981
        if err != nil {
3✔
2982
                return nil, err
×
2983
        }
×
2984
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
2985

3✔
2986
        // If this isn't using simnet or regtest mode, then one of our
3✔
2987
        // additional bootstrapping sources will be the set of running DNS
3✔
2988
        // seeds.
3✔
2989
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
2990
                //nolint:ll
×
2991
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2992

×
2993
                // If we have a set of DNS seeds for this chain, then we'll add
×
2994
                // it as an additional bootstrapping source.
×
2995
                if ok {
×
2996
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2997
                                "seeds: %v", dnsSeeds)
×
2998

×
2999
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3000
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3001
                        )
×
3002
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3003
                }
×
3004
        }
3005

3006
        return bootStrappers, nil
3✔
3007
}
3008

3009
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3010
// needs to ignore, which is made of three parts,
3011
//   - the node itself needs to be skipped as it doesn't make sense to connect
3012
//     to itself.
3013
//   - the peers that already have connections with, as in s.peersByPub.
3014
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3015
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
3✔
3016
        s.mu.RLock()
3✔
3017
        defer s.mu.RUnlock()
3✔
3018

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

3✔
3021
        // We should ignore ourselves from bootstrapping.
3✔
3022
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3023
        ignore[selfKey] = struct{}{}
3✔
3024

3✔
3025
        // Ignore all connected peers.
3✔
3026
        for _, peer := range s.peersByPub {
3✔
3027
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3028
                ignore[nID] = struct{}{}
×
3029
        }
×
3030

3031
        // Ignore all persistent peers as they have a dedicated reconnecting
3032
        // process.
3033
        for pubKeyStr := range s.persistentPeers {
3✔
3034
                var nID autopilot.NodeID
×
3035
                copy(nID[:], []byte(pubKeyStr))
×
3036
                ignore[nID] = struct{}{}
×
3037
        }
×
3038

3039
        return ignore
3✔
3040
}
3041

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

3✔
3050
        defer s.wg.Done()
3✔
3051

3✔
3052
        // Before we continue, init the ignore peers map.
3✔
3053
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3054

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

3✔
3059
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3060
        // peers.
3✔
3061
        //
3✔
3062
        // We'll use a 15 second backoff, and double the time every time an
3✔
3063
        // epoch fails up to a ceiling.
3✔
3064
        backOff := time.Second * 15
3✔
3065

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

3✔
3071
        // We'll use the number of attempts and errors to determine if we need
3✔
3072
        // to increase the time between discovery epochs.
3✔
3073
        var epochErrors uint32 // To be used atomically.
3✔
3074
        var epochAttempts uint32
3✔
3075

3✔
3076
        for {
6✔
3077
                select {
3✔
3078
                // The ticker has just woken us up, so we'll need to check if
3079
                // we need to attempt to connect our to any more peers.
3080
                case <-sampleTicker.C:
×
3081
                        // Obtain the current number of peers, so we can gauge
×
3082
                        // if we need to sample more peers or not.
×
3083
                        s.mu.RLock()
×
3084
                        numActivePeers := uint32(len(s.peersByPub))
×
3085
                        s.mu.RUnlock()
×
3086

×
3087
                        // If we have enough peers, then we can loop back
×
3088
                        // around to the next round as we're done here.
×
3089
                        if numActivePeers >= numTargetPeers {
×
3090
                                continue
×
3091
                        }
3092

3093
                        // If all of our attempts failed during this last back
3094
                        // off period, then will increase our backoff to 5
3095
                        // minute ceiling to avoid an excessive number of
3096
                        // queries
3097
                        //
3098
                        // TODO(roasbeef): add reverse policy too?
3099

3100
                        if epochAttempts > 0 &&
×
3101
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3102

×
3103
                                sampleTicker.Stop()
×
3104

×
3105
                                backOff *= 2
×
3106
                                if backOff > bootstrapBackOffCeiling {
×
3107
                                        backOff = bootstrapBackOffCeiling
×
3108
                                }
×
3109

3110
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3111
                                        "%v", backOff)
×
3112
                                sampleTicker = time.NewTicker(backOff)
×
3113
                                continue
×
3114
                        }
3115

3116
                        atomic.StoreUint32(&epochErrors, 0)
×
3117
                        epochAttempts = 0
×
3118

×
3119
                        // Since we know need more peers, we'll compute the
×
3120
                        // exact number we need to reach our threshold.
×
3121
                        numNeeded := numTargetPeers - numActivePeers
×
3122

×
3123
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3124
                                "peers", numNeeded)
×
3125

×
3126
                        // With the number of peers we need calculated, we'll
×
3127
                        // query the network bootstrappers to sample a set of
×
3128
                        // random addrs for us.
×
3129
                        //
×
3130
                        // Before we continue, get a copy of the ignore peers
×
3131
                        // map.
×
3132
                        ignoreList = s.createBootstrapIgnorePeers()
×
3133

×
3134
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3135
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3136
                        )
×
3137
                        if err != nil {
×
3138
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3139
                                        "peers: %v", err)
×
3140
                                continue
×
3141
                        }
3142

3143
                        // Finally, we'll launch a new goroutine for each
3144
                        // prospective peer candidates.
3145
                        for _, addr := range peerAddrs {
×
3146
                                epochAttempts++
×
3147

×
3148
                                go func(a *lnwire.NetAddress) {
×
3149
                                        // TODO(roasbeef): can do AS, subnet,
×
3150
                                        // country diversity, etc
×
3151
                                        errChan := make(chan error, 1)
×
3152
                                        s.connectToPeer(
×
3153
                                                a, errChan,
×
3154
                                                s.cfg.ConnectionTimeout,
×
3155
                                        )
×
3156
                                        select {
×
3157
                                        case err := <-errChan:
×
3158
                                                if err == nil {
×
3159
                                                        return
×
3160
                                                }
×
3161

3162
                                                srvrLog.Errorf("Unable to "+
×
3163
                                                        "connect to %v: %v",
×
3164
                                                        a, err)
×
3165
                                                atomic.AddUint32(&epochErrors, 1)
×
3166
                                        case <-s.quit:
×
3167
                                        }
3168
                                }(addr)
3169
                        }
3170
                case <-s.quit:
3✔
3171
                        return
3✔
3172
                }
3173
        }
3174
}
3175

3176
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3177
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3178
// query back off each time we encounter a failure.
3179
const bootstrapBackOffCeiling = time.Minute * 5
3180

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

3✔
3188
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3189
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3190

3✔
3191
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3192
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3193
        var delaySignal <-chan time.Time
3✔
3194
        delayTime := time.Second * 2
3✔
3195

3✔
3196
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3197
        // then the main peer bootstrap logic.
3✔
3198
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3199

3✔
3200
        for attempts := 0; ; attempts++ {
6✔
3201
                // Check if the server has been requested to shut down in order
3✔
3202
                // to prevent blocking.
3✔
3203
                if s.Stopped() {
3✔
3204
                        return
×
3205
                }
×
3206

3207
                // We can exit our aggressive initial peer bootstrapping stage
3208
                // if we've reached out target number of peers.
3209
                s.mu.RLock()
3✔
3210
                numActivePeers := uint32(len(s.peersByPub))
3✔
3211
                s.mu.RUnlock()
3✔
3212

3✔
3213
                if numActivePeers >= numTargetPeers {
6✔
3214
                        return
3✔
3215
                }
3✔
3216

3217
                if attempts > 0 {
3✔
UNCOV
3218
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
UNCOV
3219
                                "bootstrap peers (attempt #%v)", delayTime,
×
UNCOV
3220
                                attempts)
×
UNCOV
3221

×
UNCOV
3222
                        // We've completed at least one iterating and haven't
×
UNCOV
3223
                        // finished, so we'll start to insert a delay period
×
UNCOV
3224
                        // between each attempt.
×
UNCOV
3225
                        delaySignal = time.After(delayTime)
×
UNCOV
3226
                        select {
×
UNCOV
3227
                        case <-delaySignal:
×
UNCOV
3228
                        case <-s.quit:
×
UNCOV
3229
                                return
×
3230
                        }
3231

3232
                        // After our delay, we'll double the time we wait up to
3233
                        // the max back off period.
UNCOV
3234
                        delayTime *= 2
×
UNCOV
3235
                        if delayTime > backOffCeiling {
×
3236
                                delayTime = backOffCeiling
×
3237
                        }
×
3238
                }
3239

3240
                // Otherwise, we'll request for the remaining number of peers
3241
                // in order to reach our target.
3242
                peersNeeded := numTargetPeers - numActivePeers
3✔
3243
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3244
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3245
                )
3✔
3246
                if err != nil {
3✔
UNCOV
3247
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
UNCOV
3248
                                "peers: %v", err)
×
UNCOV
3249
                        continue
×
3250
                }
3251

3252
                // Then, we'll attempt to establish a connection to the
3253
                // different peer addresses retrieved by our bootstrappers.
3254
                var wg sync.WaitGroup
3✔
3255
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3256
                        wg.Add(1)
3✔
3257
                        go func(addr *lnwire.NetAddress) {
6✔
3258
                                defer wg.Done()
3✔
3259

3✔
3260
                                errChan := make(chan error, 1)
3✔
3261
                                go s.connectToPeer(
3✔
3262
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3263
                                )
3✔
3264

3✔
3265
                                // We'll only allow this connection attempt to
3✔
3266
                                // take up to 3 seconds. This allows us to move
3✔
3267
                                // quickly by discarding peers that are slowing
3✔
3268
                                // us down.
3✔
3269
                                select {
3✔
3270
                                case err := <-errChan:
3✔
3271
                                        if err == nil {
6✔
3272
                                                return
3✔
3273
                                        }
3✔
3274
                                        srvrLog.Errorf("Unable to connect to "+
×
3275
                                                "%v: %v", addr, err)
×
3276
                                // TODO: tune timeout? 3 seconds might be *too*
3277
                                // aggressive but works well.
3278
                                case <-time.After(3 * time.Second):
×
3279
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3280
                                                "to not establishing a "+
×
3281
                                                "connection within 3 seconds",
×
3282
                                                addr)
×
3283
                                case <-s.quit:
×
3284
                                }
3285
                        }(bootstrapAddr)
3286
                }
3287

3288
                wg.Wait()
3✔
3289
        }
3290
}
3291

3292
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3293
// order to listen for inbound connections over Tor.
3294
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3295
        // Determine the different ports the server is listening on. The onion
×
3296
        // service's virtual port will map to these ports and one will be picked
×
3297
        // at random when the onion service is being accessed.
×
3298
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3299
        for _, listenAddr := range s.listenAddrs {
×
3300
                port := listenAddr.(*net.TCPAddr).Port
×
3301
                listenPorts = append(listenPorts, port)
×
3302
        }
×
3303

3304
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3305
        if err != nil {
×
3306
                return err
×
3307
        }
×
3308

3309
        // Once the port mapping has been set, we can go ahead and automatically
3310
        // create our onion service. The service's private key will be saved to
3311
        // disk in order to regain access to this service when restarting `lnd`.
3312
        onionCfg := tor.AddOnionConfig{
×
3313
                VirtualPort: defaultPeerPort,
×
3314
                TargetPorts: listenPorts,
×
3315
                Store: tor.NewOnionFile(
×
3316
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3317
                        encrypter,
×
3318
                ),
×
3319
        }
×
3320

×
3321
        switch {
×
3322
        case s.cfg.Tor.V2:
×
3323
                onionCfg.Type = tor.V2
×
3324
        case s.cfg.Tor.V3:
×
3325
                onionCfg.Type = tor.V3
×
3326
        }
3327

3328
        addr, err := s.torController.AddOnion(onionCfg)
×
3329
        if err != nil {
×
3330
                return err
×
3331
        }
×
3332

3333
        // Now that the onion service has been created, we'll add the onion
3334
        // address it can be reached at to our list of advertised addresses.
3335
        newNodeAnn, err := s.genNodeAnnouncement(
×
3336
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3337
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3338
                },
×
3339
        )
3340
        if err != nil {
×
3341
                return fmt.Errorf("unable to generate new node "+
×
3342
                        "announcement: %v", err)
×
3343
        }
×
3344

3345
        // Finally, we'll update the on-disk version of our announcement so it
3346
        // will eventually propagate to nodes in the network.
3347
        selfNode := models.NewV1Node(
×
3348
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3349
                        Addresses:    newNodeAnn.Addresses,
×
3350
                        Features:     newNodeAnn.Features,
×
3351
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3352
                        Color:        newNodeAnn.RGBColor,
×
3353
                        Alias:        newNodeAnn.Alias.String(),
×
3354
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3355
                },
×
3356
        )
×
3357

×
3358
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3359
                return fmt.Errorf("can't set self node: %w", err)
×
3360
        }
×
3361

3362
        return nil
×
3363
}
3364

3365
// findChannel finds a channel given a public key and ChannelID. It is an
3366
// optimization that is quicker than seeking for a channel given only the
3367
// ChannelID.
3368
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3369
        *channeldb.OpenChannel, error) {
3✔
3370

3✔
3371
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3372
        if err != nil {
3✔
3373
                return nil, err
×
3374
        }
×
3375

3376
        for _, channel := range nodeChans {
6✔
3377
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3378
                        return channel, nil
3✔
3379
                }
3✔
3380
        }
3381

3382
        return nil, fmt.Errorf("unable to find channel")
3✔
3383
}
3384

3385
// getNodeAnnouncement fetches the current, fully signed node announcement.
3386
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
3✔
3387
        s.mu.Lock()
3✔
3388
        defer s.mu.Unlock()
3✔
3389

3✔
3390
        return *s.currentNodeAnn
3✔
3391
}
3✔
3392

3393
// genNodeAnnouncement generates and returns the current fully signed node
3394
// announcement. The time stamp of the announcement will be updated in order
3395
// to ensure it propagates through the network.
3396
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3397
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
3✔
3398

3✔
3399
        s.mu.Lock()
3✔
3400
        defer s.mu.Unlock()
3✔
3401

3✔
3402
        // Create a shallow copy of the current node announcement to work on.
3✔
3403
        // This ensures the original announcement remains unchanged
3✔
3404
        // until the new announcement is fully signed and valid.
3✔
3405
        newNodeAnn := *s.currentNodeAnn
3✔
3406

3✔
3407
        // First, try to update our feature manager with the updated set of
3✔
3408
        // features.
3✔
3409
        if features != nil {
6✔
3410
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3411
                        feature.SetNodeAnn: features,
3✔
3412
                }
3✔
3413
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3414
                if err != nil {
6✔
3415
                        return lnwire.NodeAnnouncement1{}, err
3✔
3416
                }
3✔
3417

3418
                // If we could successfully update our feature manager, add
3419
                // an update modifier to include these new features to our
3420
                // set.
3421
                modifiers = append(
3✔
3422
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3423
                )
3✔
3424
        }
3425

3426
        // Always update the timestamp when refreshing to ensure the update
3427
        // propagates.
3428
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3429

3✔
3430
        // Apply the requested changes to the node announcement.
3✔
3431
        for _, modifier := range modifiers {
6✔
3432
                modifier(&newNodeAnn)
3✔
3433
        }
3✔
3434

3435
        // The modifiers may have added duplicate addresses, so we need to
3436
        // de-duplicate them here.
3437
        uniqueAddrs := map[string]struct{}{}
3✔
3438
        dedupedAddrs := make([]net.Addr, 0)
3✔
3439
        for _, addr := range newNodeAnn.Addresses {
6✔
3440
                if _, ok := uniqueAddrs[addr.String()]; !ok {
6✔
3441
                        uniqueAddrs[addr.String()] = struct{}{}
3✔
3442
                        dedupedAddrs = append(dedupedAddrs, addr)
3✔
3443
                }
3✔
3444
        }
3445
        newNodeAnn.Addresses = dedupedAddrs
3✔
3446

3✔
3447
        // Sign a new update after applying all of the passed modifiers.
3✔
3448
        err := netann.SignNodeAnnouncement(
3✔
3449
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3450
        )
3✔
3451
        if err != nil {
3✔
3452
                return lnwire.NodeAnnouncement1{}, err
×
3453
        }
×
3454

3455
        // If signing succeeds, update the current announcement.
3456
        *s.currentNodeAnn = newNodeAnn
3✔
3457

3✔
3458
        return *s.currentNodeAnn, nil
3✔
3459
}
3460

3461
// updateAndBroadcastSelfNode generates a new node announcement
3462
// applying the giving modifiers and updating the time stamp
3463
// to ensure it propagates through the network. Then it broadcasts
3464
// it to the network.
3465
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3466
        features *lnwire.RawFeatureVector,
3467
        modifiers ...netann.NodeAnnModifier) error {
3✔
3468

3✔
3469
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3470
        if err != nil {
6✔
3471
                return fmt.Errorf("unable to generate new node "+
3✔
3472
                        "announcement: %v", err)
3✔
3473
        }
3✔
3474

3475
        // Update the on-disk version of our announcement.
3476
        // Load and modify self node istead of creating anew instance so we
3477
        // don't risk overwriting any existing values.
3478
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3479
        if err != nil {
3✔
3480
                return fmt.Errorf("unable to get current source node: %w", err)
×
3481
        }
×
3482

3483
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3484
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3485
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
3✔
3486
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3487
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
3✔
3488
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3489

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

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

3496
        // Finally, propagate it to the nodes in the network.
3497
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3498
        if err != nil {
3✔
3499
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3500
                        "announcement to peers: %v", err)
×
3501
                return err
×
3502
        }
×
3503

3504
        return nil
3✔
3505
}
3506

3507
type nodeAddresses struct {
3508
        pubKey    *btcec.PublicKey
3509
        addresses []net.Addr
3510
}
3511

3512
// establishPersistentConnections attempts to establish persistent connections
3513
// to all our direct channel collaborators. In order to promote liveness of our
3514
// active channels, we instruct the connection manager to attempt to establish
3515
// and maintain persistent connections to all our direct channel counterparties.
3516
func (s *server) establishPersistentConnections(ctx context.Context) error {
3✔
3517
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3518
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3519
        // since other PubKey forms can't be compared.
3✔
3520
        nodeAddrsMap := make(map[string]*nodeAddresses)
3✔
3521

3✔
3522
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3523
        // attempt to connect to based on our set of previous connections. Set
3✔
3524
        // the reconnection port to the default peer port.
3✔
3525
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3526
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
3✔
3527
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3528
        }
×
3529

3530
        for _, node := range linkNodes {
6✔
3531
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3532
                nodeAddrs := &nodeAddresses{
3✔
3533
                        pubKey:    node.IdentityPub,
3✔
3534
                        addresses: node.Addresses,
3✔
3535
                }
3✔
3536
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3537
        }
3✔
3538

3539
        // After checking our previous connections for addresses to connect to,
3540
        // iterate through the nodes in our channel graph to find addresses
3541
        // that have been added via NodeAnnouncement1 messages.
3542
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3543
        // each of the nodes.
3544
        graphAddrs := make(map[string]*nodeAddresses)
3✔
3545
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
3✔
3546
                havePolicy bool, channelPeer *models.Node) error {
6✔
3547

3✔
3548
                // If the remote party has announced the channel to us, but we
3✔
3549
                // haven't yet, then we won't have a policy. However, we don't
3✔
3550
                // need this to connect to the peer, so we'll log it and move on.
3✔
3551
                if !havePolicy {
3✔
3552
                        srvrLog.Warnf("No channel policy found for "+
×
3553
                                "ChannelPoint(%v): ", chanPoint)
×
3554
                }
×
3555

3556
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3557

3✔
3558
                // Add all unique addresses from channel
3✔
3559
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3560
                // connect to for this peer.
3✔
3561
                addrSet := make(map[string]net.Addr)
3✔
3562
                for _, addr := range channelPeer.Addresses {
6✔
3563
                        switch addr.(type) {
3✔
3564
                        case *net.TCPAddr:
3✔
3565
                                addrSet[addr.String()] = addr
3✔
3566

3567
                        // We'll only attempt to connect to Tor addresses if Tor
3568
                        // outbound support is enabled.
3569
                        case *tor.OnionAddr:
×
3570
                                if s.cfg.Tor.Active {
×
3571
                                        addrSet[addr.String()] = addr
×
3572
                                }
×
3573
                        }
3574
                }
3575

3576
                // If this peer is also recorded as a link node, we'll add any
3577
                // additional addresses that have not already been selected.
3578
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3579
                if ok {
6✔
3580
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3581
                                switch lnAddress.(type) {
3✔
3582
                                case *net.TCPAddr:
3✔
3583
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3584

3585
                                // We'll only attempt to connect to Tor
3586
                                // addresses if Tor outbound support is enabled.
3587
                                case *tor.OnionAddr:
×
3588
                                        if s.cfg.Tor.Active {
×
3589
                                                //nolint:ll
×
3590
                                                addrSet[lnAddress.String()] = lnAddress
×
3591
                                        }
×
3592
                                }
3593
                        }
3594
                }
3595

3596
                // Construct a slice of the deduped addresses.
3597
                var addrs []net.Addr
3✔
3598
                for _, addr := range addrSet {
6✔
3599
                        addrs = append(addrs, addr)
3✔
3600
                }
3✔
3601

3602
                n := &nodeAddresses{
3✔
3603
                        addresses: addrs,
3✔
3604
                }
3✔
3605
                n.pubKey, err = channelPeer.PubKey()
3✔
3606
                if err != nil {
3✔
3607
                        return err
×
3608
                }
×
3609

3610
                graphAddrs[pubStr] = n
3✔
3611
                return nil
3✔
3612
        }
3613
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3614
                ctx, forEachSrcNodeChan, func() {
6✔
3615
                        clear(graphAddrs)
3✔
3616
                },
3✔
3617
        )
3618
        if err != nil {
3✔
3619
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3620
                        "%v", err)
×
3621

×
3622
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3623
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3624

×
3625
                        return err
×
3626
                }
×
3627
        }
3628

3629
        // Combine the addresses from the link nodes and the channel graph.
3630
        for pubStr, nodeAddr := range graphAddrs {
6✔
3631
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3632
        }
3✔
3633

3634
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3635
                len(nodeAddrsMap))
3✔
3636

3✔
3637
        // Acquire and hold server lock until all persistent connection requests
3✔
3638
        // have been recorded and sent to the connection manager.
3✔
3639
        s.mu.Lock()
3✔
3640
        defer s.mu.Unlock()
3✔
3641

3✔
3642
        // Iterate through the combined list of addresses from prior links and
3✔
3643
        // node announcements and attempt to reconnect to each node.
3✔
3644
        var numOutboundConns int
3✔
3645
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3646
                // Add this peer to the set of peers we should maintain a
3✔
3647
                // persistent connection with. We set the value to false to
3✔
3648
                // indicate that we should not continue to reconnect if the
3✔
3649
                // number of channels returns to zero, since this peer has not
3✔
3650
                // been requested as perm by the user.
3✔
3651
                s.persistentPeers[pubStr] = false
3✔
3652
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3653
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3654
                }
3✔
3655

3656
                for _, address := range nodeAddr.addresses {
6✔
3657
                        // Create a wrapper address which couples the IP and
3✔
3658
                        // the pubkey so the brontide authenticated connection
3✔
3659
                        // can be established.
3✔
3660
                        lnAddr := &lnwire.NetAddress{
3✔
3661
                                IdentityKey: nodeAddr.pubKey,
3✔
3662
                                Address:     address,
3✔
3663
                        }
3✔
3664

3✔
3665
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3666
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3667
                }
3✔
3668

3669
                // We'll connect to the first 10 peers immediately, then
3670
                // randomly stagger any remaining connections if the
3671
                // stagger initial reconnect flag is set. This ensures
3672
                // that mobile nodes or nodes with a small number of
3673
                // channels obtain connectivity quickly, but larger
3674
                // nodes are able to disperse the costs of connecting to
3675
                // all peers at once.
3676
                if numOutboundConns < numInstantInitReconnect ||
3✔
3677
                        !s.cfg.StaggerInitialReconnect {
6✔
3678

3✔
3679
                        go s.connectToPersistentPeer(pubStr)
3✔
3680
                } else {
3✔
3681
                        go s.delayInitialReconnect(pubStr)
×
3682
                }
×
3683

3684
                numOutboundConns++
3✔
3685
        }
3686

3687
        return nil
3✔
3688
}
3689

3690
// delayInitialReconnect will attempt a reconnection to the given peer after
3691
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3692
//
3693
// NOTE: This method MUST be run as a goroutine.
3694
func (s *server) delayInitialReconnect(pubStr string) {
×
3695
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3696
        select {
×
3697
        case <-time.After(delay):
×
3698
                s.connectToPersistentPeer(pubStr)
×
3699
        case <-s.quit:
×
3700
        }
3701
}
3702

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

3✔
3709
        s.mu.Lock()
3✔
3710
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3711
                delete(s.persistentPeers, pubKeyStr)
3✔
3712
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3713
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3714
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3715
                s.mu.Unlock()
3✔
3716

3✔
3717
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3718
                        "peer has no open channels", compressedPubKey)
3✔
3719

3✔
3720
                return
3✔
3721
        }
3✔
3722
        s.mu.Unlock()
3✔
3723
}
3724

3725
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3726
// is instead used to remove persistent peer state for a peer that has been
3727
// disconnected for good cause by the server. Currently, a gossip ban from
3728
// sending garbage and the server running out of restricted-access
3729
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3730
// future, this function may expand when more ban criteria is added.
3731
//
3732
// NOTE: The server's write lock MUST be held when this is called.
3733
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3734
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3735
                delete(s.persistentPeers, remotePub)
×
3736
                delete(s.persistentPeersBackoff, remotePub)
×
3737
                delete(s.persistentPeerAddrs, remotePub)
×
3738
                s.cancelConnReqs(remotePub, nil)
×
3739
        }
×
3740
}
3741

3742
// BroadcastMessage sends a request to the server to broadcast a set of
3743
// messages to all peers other than the one specified by the `skips` parameter.
3744
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3745
// the target peers.
3746
//
3747
// NOTE: This function is safe for concurrent access.
3748
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3749
        msgs ...lnwire.Message) error {
3✔
3750

3✔
3751
        // Filter out peers found in the skips map. We synchronize access to
3✔
3752
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3753
        // exact set of peers present at the time of invocation.
3✔
3754
        s.mu.RLock()
3✔
3755
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3756
        for pubStr, sPeer := range s.peersByPub {
6✔
3757
                if skips != nil {
6✔
3758
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3759
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3760
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3761
                                continue
3✔
3762
                        }
3763
                }
3764

3765
                peers = append(peers, sPeer)
3✔
3766
        }
3767
        s.mu.RUnlock()
3✔
3768

3✔
3769
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3770
        // all messages to each of peers.
3✔
3771
        var wg sync.WaitGroup
3✔
3772
        for _, sPeer := range peers {
6✔
3773
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3774
                        sPeer.PubKey())
3✔
3775

3✔
3776
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3777
                wg.Add(1)
3✔
3778
                s.wg.Add(1)
3✔
3779
                go func(p lnpeer.Peer) {
6✔
3780
                        defer s.wg.Done()
3✔
3781
                        defer wg.Done()
3✔
3782

3✔
3783
                        p.SendMessageLazy(false, msgs...)
3✔
3784
                }(sPeer)
3✔
3785
        }
3786

3787
        // Wait for all messages to have been dispatched before returning to
3788
        // caller.
3789
        wg.Wait()
3✔
3790

3✔
3791
        return nil
3✔
3792
}
3793

3794
// NotifyWhenOnline can be called by other subsystems to get notified when a
3795
// particular peer comes online. The peer itself is sent across the peerChan.
3796
//
3797
// NOTE: This function is safe for concurrent access.
3798
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3799
        peerChan chan<- lnpeer.Peer) {
3✔
3800

3✔
3801
        s.mu.Lock()
3✔
3802

3✔
3803
        // Compute the target peer's identifier.
3✔
3804
        pubStr := string(peerKey[:])
3✔
3805

3✔
3806
        // Check if peer is connected.
3✔
3807
        peer, ok := s.peersByPub[pubStr]
3✔
3808
        if ok {
6✔
3809
                // Unlock here so that the mutex isn't held while we are
3✔
3810
                // waiting for the peer to become active.
3✔
3811
                s.mu.Unlock()
3✔
3812

3✔
3813
                // Wait until the peer signals that it is actually active
3✔
3814
                // rather than only in the server's maps.
3✔
3815
                select {
3✔
3816
                case <-peer.ActiveSignal():
3✔
3817
                case <-peer.QuitSignal():
×
3818
                        // The peer quit, so we'll add the channel to the slice
×
3819
                        // and return.
×
3820
                        s.mu.Lock()
×
3821
                        s.peerConnectedListeners[pubStr] = append(
×
3822
                                s.peerConnectedListeners[pubStr], peerChan,
×
3823
                        )
×
3824
                        s.mu.Unlock()
×
3825
                        return
×
3826
                }
3827

3828
                // Connected, can return early.
3829
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3830

3✔
3831
                select {
3✔
3832
                case peerChan <- peer:
3✔
3833
                case <-s.quit:
×
3834
                }
3835

3836
                return
3✔
3837
        }
3838

3839
        // Not connected, store this listener such that it can be notified when
3840
        // the peer comes online.
3841
        s.peerConnectedListeners[pubStr] = append(
3✔
3842
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3843
        )
3✔
3844
        s.mu.Unlock()
3✔
3845
}
3846

3847
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3848
// the given public key has been disconnected. The notification is signaled by
3849
// closing the channel returned.
3850
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3851
        s.mu.Lock()
3✔
3852
        defer s.mu.Unlock()
3✔
3853

3✔
3854
        c := make(chan struct{})
3✔
3855

3✔
3856
        // If the peer is already offline, we can immediately trigger the
3✔
3857
        // notification.
3✔
3858
        peerPubKeyStr := string(peerPubKey[:])
3✔
3859
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3860
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3861
                close(c)
×
3862
                return c
×
3863
        }
×
3864

3865
        // Otherwise, the peer is online, so we'll keep track of the channel to
3866
        // trigger the notification once the server detects the peer
3867
        // disconnects.
3868
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3869
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3870
        )
3✔
3871

3✔
3872
        return c
3✔
3873
}
3874

3875
// FindPeer will return the peer that corresponds to the passed in public key.
3876
// This function is used by the funding manager, allowing it to update the
3877
// daemon's local representation of the remote peer.
3878
//
3879
// NOTE: This function is safe for concurrent access.
3880
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3881
        s.mu.RLock()
3✔
3882
        defer s.mu.RUnlock()
3✔
3883

3✔
3884
        pubStr := string(peerKey.SerializeCompressed())
3✔
3885

3✔
3886
        return s.findPeerByPubStr(pubStr)
3✔
3887
}
3✔
3888

3889
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3890
// which should be a string representation of the peer's serialized, compressed
3891
// public key.
3892
//
3893
// NOTE: This function is safe for concurrent access.
3894
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3895
        s.mu.RLock()
3✔
3896
        defer s.mu.RUnlock()
3✔
3897

3✔
3898
        return s.findPeerByPubStr(pubStr)
3✔
3899
}
3✔
3900

3901
// findPeerByPubStr is an internal method that retrieves the specified peer from
3902
// the server's internal state using.
3903
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3904
        peer, ok := s.peersByPub[pubStr]
3✔
3905
        if !ok {
6✔
3906
                return nil, ErrPeerNotConnected
3✔
3907
        }
3✔
3908

3909
        return peer, nil
3✔
3910
}
3911

3912
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3913
// exponential backoff. If no previous backoff was known, the default is
3914
// returned.
3915
func (s *server) nextPeerBackoff(pubStr string,
3916
        startTime time.Time) time.Duration {
3✔
3917

3✔
3918
        // Now, determine the appropriate backoff to use for the retry.
3✔
3919
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3920
        if !ok {
6✔
3921
                // If an existing backoff was unknown, use the default.
3✔
3922
                return s.cfg.MinBackoff
3✔
3923
        }
3✔
3924

3925
        // If the peer failed to start properly, we'll just use the previous
3926
        // backoff to compute the subsequent randomized exponential backoff
3927
        // duration. This will roughly double on average.
3928
        if startTime.IsZero() {
3✔
3929
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3930
        }
×
3931

3932
        // The peer succeeded in starting. If the connection didn't last long
3933
        // enough to be considered stable, we'll continue to back off retries
3934
        // with this peer.
3935
        connDuration := time.Since(startTime)
3✔
3936
        if connDuration < defaultStableConnDuration {
6✔
3937
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3938
        }
3✔
3939

3940
        // The peer succeed in starting and this was stable peer, so we'll
3941
        // reduce the timeout duration by the length of the connection after
3942
        // applying randomized exponential backoff. We'll only apply this in the
3943
        // case that:
3944
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3945
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3946
        if relaxedBackoff > s.cfg.MinBackoff {
×
3947
                return relaxedBackoff
×
3948
        }
×
3949

3950
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3951
        // the stable connection lasted much longer than our previous backoff.
3952
        // To reward such good behavior, we'll reconnect after the default
3953
        // timeout.
3954
        return s.cfg.MinBackoff
×
3955
}
3956

3957
// shouldDropLocalConnection determines if our local connection to a remote peer
3958
// should be dropped in the case of concurrent connection establishment. In
3959
// order to deterministically decide which connection should be dropped, we'll
3960
// utilize the ordering of the local and remote public key. If we didn't use
3961
// such a tie breaker, then we risk _both_ connections erroneously being
3962
// dropped.
3963
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3964
        localPubBytes := local.SerializeCompressed()
×
3965
        remotePubPbytes := remote.SerializeCompressed()
×
3966

×
3967
        // The connection that comes from the node with a "smaller" pubkey
×
3968
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3969
        // should drop our established connection.
×
3970
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3971
}
×
3972

3973
// InboundPeerConnected initializes a new peer in response to a new inbound
3974
// connection.
3975
//
3976
// NOTE: This function is safe for concurrent access.
3977
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3978
        // Exit early if we have already been instructed to shutdown, this
3✔
3979
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3980
        if s.Stopped() {
3✔
3981
                return
×
3982
        }
×
3983

3984
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3985
        pubSer := nodePub.SerializeCompressed()
3✔
3986
        pubStr := string(pubSer)
3✔
3987

3✔
3988
        var pubBytes [33]byte
3✔
3989
        copy(pubBytes[:], pubSer)
3✔
3990

3✔
3991
        s.mu.Lock()
3✔
3992
        defer s.mu.Unlock()
3✔
3993

3✔
3994
        // If we already have an outbound connection to this peer, then ignore
3✔
3995
        // this new connection.
3✔
3996
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3997
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3998
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3999
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4000

3✔
4001
                conn.Close()
3✔
4002
                return
3✔
4003
        }
3✔
4004

4005
        // If we already have a valid connection that is scheduled to take
4006
        // precedence once the prior peer has finished disconnecting, we'll
4007
        // ignore this connection.
4008
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4009
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4010
                        "scheduled", conn.RemoteAddr(), p)
×
4011
                conn.Close()
×
4012
                return
×
4013
        }
×
4014

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

3✔
4017
        // Check to see if we already have a connection with this peer. If so,
3✔
4018
        // we may need to drop our existing connection. This prevents us from
3✔
4019
        // having duplicate connections to the same peer. We forgo adding a
3✔
4020
        // default case as we expect these to be the only error values returned
3✔
4021
        // from findPeerByPubStr.
3✔
4022
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4023
        switch err {
3✔
4024
        case ErrPeerNotConnected:
3✔
4025
                // We were unable to locate an existing connection with the
3✔
4026
                // target peer, proceed to connect.
3✔
4027
                s.cancelConnReqs(pubStr, nil)
3✔
4028
                s.peerConnected(conn, nil, true)
3✔
4029

4030
        case nil:
3✔
4031
                ctx := btclog.WithCtx(
3✔
4032
                        context.TODO(),
3✔
4033
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4034
                )
3✔
4035

3✔
4036
                // We already have a connection with the incoming peer. If the
3✔
4037
                // connection we've already established should be kept and is
3✔
4038
                // not of the same type of the new connection (inbound), then
3✔
4039
                // we'll close out the new connection s.t there's only a single
3✔
4040
                // connection between us.
3✔
4041
                localPub := s.identityECDH.PubKey()
3✔
4042
                if !connectedPeer.Inbound() &&
3✔
4043
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4044

×
4045
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4046
                                "peer, but already have outbound "+
×
4047
                                "connection, dropping conn",
×
4048
                                fmt.Errorf("already have outbound conn"))
×
4049
                        conn.Close()
×
4050
                        return
×
4051
                }
×
4052

4053
                // Otherwise, if we should drop the connection, then we'll
4054
                // disconnect our already connected peer.
4055
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4056

3✔
4057
                s.cancelConnReqs(pubStr, nil)
3✔
4058

3✔
4059
                // Remove the current peer from the server's internal state and
3✔
4060
                // signal that the peer termination watcher does not need to
3✔
4061
                // execute for this peer.
3✔
4062
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4063
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4064
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4065
                        s.peerConnected(conn, nil, true)
3✔
4066
                }
3✔
4067
        }
4068
}
4069

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

4080
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4081
        pubSer := nodePub.SerializeCompressed()
3✔
4082
        pubStr := string(pubSer)
3✔
4083

3✔
4084
        var pubBytes [33]byte
3✔
4085
        copy(pubBytes[:], pubSer)
3✔
4086

3✔
4087
        s.mu.Lock()
3✔
4088
        defer s.mu.Unlock()
3✔
4089

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

3✔
4097
                if connReq != nil {
6✔
4098
                        s.connMgr.Remove(connReq.ID())
3✔
4099
                }
3✔
4100
                conn.Close()
3✔
4101
                return
3✔
4102
        }
4103
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4104
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4105
                s.connMgr.Remove(connReq.ID())
×
4106
                conn.Close()
×
4107
                return
×
4108
        }
×
4109

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

×
4116
                if connReq != nil {
×
4117
                        s.connMgr.Remove(connReq.ID())
×
4118
                }
×
4119

4120
                conn.Close()
×
4121
                return
×
4122
        }
4123

4124
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4125
                conn.RemoteAddr())
3✔
4126

3✔
4127
        if connReq != nil {
6✔
4128
                // A successful connection was returned by the connmgr.
3✔
4129
                // Immediately cancel all pending requests, excluding the
3✔
4130
                // outbound connection we just established.
3✔
4131
                ignore := connReq.ID()
3✔
4132
                s.cancelConnReqs(pubStr, &ignore)
3✔
4133
        } else {
6✔
4134
                // This was a successful connection made by some other
3✔
4135
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4136
                s.cancelConnReqs(pubStr, nil)
3✔
4137
        }
3✔
4138

4139
        // If we already have a connection with this peer, decide whether or not
4140
        // we need to drop the stale connection. We forgo adding a default case
4141
        // as we expect these to be the only error values returned from
4142
        // findPeerByPubStr.
4143
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4144
        switch err {
3✔
4145
        case ErrPeerNotConnected:
3✔
4146
                // We were unable to locate an existing connection with the
3✔
4147
                // target peer, proceed to connect.
3✔
4148
                s.peerConnected(conn, connReq, false)
3✔
4149

4150
        case nil:
3✔
4151
                ctx := btclog.WithCtx(
3✔
4152
                        context.TODO(),
3✔
4153
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4154
                )
3✔
4155

3✔
4156
                // We already have a connection with the incoming peer. If the
3✔
4157
                // connection we've already established should be kept and is
3✔
4158
                // not of the same type of the new connection (outbound), then
3✔
4159
                // we'll close out the new connection s.t there's only a single
3✔
4160
                // connection between us.
3✔
4161
                localPub := s.identityECDH.PubKey()
3✔
4162
                if connectedPeer.Inbound() &&
3✔
4163
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4164

×
4165
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4166
                                "to peer, but already have inbound "+
×
4167
                                "connection, dropping conn",
×
4168
                                fmt.Errorf("already have inbound conn"))
×
4169
                        if connReq != nil {
×
4170
                                s.connMgr.Remove(connReq.ID())
×
4171
                        }
×
4172
                        conn.Close()
×
4173
                        return
×
4174
                }
4175

4176
                // Otherwise, _their_ connection should be dropped. So we'll
4177
                // disconnect the peer and send the now obsolete peer to the
4178
                // server for garbage collection.
4179
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4180

3✔
4181
                // Remove the current peer from the server's internal state and
3✔
4182
                // signal that the peer termination watcher does not need to
3✔
4183
                // execute for this peer.
3✔
4184
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4185
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4186
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4187
                        s.peerConnected(conn, connReq, false)
3✔
4188
                }
3✔
4189
        }
4190
}
4191

4192
// UnassignedConnID is the default connection ID that a request can have before
4193
// it actually is submitted to the connmgr.
4194
// TODO(conner): move into connmgr package, or better, add connmgr method for
4195
// generating atomic IDs
4196
const UnassignedConnID uint64 = 0
4197

4198
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4199
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4200
// Afterwards, each connection request removed from the connmgr. The caller can
4201
// optionally specify a connection ID to ignore, which prevents us from
4202
// canceling a successful request. All persistent connreqs for the provided
4203
// pubkey are discarded after the operationjw.
4204
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4205
        // First, cancel any lingering persistent retry attempts, which will
3✔
4206
        // prevent retries for any with backoffs that are still maturing.
3✔
4207
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4208
                close(cancelChan)
3✔
4209
                delete(s.persistentRetryCancels, pubStr)
3✔
4210
        }
3✔
4211

4212
        // Next, check to see if we have any outstanding persistent connection
4213
        // requests to this peer. If so, then we'll remove all of these
4214
        // connection requests, and also delete the entry from the map.
4215
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4216
        if !ok {
6✔
4217
                return
3✔
4218
        }
3✔
4219

4220
        for _, connReq := range connReqs {
6✔
4221
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4222

3✔
4223
                // Atomically capture the current request identifier.
3✔
4224
                connID := connReq.ID()
3✔
4225

3✔
4226
                // Skip any zero IDs, this indicates the request has not
3✔
4227
                // yet been schedule.
3✔
4228
                if connID == UnassignedConnID {
3✔
4229
                        continue
×
4230
                }
4231

4232
                // Skip a particular connection ID if instructed.
4233
                if skip != nil && connID == *skip {
6✔
4234
                        continue
3✔
4235
                }
4236

4237
                s.connMgr.Remove(connID)
3✔
4238
        }
4239

4240
        delete(s.persistentConnReqs, pubStr)
3✔
4241
}
4242

4243
// handleCustomMessage dispatches an incoming custom peers message to
4244
// subscribers.
4245
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4246
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4247
                peer, msg.Type)
3✔
4248

3✔
4249
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4250
                Peer: peer,
3✔
4251
                Msg:  msg,
3✔
4252
        })
3✔
4253
}
3✔
4254

4255
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4256
// messages.
4257
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4258
        return s.customMessageServer.Subscribe()
3✔
4259
}
3✔
4260

4261
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4262
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4263
        return s.onionMessageServer.Subscribe()
3✔
4264
}
3✔
4265

4266
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4267
// the channelNotifier's NotifyOpenChannelEvent.
4268
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4269
        remotePub *btcec.PublicKey) {
3✔
4270

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

4277
        // Notify subscribers about this open channel event.
4278
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4279
}
4280

4281
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4282
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4283
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4284
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4285

3✔
4286
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4287
        // peer.
3✔
4288
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4289
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4290
                        "channel[%v] pending open",
×
4291
                        remotePub.SerializeCompressed(), op)
×
4292
        }
×
4293

4294
        // Notify subscribers about this event.
4295
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4296
}
4297

4298
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4299
// calls the channelNotifier's NotifyFundingTimeout.
4300
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4301
        remotePub *btcec.PublicKey) {
3✔
4302

3✔
4303
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4304
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4305
        if err != nil {
3✔
4306
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4307
                        "channel[%v] pending close",
×
4308
                        remotePub.SerializeCompressed(), op)
×
4309
        }
×
4310

4311
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4312
                // If we encounter an error while attempting to disconnect the
×
4313
                // peer, log the error.
×
4314
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4315
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4316
                }
×
4317
        }
4318

4319
        // Notify subscribers about this event.
4320
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4321
}
4322

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

3✔
4330
        brontideConn := conn.(*brontide.Conn)
3✔
4331
        addr := conn.RemoteAddr()
3✔
4332
        pubKey := brontideConn.RemotePub()
3✔
4333

3✔
4334
        // Only restrict access for inbound connections, which means if the
3✔
4335
        // remote node's public key is banned or the restricted slots are used
3✔
4336
        // up, we will drop the connection.
3✔
4337
        //
3✔
4338
        // TODO(yy): Consider perform this check in
3✔
4339
        // `peerAccessMan.addPeerAccess`.
3✔
4340
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4341
        if inbound && err != nil {
3✔
4342
                pubSer := pubKey.SerializeCompressed()
×
4343

×
4344
                // Clean up the persistent peer maps if we're dropping this
×
4345
                // connection.
×
4346
                s.bannedPersistentPeerConnection(string(pubSer))
×
4347

×
4348
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4349
                        "of restricted-access connection slots: %v.", pubSer,
×
4350
                        err)
×
4351

×
4352
                conn.Close()
×
4353

×
4354
                return
×
4355
        }
×
4356

4357
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4358
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4359

3✔
4360
        peerAddr := &lnwire.NetAddress{
3✔
4361
                IdentityKey: pubKey,
3✔
4362
                Address:     addr,
3✔
4363
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4364
        }
3✔
4365

3✔
4366
        // With the brontide connection established, we'll now craft the feature
3✔
4367
        // vectors to advertise to the remote node.
3✔
4368
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4369
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4370

3✔
4371
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4372
        // found, create a fresh buffer.
3✔
4373
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4374
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4375
        if !ok {
6✔
4376
                var err error
3✔
4377
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4378
                if err != nil {
3✔
4379
                        srvrLog.Errorf("unable to create peer %v", err)
×
4380
                        return
×
4381
                }
×
4382
        }
4383

4384
        // If we directly set the peer.Config TowerClient member to the
4385
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4386
        // the peer.Config's TowerClient member will not evaluate to nil even
4387
        // though the underlying value is nil. To avoid this gotcha which can
4388
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4389
        // TowerClient if needed.
4390
        var towerClient wtclient.ClientManager
3✔
4391
        if s.towerClientMgr != nil {
6✔
4392
                towerClient = s.towerClientMgr
3✔
4393
        }
3✔
4394

4395
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4396
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4397

3✔
4398
        // Now that we've established a connection, create a peer, and it to the
3✔
4399
        // set of currently active peers. Configure the peer with the incoming
3✔
4400
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4401
        // offered that would trigger channel closure. In case of outgoing
3✔
4402
        // htlcs, an extra block is added to prevent the channel from being
3✔
4403
        // closed when the htlc is outstanding and a new block comes in.
3✔
4404
        pCfg := peer.Config{
3✔
4405
                Conn:                    brontideConn,
3✔
4406
                ConnReq:                 connReq,
3✔
4407
                Addr:                    peerAddr,
3✔
4408
                Inbound:                 inbound,
3✔
4409
                Features:                initFeatures,
3✔
4410
                LegacyFeatures:          legacyFeatures,
3✔
4411
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4412
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4413
                ErrorBuffer:             errBuffer,
3✔
4414
                WritePool:               s.writePool,
3✔
4415
                ReadPool:                s.readPool,
3✔
4416
                Switch:                  s.htlcSwitch,
3✔
4417
                InterceptSwitch:         s.interceptableSwitch,
3✔
4418
                ChannelDB:               s.chanStateDB,
3✔
4419
                ChannelGraph:            s.graphDB,
3✔
4420
                ChainArb:                s.chainArb,
3✔
4421
                AuthGossiper:            s.authGossiper,
3✔
4422
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4423
                ChainIO:                 s.cc.ChainIO,
3✔
4424
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4425
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4426
                SigPool:                 s.sigPool,
3✔
4427
                Wallet:                  s.cc.Wallet,
3✔
4428
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4429
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4430
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4431
                Sphinx:                  s.sphinx,
3✔
4432
                SphinxRouterNoReplayLog: s.sphinxRouterNoReplayLog,
3✔
4433
                WitnessBeacon:           s.witnessBeacon,
3✔
4434
                Invoices:                s.invoices,
3✔
4435
                ChannelNotifier:         s.channelNotifier,
3✔
4436
                HtlcNotifier:            s.htlcNotifier,
3✔
4437
                TowerClient:             towerClient,
3✔
4438
                DisconnectPeer:          s.DisconnectPeer,
3✔
4439
                OnionMessageServer:      s.onionMessageServer,
3✔
4440
                ActorSystem:             s.actorSystem,
3✔
4441
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4442
                        lnwire.NodeAnnouncement1, error) {
6✔
4443

3✔
4444
                        return s.genNodeAnnouncement(nil)
3✔
4445
                },
3✔
4446

4447
                PongBuf: s.pongBuf,
4448

4449
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4450

4451
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4452

4453
                FundingManager: s.fundingMgr,
4454

4455
                Hodl:                    s.cfg.Hodl,
4456
                UnsafeReplay:            s.cfg.UnsafeReplay,
4457
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4458
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4459
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4460
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4461
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4462
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4463
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4464
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4465
                HandleCustomMessage:    s.handleCustomMessage,
4466
                GetAliases:             s.aliasMgr.GetAliases,
4467
                RequestAlias:           s.aliasMgr.RequestAlias,
4468
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4469
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4470
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4471
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4472
                MaxFeeExposure:         thresholdMSats,
4473
                Quit:                   s.quit,
4474
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4475
                AuxSigner:              s.implCfg.AuxSigner,
4476
                MsgRouter:              s.implCfg.MsgRouter,
4477
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4478
                AuxResolver:            s.implCfg.AuxContractResolver,
4479
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4480
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4481
                ShouldFwdExpEndorsement: func() bool {
3✔
4482
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4483
                                return false
3✔
4484
                        }
3✔
4485

4486
                        return clock.NewDefaultClock().Now().Before(
3✔
4487
                                EndorsementExperimentEnd,
3✔
4488
                        )
3✔
4489
                },
4490
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4491
        }
4492

4493
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4494
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4495

3✔
4496
        p := peer.NewBrontide(pCfg)
3✔
4497

3✔
4498
        // Update the access manager with the access permission for this peer.
3✔
4499
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4500

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

3✔
4504
        s.addPeer(p)
3✔
4505

3✔
4506
        // Once we have successfully added the peer to the server, we can
3✔
4507
        // delete the previous error buffer from the server's map of error
3✔
4508
        // buffers.
3✔
4509
        delete(s.peerErrors, pkStr)
3✔
4510

3✔
4511
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4512
        // includes sending and receiving Init messages, which would be a DOS
3✔
4513
        // vector if we held the server's mutex throughout the procedure.
3✔
4514
        s.wg.Add(1)
3✔
4515
        go s.peerInitializer(p)
3✔
4516
}
4517

4518
// addPeer adds the passed peer to the server's global state of all active
4519
// peers.
4520
func (s *server) addPeer(p *peer.Brontide) {
3✔
4521
        if p == nil {
3✔
4522
                return
×
4523
        }
×
4524

4525
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4526

3✔
4527
        // Ignore new peers if we're shutting down.
3✔
4528
        if s.Stopped() {
3✔
4529
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4530
                        pubBytes)
×
4531
                p.Disconnect(ErrServerShuttingDown)
×
4532

×
4533
                return
×
4534
        }
×
4535

4536
        // Track the new peer in our indexes so we can quickly look it up either
4537
        // according to its public key, or its peer ID.
4538
        // TODO(roasbeef): pipe all requests through to the
4539
        // queryHandler/peerManager
4540

4541
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4542
        // be human-readable.
4543
        pubStr := string(pubBytes)
3✔
4544

3✔
4545
        s.peersByPub[pubStr] = p
3✔
4546

3✔
4547
        if p.Inbound() {
6✔
4548
                s.inboundPeers[pubStr] = p
3✔
4549
        } else {
6✔
4550
                s.outboundPeers[pubStr] = p
3✔
4551
        }
3✔
4552

4553
        // Inform the peer notifier of a peer online event so that it can be reported
4554
        // to clients listening for peer events.
4555
        var pubKey [33]byte
3✔
4556
        copy(pubKey[:], pubBytes)
3✔
4557
}
4558

4559
// peerInitializer asynchronously starts a newly connected peer after it has
4560
// been added to the server's peer map. This method sets up a
4561
// peerTerminationWatcher for the given peer, and ensures that it executes even
4562
// if the peer failed to start. In the event of a successful connection, this
4563
// method reads the negotiated, local feature-bits and spawns the appropriate
4564
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4565
// be signaled of the new peer once the method returns.
4566
//
4567
// NOTE: This MUST be launched as a goroutine.
4568
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4569
        defer s.wg.Done()
3✔
4570

3✔
4571
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4572

3✔
4573
        // Avoid initializing peers while the server is exiting.
3✔
4574
        if s.Stopped() {
3✔
4575
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4576
                        pubBytes)
×
4577
                return
×
4578
        }
×
4579

4580
        // Create a channel that will be used to signal a successful start of
4581
        // the link. This prevents the peer termination watcher from beginning
4582
        // its duty too early.
4583
        ready := make(chan struct{})
3✔
4584

3✔
4585
        // Before starting the peer, launch a goroutine to watch for the
3✔
4586
        // unexpected termination of this peer, which will ensure all resources
3✔
4587
        // are properly cleaned up, and re-establish persistent connections when
3✔
4588
        // necessary. The peer termination watcher will be short circuited if
3✔
4589
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4590
        // that the server has already handled the removal of this peer.
3✔
4591
        s.wg.Add(1)
3✔
4592
        go s.peerTerminationWatcher(p, ready)
3✔
4593

3✔
4594
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4595
        // will unblock the peerTerminationWatcher.
3✔
4596
        if err := p.Start(); err != nil {
6✔
4597
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4598

3✔
4599
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4600
                return
3✔
4601
        }
3✔
4602

4603
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4604
        // was successful, and to begin watching the peer's wait group.
4605
        close(ready)
3✔
4606

3✔
4607
        s.mu.Lock()
3✔
4608
        defer s.mu.Unlock()
3✔
4609

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

3✔
4613
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4614
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4615
        pubStr := string(pubBytes)
3✔
4616
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4617
                select {
3✔
4618
                case peerChan <- p:
3✔
4619
                case <-s.quit:
×
4620
                        return
×
4621
                }
4622
        }
4623
        delete(s.peerConnectedListeners, pubStr)
3✔
4624

3✔
4625
        // Since the peer has been fully initialized, now it's time to notify
3✔
4626
        // the RPC about the peer online event.
3✔
4627
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4628
}
4629

4630
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4631
// and then cleans up all resources allocated to the peer, notifies relevant
4632
// sub-systems of its demise, and finally handles re-connecting to the peer if
4633
// it's persistent. If the server intentionally disconnects a peer, it should
4634
// have a corresponding entry in the ignorePeerTermination map which will cause
4635
// the cleanup routine to exit early. The passed `ready` chan is used to
4636
// synchronize when WaitForDisconnect should begin watching on the peer's
4637
// waitgroup. The ready chan should only be signaled if the peer starts
4638
// successfully, otherwise the peer should be disconnected instead.
4639
//
4640
// NOTE: This MUST be launched as a goroutine.
4641
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4642
        defer s.wg.Done()
3✔
4643

3✔
4644
        ctx := btclog.WithCtx(
3✔
4645
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4646
        )
3✔
4647

3✔
4648
        p.WaitForDisconnect(ready)
3✔
4649

3✔
4650
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4651

3✔
4652
        // If the server is exiting then we can bail out early ourselves as all
3✔
4653
        // the other sub-systems will already be shutting down.
3✔
4654
        if s.Stopped() {
6✔
4655
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4656
                return
3✔
4657
        }
3✔
4658

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

3✔
4665
        pubKey := p.IdentityKey()
3✔
4666

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

3✔
4671
        // Tell the switch to remove all links associated with this peer.
3✔
4672
        // Passing nil as the target link indicates that all links associated
3✔
4673
        // with this interface should be closed.
3✔
4674
        //
3✔
4675
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4676
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4677
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4678
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4679
        }
×
4680

4681
        for _, link := range links {
6✔
4682
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4683
        }
3✔
4684

4685
        s.mu.Lock()
3✔
4686
        defer s.mu.Unlock()
3✔
4687

3✔
4688
        // If there were any notification requests for when this peer
3✔
4689
        // disconnected, we can trigger them now.
3✔
4690
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4691
        pubStr := string(pubKey.SerializeCompressed())
3✔
4692
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4693
                close(offlineChan)
3✔
4694
        }
3✔
4695
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4696

3✔
4697
        // If the server has already removed this peer, we can short circuit the
3✔
4698
        // peer termination watcher and skip cleanup.
3✔
4699
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4700
                delete(s.ignorePeerTermination, p)
3✔
4701

3✔
4702
                pubKey := p.PubKey()
3✔
4703
                pubStr := string(pubKey[:])
3✔
4704

3✔
4705
                // If a connection callback is present, we'll go ahead and
3✔
4706
                // execute it now that previous peer has fully disconnected. If
3✔
4707
                // the callback is not present, this likely implies the peer was
3✔
4708
                // purposefully disconnected via RPC, and that no reconnect
3✔
4709
                // should be attempted.
3✔
4710
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4711
                if ok {
6✔
4712
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4713
                        connCallback()
3✔
4714
                }
3✔
4715
                return
3✔
4716
        }
4717

4718
        // First, cleanup any remaining state the server has regarding the peer
4719
        // in question.
4720
        s.removePeerUnsafe(ctx, p)
3✔
4721

3✔
4722
        // Next, check to see if this is a persistent peer or not.
3✔
4723
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4724
                return
3✔
4725
        }
3✔
4726

4727
        // Get the last address that we used to connect to the peer.
4728
        addrs := []net.Addr{
3✔
4729
                p.NetAddress().Address,
3✔
4730
        }
3✔
4731

3✔
4732
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4733
        // reconnection purposes.
3✔
4734
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4735
        switch {
3✔
4736
        // We found advertised addresses, so use them.
4737
        case err == nil:
3✔
4738
                addrs = advertisedAddrs
3✔
4739

4740
        // The peer doesn't have an advertised address.
4741
        case err == errNoAdvertisedAddr:
3✔
4742
                // If it is an outbound peer then we fall back to the existing
3✔
4743
                // peer address.
3✔
4744
                if !p.Inbound() {
6✔
4745
                        break
3✔
4746
                }
4747

4748
                // Fall back to the existing peer address if
4749
                // we're not accepting connections over Tor.
4750
                if s.torController == nil {
6✔
4751
                        break
3✔
4752
                }
4753

4754
                // If we are, the peer's address won't be known
4755
                // to us (we'll see a private address, which is
4756
                // the address used by our onion service to dial
4757
                // to lnd), so we don't have enough information
4758
                // to attempt a reconnect.
4759
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4760
                        "to inbound peer without advertised address")
×
4761
                return
×
4762

4763
        // We came across an error retrieving an advertised
4764
        // address, log it, and fall back to the existing peer
4765
        // address.
4766
        default:
3✔
4767
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4768
                        "address for peer", err)
3✔
4769
        }
4770

4771
        // Make an easy lookup map so that we can check if an address
4772
        // is already in the address list that we have stored for this peer.
4773
        existingAddrs := make(map[string]bool)
3✔
4774
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4775
                existingAddrs[addr.String()] = true
3✔
4776
        }
3✔
4777

4778
        // Add any missing addresses for this peer to persistentPeerAddr.
4779
        for _, addr := range addrs {
6✔
4780
                if existingAddrs[addr.String()] {
3✔
4781
                        continue
×
4782
                }
4783

4784
                s.persistentPeerAddrs[pubStr] = append(
3✔
4785
                        s.persistentPeerAddrs[pubStr],
3✔
4786
                        &lnwire.NetAddress{
3✔
4787
                                IdentityKey: p.IdentityKey(),
3✔
4788
                                Address:     addr,
3✔
4789
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4790
                        },
3✔
4791
                )
3✔
4792
        }
4793

4794
        // Record the computed backoff in the backoff map.
4795
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4796
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4797

3✔
4798
        // Initialize a retry canceller for this peer if one does not
3✔
4799
        // exist.
3✔
4800
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4801
        if !ok {
6✔
4802
                cancelChan = make(chan struct{})
3✔
4803
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4804
        }
3✔
4805

4806
        // We choose not to wait group this go routine since the Connect
4807
        // call can stall for arbitrarily long if we shutdown while an
4808
        // outbound connection attempt is being made.
4809
        go func() {
6✔
4810
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4811
                        "re-establishment to persistent peer",
3✔
4812
                        "reconnecting_in", backoff)
3✔
4813

3✔
4814
                select {
3✔
4815
                case <-time.After(backoff):
3✔
4816
                case <-cancelChan:
3✔
4817
                        return
3✔
4818
                case <-s.quit:
3✔
4819
                        return
3✔
4820
                }
4821

4822
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4823
                        "connection")
3✔
4824

3✔
4825
                s.connectToPersistentPeer(pubStr)
3✔
4826
        }()
4827
}
4828

4829
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4830
// to connect to the peer. It creates connection requests if there are
4831
// currently none for a given address and it removes old connection requests
4832
// if the associated address is no longer in the latest address list for the
4833
// peer.
4834
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4835
        s.mu.Lock()
3✔
4836
        defer s.mu.Unlock()
3✔
4837

3✔
4838
        // Create an easy lookup map of the addresses we have stored for the
3✔
4839
        // peer. We will remove entries from this map if we have existing
3✔
4840
        // connection requests for the associated address and then any leftover
3✔
4841
        // entries will indicate which addresses we should create new
3✔
4842
        // connection requests for.
3✔
4843
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4844
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4845
                addrMap[addr.String()] = addr
3✔
4846
        }
3✔
4847

4848
        // Go through each of the existing connection requests and
4849
        // check if they correspond to the latest set of addresses. If
4850
        // there is a connection requests that does not use one of the latest
4851
        // advertised addresses then remove that connection request.
4852
        var updatedConnReqs []*connmgr.ConnReq
3✔
4853
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4854
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4855

3✔
4856
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4857
                // If the existing connection request is using one of the
4858
                // latest advertised addresses for the peer then we add it to
4859
                // updatedConnReqs and remove the associated address from
4860
                // addrMap so that we don't recreate this connReq later on.
4861
                case true:
×
4862
                        updatedConnReqs = append(
×
4863
                                updatedConnReqs, connReq,
×
4864
                        )
×
4865
                        delete(addrMap, lnAddr)
×
4866

4867
                // If the existing connection request is using an address that
4868
                // is not one of the latest advertised addresses for the peer
4869
                // then we remove the connecting request from the connection
4870
                // manager.
4871
                case false:
3✔
4872
                        srvrLog.Info(
3✔
4873
                                "Removing conn req:", connReq.Addr.String(),
3✔
4874
                        )
3✔
4875
                        s.connMgr.Remove(connReq.ID())
3✔
4876
                }
4877
        }
4878

4879
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4880

3✔
4881
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4882
        if !ok {
6✔
4883
                cancelChan = make(chan struct{})
3✔
4884
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4885
        }
3✔
4886

4887
        // Any addresses left in addrMap are new ones that we have not made
4888
        // connection requests for. So create new connection requests for those.
4889
        // If there is more than one address in the address map, stagger the
4890
        // creation of the connection requests for those.
4891
        go func() {
6✔
4892
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4893
                defer ticker.Stop()
3✔
4894

3✔
4895
                for _, addr := range addrMap {
6✔
4896
                        // Send the persistent connection request to the
3✔
4897
                        // connection manager, saving the request itself so we
3✔
4898
                        // can cancel/restart the process as needed.
3✔
4899
                        connReq := &connmgr.ConnReq{
3✔
4900
                                Addr:      addr,
3✔
4901
                                Permanent: true,
3✔
4902
                        }
3✔
4903

3✔
4904
                        s.mu.Lock()
3✔
4905
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4906
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4907
                        )
3✔
4908
                        s.mu.Unlock()
3✔
4909

3✔
4910
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4911
                                "channel peer %v", addr)
3✔
4912

3✔
4913
                        go s.connMgr.Connect(connReq)
3✔
4914

3✔
4915
                        select {
3✔
4916
                        case <-s.quit:
3✔
4917
                                return
3✔
4918
                        case <-cancelChan:
3✔
4919
                                return
3✔
4920
                        case <-ticker.C:
3✔
4921
                        }
4922
                }
4923
        }()
4924
}
4925

4926
// removePeerUnsafe removes the passed peer from the server's state of all
4927
// active peers.
4928
//
4929
// NOTE: Server mutex must be held when calling this function.
4930
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
4931
        if p == nil {
3✔
4932
                return
×
4933
        }
×
4934

4935
        srvrLog.DebugS(ctx, "Removing peer")
3✔
4936

3✔
4937
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4938
        // will be disconnected in the server shutdown process.
3✔
4939
        if s.Stopped() {
3✔
4940
                return
×
4941
        }
×
4942

4943
        // Capture the peer's public key and string representation.
4944
        pKey := p.PubKey()
3✔
4945
        pubSer := pKey[:]
3✔
4946
        pubStr := string(pubSer)
3✔
4947

3✔
4948
        delete(s.peersByPub, pubStr)
3✔
4949

3✔
4950
        if p.Inbound() {
6✔
4951
                delete(s.inboundPeers, pubStr)
3✔
4952
        } else {
6✔
4953
                delete(s.outboundPeers, pubStr)
3✔
4954
        }
3✔
4955

4956
        // When removing the peer we make sure to disconnect it asynchronously
4957
        // to avoid blocking the main server goroutine because it is holding the
4958
        // server's mutex. Disconnecting the peer might block and wait until the
4959
        // peer has fully started up. This can happen if an inbound and outbound
4960
        // race condition occurs.
4961
        s.wg.Add(1)
3✔
4962
        go func() {
6✔
4963
                defer s.wg.Done()
3✔
4964

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

3✔
4967
                // If this peer had an active persistent connection request,
3✔
4968
                // remove it.
3✔
4969
                if p.ConnReq() != nil {
6✔
4970
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
4971
                }
3✔
4972

4973
                // Remove the peer's access permission from the access manager.
4974
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
4975
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
4976

3✔
4977
                // Copy the peer's error buffer across to the server if it has
3✔
4978
                // any items in it so that we can restore peer errors across
3✔
4979
                // connections. We need to look up the error after the peer has
3✔
4980
                // been disconnected because we write the error in the
3✔
4981
                // `Disconnect` method.
3✔
4982
                s.mu.Lock()
3✔
4983
                if p.ErrorBuffer().Total() > 0 {
6✔
4984
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4985
                }
3✔
4986
                s.mu.Unlock()
3✔
4987

3✔
4988
                // Inform the peer notifier of a peer offline event so that it
3✔
4989
                // can be reported to clients listening for peer events.
3✔
4990
                var pubKey [33]byte
3✔
4991
                copy(pubKey[:], pubSer)
3✔
4992

3✔
4993
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4994
        }()
4995
}
4996

4997
// ConnectToPeer requests that the server connect to a Lightning Network peer
4998
// at the specified address. This function will *block* until either a
4999
// connection is established, or the initial handshake process fails.
5000
//
5001
// NOTE: This function is safe for concurrent access.
5002
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5003
        perm bool, timeout time.Duration) error {
3✔
5004

3✔
5005
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5006

3✔
5007
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5008
        // better granularity.  In certain conditions, this method requires
3✔
5009
        // making an outbound connection to a remote peer, which requires the
3✔
5010
        // lock to be released, and subsequently reacquired.
3✔
5011
        s.mu.Lock()
3✔
5012

3✔
5013
        // Ensure we're not already connected to this peer.
3✔
5014
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5015

3✔
5016
        // When there's no error it means we already have a connection with this
3✔
5017
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5018
        // set, we will ignore the existing connection and continue.
3✔
5019
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5020
                s.mu.Unlock()
3✔
5021
                return &errPeerAlreadyConnected{peer: peer}
3✔
5022
        }
3✔
5023

5024
        // Peer was not found, continue to pursue connection with peer.
5025

5026
        // If there's already a pending connection request for this pubkey,
5027
        // then we ignore this request to ensure we don't create a redundant
5028
        // connection.
5029
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5030
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5031
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5032
        }
3✔
5033

5034
        // If there's not already a pending or active connection to this node,
5035
        // then instruct the connection manager to attempt to establish a
5036
        // persistent connection to the peer.
5037
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5038
        if perm {
6✔
5039
                connReq := &connmgr.ConnReq{
3✔
5040
                        Addr:      addr,
3✔
5041
                        Permanent: true,
3✔
5042
                }
3✔
5043

3✔
5044
                // Since the user requested a permanent connection, we'll set
3✔
5045
                // the entry to true which will tell the server to continue
3✔
5046
                // reconnecting even if the number of channels with this peer is
3✔
5047
                // zero.
3✔
5048
                s.persistentPeers[targetPub] = true
3✔
5049
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5050
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5051
                }
3✔
5052
                s.persistentConnReqs[targetPub] = append(
3✔
5053
                        s.persistentConnReqs[targetPub], connReq,
3✔
5054
                )
3✔
5055
                s.mu.Unlock()
3✔
5056

3✔
5057
                go s.connMgr.Connect(connReq)
3✔
5058

3✔
5059
                return nil
3✔
5060
        }
5061
        s.mu.Unlock()
3✔
5062

3✔
5063
        // If we're not making a persistent connection, then we'll attempt to
3✔
5064
        // connect to the target peer. If the we can't make the connection, or
3✔
5065
        // the crypto negotiation breaks down, then return an error to the
3✔
5066
        // caller.
3✔
5067
        errChan := make(chan error, 1)
3✔
5068
        s.connectToPeer(addr, errChan, timeout)
3✔
5069

3✔
5070
        select {
3✔
5071
        case err := <-errChan:
3✔
5072
                return err
3✔
5073
        case <-s.quit:
×
5074
                return ErrServerShuttingDown
×
5075
        }
5076
}
5077

5078
// connectToPeer establishes a connection to a remote peer. errChan is used to
5079
// notify the caller if the connection attempt has failed. Otherwise, it will be
5080
// closed.
5081
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5082
        errChan chan<- error, timeout time.Duration) {
3✔
5083

3✔
5084
        conn, err := brontide.Dial(
3✔
5085
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5086
        )
3✔
5087
        if err != nil {
6✔
5088
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5089
                select {
3✔
5090
                case errChan <- err:
3✔
5091
                case <-s.quit:
×
5092
                }
5093
                return
3✔
5094
        }
5095

5096
        close(errChan)
3✔
5097

3✔
5098
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5099
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5100

3✔
5101
        s.OutboundPeerConnected(nil, conn)
3✔
5102
}
5103

5104
// DisconnectPeer sends the request to server to close the connection with peer
5105
// identified by public key.
5106
//
5107
// NOTE: This function is safe for concurrent access.
5108
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5109
        pubBytes := pubKey.SerializeCompressed()
3✔
5110
        pubStr := string(pubBytes)
3✔
5111

3✔
5112
        s.mu.Lock()
3✔
5113
        defer s.mu.Unlock()
3✔
5114

3✔
5115
        // Check that were actually connected to this peer. If not, then we'll
3✔
5116
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5117
        // currently connected to.
3✔
5118
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5119
        if err == ErrPeerNotConnected {
6✔
5120
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5121
        }
3✔
5122

5123
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5124

3✔
5125
        s.cancelConnReqs(pubStr, nil)
3✔
5126

3✔
5127
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5128
        // them from this map so we don't attempt to re-connect after we
3✔
5129
        // disconnect.
3✔
5130
        delete(s.persistentPeers, pubStr)
3✔
5131
        delete(s.persistentPeersBackoff, pubStr)
3✔
5132

3✔
5133
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5134
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5135
        //
3✔
5136
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5137
        // goroutine because we might hold the server's mutex.
3✔
5138
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5139

3✔
5140
        return nil
3✔
5141
}
5142

5143
// OpenChannel sends a request to the server to open a channel to the specified
5144
// peer identified by nodeKey with the passed channel funding parameters.
5145
//
5146
// NOTE: This function is safe for concurrent access.
5147
func (s *server) OpenChannel(
5148
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5149

3✔
5150
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5151
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5152
        // not blocked if the caller is not reading the updates.
3✔
5153
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5154
        req.Err = make(chan error, 1)
3✔
5155

3✔
5156
        // First attempt to locate the target peer to open a channel with, if
3✔
5157
        // we're unable to locate the peer then this request will fail.
3✔
5158
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5159
        s.mu.RLock()
3✔
5160
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5161
        if !ok {
3✔
5162
                s.mu.RUnlock()
×
5163

×
5164
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5165
                return req.Updates, req.Err
×
5166
        }
×
5167
        req.Peer = peer
3✔
5168
        s.mu.RUnlock()
3✔
5169

3✔
5170
        // We'll wait until the peer is active before beginning the channel
3✔
5171
        // opening process.
3✔
5172
        select {
3✔
5173
        case <-peer.ActiveSignal():
3✔
5174
        case <-peer.QuitSignal():
×
5175
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5176
                return req.Updates, req.Err
×
5177
        case <-s.quit:
×
5178
                req.Err <- ErrServerShuttingDown
×
5179
                return req.Updates, req.Err
×
5180
        }
5181

5182
        // If the fee rate wasn't specified at this point we fail the funding
5183
        // because of the missing fee rate information. The caller of the
5184
        // `OpenChannel` method needs to make sure that default values for the
5185
        // fee rate are set beforehand.
5186
        if req.FundingFeePerKw == 0 {
3✔
5187
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5188
                        "the channel opening transaction")
×
5189

×
5190
                return req.Updates, req.Err
×
5191
        }
×
5192

5193
        // Spawn a goroutine to send the funding workflow request to the funding
5194
        // manager. This allows the server to continue handling queries instead
5195
        // of blocking on this request which is exported as a synchronous
5196
        // request to the outside world.
5197
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5198

3✔
5199
        return req.Updates, req.Err
3✔
5200
}
5201

5202
// Peers returns a slice of all active peers.
5203
//
5204
// NOTE: This function is safe for concurrent access.
5205
func (s *server) Peers() []*peer.Brontide {
3✔
5206
        s.mu.RLock()
3✔
5207
        defer s.mu.RUnlock()
3✔
5208

3✔
5209
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5210
        for _, peer := range s.peersByPub {
6✔
5211
                peers = append(peers, peer)
3✔
5212
        }
3✔
5213

5214
        return peers
3✔
5215
}
5216

5217
// computeNextBackoff uses a truncated exponential backoff to compute the next
5218
// backoff using the value of the exiting backoff. The returned duration is
5219
// randomized in either direction by 1/20 to prevent tight loops from
5220
// stabilizing.
5221
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5222
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5223
        nextBackoff := 2 * currBackoff
3✔
5224
        if nextBackoff > maxBackoff {
6✔
5225
                nextBackoff = maxBackoff
3✔
5226
        }
3✔
5227

5228
        // Using 1/10 of our duration as a margin, compute a random offset to
5229
        // avoid the nodes entering connection cycles.
5230
        margin := nextBackoff / 10
3✔
5231

3✔
5232
        var wiggle big.Int
3✔
5233
        wiggle.SetUint64(uint64(margin))
3✔
5234
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5235
                // Randomizing is not mission critical, so we'll just return the
×
5236
                // current backoff.
×
5237
                return nextBackoff
×
5238
        }
×
5239

5240
        // Otherwise add in our wiggle, but subtract out half of the margin so
5241
        // that the backoff can tweaked by 1/20 in either direction.
5242
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5243
}
5244

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

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

3✔
5253
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5254
        if err != nil {
3✔
5255
                return nil, err
×
5256
        }
×
5257

5258
        node, err := s.graphDB.FetchNode(ctx, vertex)
3✔
5259
        if err != nil {
6✔
5260
                return nil, err
3✔
5261
        }
3✔
5262

5263
        if len(node.Addresses) == 0 {
6✔
5264
                return nil, errNoAdvertisedAddr
3✔
5265
        }
3✔
5266

5267
        return node.Addresses, nil
3✔
5268
}
5269

5270
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5271
// channel update for a target channel.
5272
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5273
        *lnwire.ChannelUpdate1, error) {
3✔
5274

3✔
5275
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5276
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5277
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5278
                if err != nil {
6✔
5279
                        return nil, err
3✔
5280
                }
3✔
5281

5282
                return netann.ExtractChannelUpdate(
3✔
5283
                        ourPubKey[:], info, edge1, edge2,
3✔
5284
                )
3✔
5285
        }
5286
}
5287

5288
// applyChannelUpdate applies the channel update to the different sub-systems of
5289
// the server. The useAlias boolean denotes whether or not to send an alias in
5290
// place of the real SCID.
5291
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5292
        op *wire.OutPoint, useAlias bool) error {
3✔
5293

3✔
5294
        var (
3✔
5295
                peerAlias    *lnwire.ShortChannelID
3✔
5296
                defaultAlias lnwire.ShortChannelID
3✔
5297
        )
3✔
5298

3✔
5299
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5300

3✔
5301
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5302
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5303
        if useAlias {
6✔
5304
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5305
                if foundAlias != defaultAlias {
6✔
5306
                        peerAlias = &foundAlias
3✔
5307
                }
3✔
5308
        }
5309

5310
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5311
                update, discovery.RemoteAlias(peerAlias),
3✔
5312
        )
3✔
5313
        select {
3✔
5314
        case err := <-errChan:
3✔
5315
                return err
3✔
5316
        case <-s.quit:
×
5317
                return ErrServerShuttingDown
×
5318
        }
5319
}
5320

5321
// SendCustomMessage sends a custom message to the peer with the specified
5322
// pubkey.
5323
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5324
        msgType lnwire.MessageType, data []byte) error {
3✔
5325

3✔
5326
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5327
        if err != nil {
6✔
5328
                return err
3✔
5329
        }
3✔
5330

5331
        // We'll wait until the peer is active, but also listen for
5332
        // cancellation.
5333
        select {
3✔
5334
        case <-peer.ActiveSignal():
3✔
5335
        case <-peer.QuitSignal():
×
5336
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5337
        case <-s.quit:
×
5338
                return ErrServerShuttingDown
×
5339
        case <-ctx.Done():
×
5340
                return ctx.Err()
×
5341
        }
5342

5343
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5344
        if err != nil {
6✔
5345
                return err
3✔
5346
        }
3✔
5347

5348
        // Send the message as low-priority. For now we assume that all
5349
        // application-defined message are low priority.
5350
        return peer.SendMessageLazy(true, msg)
3✔
5351
}
5352

5353
// SendOnionMessage sends a custom message to the peer with the specified
5354
// pubkey.
5355
// TODO(gijs): change this message to include path finding.
5356
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5357
        pathKey *btcec.PublicKey, onion []byte) error {
3✔
5358

3✔
5359
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5360
        if err != nil {
3✔
5361
                return err
×
5362
        }
×
5363

5364
        // We'll wait until the peer is active, but also listen for
5365
        // cancellation.
5366
        select {
3✔
5367
        case <-peer.ActiveSignal():
3✔
5368
        case <-peer.QuitSignal():
×
5369
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5370
        case <-s.quit:
×
5371
                return ErrServerShuttingDown
×
5372
        case <-ctx.Done():
×
5373
                return ctx.Err()
×
5374
        }
5375

5376
        msg := lnwire.NewOnionMessage(pathKey, onion)
3✔
5377

3✔
5378
        // Send the message as low-priority. For now we assume that all
3✔
5379
        // application-defined message are low priority.
3✔
5380
        return peer.SendMessageLazy(true, msg)
3✔
5381
}
5382

5383
// newSweepPkScriptGen creates closure that generates a new public key script
5384
// which should be used to sweep any funds into the on-chain wallet.
5385
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5386
// (p2wkh) output.
5387
func newSweepPkScriptGen(
5388
        wallet lnwallet.WalletController,
5389
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5390

3✔
5391
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5392
                sweepAddr, err := wallet.NewAddress(
3✔
5393
                        lnwallet.TaprootPubkey, false,
3✔
5394
                        lnwallet.DefaultAccountName,
3✔
5395
                )
3✔
5396
                if err != nil {
3✔
5397
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5398
                }
×
5399

5400
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5401
                if err != nil {
3✔
5402
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5403
                }
×
5404

5405
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5406
                        wallet, netParams, addr,
3✔
5407
                )
3✔
5408
                if err != nil {
3✔
5409
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5410
                }
×
5411

5412
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5413
                        DeliveryAddress: addr,
3✔
5414
                        InternalKey:     internalKeyDesc,
3✔
5415
                })
3✔
5416
        }
5417
}
5418

5419
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5420
// finished.
5421
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5422
        // Get a list of closed channels.
3✔
5423
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5424
        if err != nil {
3✔
5425
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5426
                return nil
×
5427
        }
×
5428

5429
        // Save the SCIDs in a map.
5430
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5431
        for _, c := range channels {
6✔
5432
                // If the channel is not pending, its FC has been finalized.
3✔
5433
                if !c.IsPending {
6✔
5434
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5435
                }
3✔
5436
        }
5437

5438
        // Double check whether the reported closed channel has indeed finished
5439
        // closing.
5440
        //
5441
        // NOTE: There are misalignments regarding when a channel's FC is
5442
        // marked as finalized. We double check the pending channels to make
5443
        // sure the returned SCIDs are indeed terminated.
5444
        //
5445
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5446
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5447
        if err != nil {
3✔
5448
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5449
                return nil
×
5450
        }
×
5451

5452
        for _, c := range pendings {
6✔
5453
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5454
                        continue
3✔
5455
                }
5456

5457
                // If the channel is still reported as pending, remove it from
5458
                // the map.
5459
                delete(closedSCIDs, c.ShortChannelID)
×
5460

×
5461
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5462
                        c.ShortChannelID)
×
5463
        }
5464

5465
        return closedSCIDs
3✔
5466
}
5467

5468
// getStartingBeat returns the current beat. This is used during the startup to
5469
// initialize blockbeat consumers.
5470
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5471
        // beat is the current blockbeat.
3✔
5472
        var beat *chainio.Beat
3✔
5473

3✔
5474
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5475
        // we will skip fetching the best block.
3✔
5476
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5477
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5478
                        "mode")
×
5479

×
5480
                return &chainio.Beat{}, nil
×
5481
        }
×
5482

5483
        // We should get a notification with the current best block immediately
5484
        // by passing a nil block.
5485
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5486
        if err != nil {
3✔
5487
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5488
        }
×
5489
        defer blockEpochs.Cancel()
3✔
5490

3✔
5491
        // We registered for the block epochs with a nil request. The notifier
3✔
5492
        // should send us the current best block immediately. So we need to
3✔
5493
        // wait for it here because we need to know the current best height.
3✔
5494
        select {
3✔
5495
        case bestBlock := <-blockEpochs.Epochs:
3✔
5496
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5497
                        bestBlock.Hash, bestBlock.Height)
3✔
5498

3✔
5499
                // Update the current blockbeat.
3✔
5500
                beat = chainio.NewBeat(*bestBlock)
3✔
5501

5502
        case <-s.quit:
×
5503
                srvrLog.Debug("LND shutting down")
×
5504
        }
5505

5506
        return beat, nil
3✔
5507
}
5508

5509
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5510
// point has an active RBF chan closer.
5511
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5512
        chanPoint wire.OutPoint) bool {
3✔
5513

3✔
5514
        pubBytes := peerPub.SerializeCompressed()
3✔
5515

3✔
5516
        s.mu.RLock()
3✔
5517
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5518
        s.mu.RUnlock()
3✔
5519
        if !ok {
3✔
5520
                return false
×
5521
        }
×
5522

5523
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5524
}
5525

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

3✔
5534
        // First, we'll attempt to look up the channel based on it's
3✔
5535
        // ChannelPoint.
3✔
5536
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5537
        if err != nil {
3✔
5538
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5539
        }
×
5540

5541
        // From the channel, we can now get the pubkey of the peer, then use
5542
        // that to eventually get the chan closer.
5543
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5544

3✔
5545
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5546
        s.mu.RLock()
3✔
5547
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5548
        s.mu.RUnlock()
3✔
5549
        if !ok {
3✔
5550
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5551
                        "not online", chanPoint)
×
5552
        }
×
5553

5554
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5555
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5556
        )
3✔
5557
        if err != nil {
3✔
5558
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5559
                        "%w", err)
×
5560
        }
×
5561

5562
        return closeUpdates, nil
3✔
5563
}
5564

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

3✔
5573
        // If the channel is present in the switch, then the request should flow
3✔
5574
        // through the switch instead.
3✔
5575
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5576
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5577
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5578
                        "invalid request", chanPoint)
×
5579
        }
×
5580

5581
        // At this point, we know that the channel isn't present in the link, so
5582
        // we'll check to see if we have an entry in the active chan closer map.
5583
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5584
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5585
        )
3✔
5586
        if err != nil {
3✔
5587
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5588
                        "ChannelPoint(%v)", chanPoint)
×
5589
        }
×
5590

5591
        return updates, nil
3✔
5592
}
5593

5594
// calculateNodeAnnouncementTimestamp returns the timestamp to use for a node
5595
// announcement, ensuring it's at least one second after the previously
5596
// persisted timestamp. This ensures BOLT-07 compliance, which requires node
5597
// announcements to have strictly increasing timestamps.
5598
func calculateNodeAnnouncementTimestamp(persistedTime,
5599
        currentTime time.Time) time.Time {
12✔
5600

12✔
5601
        if persistedTime.Unix() >= currentTime.Unix() {
21✔
5602
                return persistedTime.Add(time.Second)
9✔
5603
        }
9✔
5604

5605
        return currentTime
6✔
5606
}
5607

5608
// setSelfNode configures and sets the server's self node. It sets the node
5609
// announcement, signs it, and updates the source node in the graph. When
5610
// determining values such as color and alias, the method prioritizes values
5611
// set in the config, then values previously persisted on disk, and finally
5612
// falls back to the defaults.
5613
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5614
        listenAddrs []net.Addr) error {
3✔
5615

3✔
5616
        // If we were requested to automatically configure port forwarding,
3✔
5617
        // we'll use the ports that the server will be listening on.
3✔
5618
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
3✔
5619
        for _, ip := range s.cfg.ExternalIPs {
6✔
5620
                externalIPStrings = append(externalIPStrings, ip.String())
3✔
5621
        }
3✔
5622
        if s.natTraversal != nil {
3✔
5623
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5624
                for _, listenAddr := range listenAddrs {
×
5625
                        // At this point, the listen addresses should have
×
5626
                        // already been normalized, so it's safe to ignore the
×
5627
                        // errors.
×
5628
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5629
                        port, _ := strconv.Atoi(portStr)
×
5630

×
5631
                        listenPorts = append(listenPorts, uint16(port))
×
5632
                }
×
5633

5634
                ips, err := s.configurePortForwarding(listenPorts...)
×
5635
                if err != nil {
×
5636
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5637
                                "forwarding using %s: %v",
×
5638
                                s.natTraversal.Name(), err)
×
5639
                } else {
×
5640
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5641
                                "using %s to advertise external IP",
×
5642
                                s.natTraversal.Name())
×
5643
                        externalIPStrings = append(externalIPStrings, ips...)
×
5644
                }
×
5645
        }
5646

5647
        // Normalize the external IP strings to net.Addr.
5648
        addrs, err := lncfg.NormalizeAddresses(
3✔
5649
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
5650
                s.cfg.net.ResolveTCPAddr,
3✔
5651
        )
3✔
5652
        if err != nil {
3✔
5653
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5654
        }
×
5655

5656
        // Parse the color from config. We will update this later if the config
5657
        // color is not changed from default (#3399FF) and we have a value in
5658
        // the source node.
5659
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
3✔
5660
        if err != nil {
3✔
5661
                return fmt.Errorf("unable to parse color: %w", err)
×
5662
        }
×
5663

5664
        var (
3✔
5665
                alias          = s.cfg.Alias
3✔
5666
                nodeLastUpdate = time.Now()
3✔
5667
        )
3✔
5668

3✔
5669
        srcNode, err := s.graphDB.SourceNode(ctx)
3✔
5670
        switch {
3✔
5671
        case err == nil:
3✔
5672
                // If we have a source node persisted in the DB already, then we
3✔
5673
                // just need to make sure that the new LastUpdate time is at
3✔
5674
                // least one second after the last update time.
3✔
5675
                nodeLastUpdate = calculateNodeAnnouncementTimestamp(
3✔
5676
                        srcNode.LastUpdate, nodeLastUpdate,
3✔
5677
                )
3✔
5678

3✔
5679
                // If the color is not changed from default, it means that we
3✔
5680
                // didn't specify a different color in the config. We'll use the
3✔
5681
                // source node's color.
3✔
5682
                if s.cfg.Color == defaultColor {
6✔
5683
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
6✔
5684
                                nodeColor = rgba
3✔
5685
                        })
3✔
5686
                }
5687

5688
                // If an alias is not specified in the config, we'll use the
5689
                // source node's alias.
5690
                if alias == "" {
6✔
5691
                        srcNode.Alias.WhenSome(func(s string) {
6✔
5692
                                alias = s
3✔
5693
                        })
3✔
5694
                }
5695

5696
                // If the `externalip` is not specified in the config, it means
5697
                // `addrs` will be empty, we'll use the source node's addresses.
5698
                if len(s.cfg.ExternalIPs) == 0 {
6✔
5699
                        addrs = srcNode.Addresses
3✔
5700
                }
3✔
5701

5702
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
3✔
5703
                // If an alias is not specified in the config, we'll use the
3✔
5704
                // default, which is the first 10 bytes of the serialized
3✔
5705
                // pubkey.
3✔
5706
                if alias == "" {
6✔
5707
                        alias = hex.EncodeToString(nodePub[:10])
3✔
5708
                }
3✔
5709

5710
        // If the above cases are not matched, then we have an unhandled non
5711
        // nil error.
5712
        default:
×
5713
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5714
        }
5715

5716
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
5717
        if err != nil {
3✔
5718
                return err
×
5719
        }
×
5720

5721
        // TODO(abdulkbk): potentially find a way to use the source node's
5722
        // features in the self node.
5723
        selfNode := models.NewV1Node(
3✔
5724
                nodePub, &models.NodeV1Fields{
3✔
5725
                        Alias:      nodeAlias.String(),
3✔
5726
                        Color:      nodeColor,
3✔
5727
                        LastUpdate: nodeLastUpdate,
3✔
5728
                        Addresses:  addrs,
3✔
5729
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
3✔
5730
                },
3✔
5731
        )
3✔
5732

3✔
5733
        // Based on the disk representation of the node announcement generated
3✔
5734
        // above, we'll generate a node announcement that can go out on the
3✔
5735
        // network so we can properly sign it.
3✔
5736
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
5737
        if err != nil {
3✔
5738
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5739
        }
×
5740

5741
        // With the announcement generated, we'll sign it to properly
5742
        // authenticate the message on the network.
5743
        authSig, err := netann.SignAnnouncement(
3✔
5744
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
3✔
5745
        )
3✔
5746
        if err != nil {
3✔
5747
                return fmt.Errorf("unable to generate signature for self node "+
×
5748
                        "announcement: %v", err)
×
5749
        }
×
5750

5751
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
5752
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
5753
                selfNode.AuthSigBytes,
3✔
5754
        )
3✔
5755
        if err != nil {
3✔
5756
                return err
×
5757
        }
×
5758

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

5765
        s.currentNodeAnn = nodeAnn
3✔
5766

3✔
5767
        return nil
3✔
5768
}
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