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

lightningnetwork / lnd / 16693114906

02 Aug 2025 11:25AM UTC coverage: 67.036% (-0.01%) from 67.047%
16693114906

Pull #9826

github

web-flow
Merge 2b3b27f5a into 37523b6cb
Pull Request #9826: Refactor Payment PR 2

1002 of 1343 new or added lines in 5 files covered. (74.61%)

83 existing lines in 18 files now uncovered.

135561 of 202222 relevant lines covered (67.04%)

21699.54 hits per line

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

69.38
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        // kvPaymentsDB is the DB that contains all functions for managing
339
        // payments.
340
        //
341
        // TODO(ziggie): Replace with interface.
342
        kvPaymentsDB *channeldb.KVPaymentsDB
343

344
        aliasMgr *aliasmgr.Manager
345

346
        htlcSwitch *htlcswitch.Switch
347

348
        interceptableSwitch *htlcswitch.InterceptableSwitch
349

350
        invoices *invoices.InvoiceRegistry
351

352
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
353

354
        channelNotifier *channelnotifier.ChannelNotifier
355

356
        peerNotifier *peernotifier.PeerNotifier
357

358
        htlcNotifier *htlcswitch.HtlcNotifier
359

360
        witnessBeacon contractcourt.WitnessBeacon
361

362
        breachArbitrator *contractcourt.BreachArbitrator
363

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

367
        graphBuilder *graph.Builder
368

369
        chanRouter *routing.ChannelRouter
370

371
        controlTower routing.ControlTower
372

373
        authGossiper *discovery.AuthenticatedGossiper
374

375
        localChanMgr *localchans.Manager
376

377
        utxoNursery *contractcourt.UtxoNursery
378

379
        sweeper *sweep.UtxoSweeper
380

381
        chainArb *contractcourt.ChainArbitrator
382

383
        sphinx *hop.OnionProcessor
384

385
        towerClientMgr *wtclient.Manager
386

387
        connMgr *connmgr.ConnManager
388

389
        sigPool *lnwallet.SigPool
390

391
        writePool *pool.Write
392

393
        readPool *pool.Read
394

395
        tlsManager *TLSManager
396

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

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

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

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

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

419
        hostAnn *netann.HostAnnouncer
420

421
        // livenessMonitor monitors that lnd has access to critical resources.
422
        livenessMonitor *healthcheck.Monitor
423

424
        customMessageServer *subscribe.Server
425

426
        // txPublisher is a publisher with fee-bumping capability.
427
        txPublisher *sweep.TxPublisher
428

429
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
430
        // of new blocks.
431
        blockbeatDispatcher *chainio.BlockbeatDispatcher
432

433
        // peerAccessMan implements peer access controls.
434
        peerAccessMan *accessMan
435

436
        quit chan struct{}
437

438
        wg sync.WaitGroup
439
}
440

441
// updatePersistentPeerAddrs subscribes to topology changes and stores
442
// advertised addresses for any NodeAnnouncements from our persisted peers.
443
func (s *server) updatePersistentPeerAddrs() error {
3✔
444
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
445
        if err != nil {
3✔
446
                return err
×
447
        }
×
448

449
        s.wg.Add(1)
3✔
450
        go func() {
6✔
451
                defer func() {
6✔
452
                        graphSub.Cancel()
3✔
453
                        s.wg.Done()
3✔
454
                }()
3✔
455

456
                for {
6✔
457
                        select {
3✔
458
                        case <-s.quit:
3✔
459
                                return
3✔
460

461
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
462
                                // If the router is shutting down, then we will
3✔
463
                                // as well.
3✔
464
                                if !ok {
3✔
465
                                        return
×
466
                                }
×
467

468
                                for _, update := range topChange.NodeUpdates {
6✔
469
                                        pubKeyStr := string(
3✔
470
                                                update.IdentityKey.
3✔
471
                                                        SerializeCompressed(),
3✔
472
                                        )
3✔
473

3✔
474
                                        // We only care about updates from
3✔
475
                                        // our persistentPeers.
3✔
476
                                        s.mu.RLock()
3✔
477
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
478
                                        s.mu.RUnlock()
3✔
479
                                        if !ok {
6✔
480
                                                continue
3✔
481
                                        }
482

483
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
484
                                                len(update.Addresses))
3✔
485

3✔
486
                                        for _, addr := range update.Addresses {
6✔
487
                                                addrs = append(addrs,
3✔
488
                                                        &lnwire.NetAddress{
3✔
489
                                                                IdentityKey: update.IdentityKey,
3✔
490
                                                                Address:     addr,
3✔
491
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
492
                                                        },
3✔
493
                                                )
3✔
494
                                        }
3✔
495

496
                                        s.mu.Lock()
3✔
497

3✔
498
                                        // Update the stored addresses for this
3✔
499
                                        // to peer to reflect the new set.
3✔
500
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
501

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

512
                                        s.mu.Unlock()
3✔
513

3✔
514
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
515
                                }
516
                        }
517
                }
518
        }()
519

520
        return nil
3✔
521
}
522

523
// CustomMessage is a custom message that is received from a peer.
524
type CustomMessage struct {
525
        // Peer is the peer pubkey
526
        Peer [33]byte
527

528
        // Msg is the custom wire message.
529
        Msg *lnwire.Custom
530
}
531

532
// parseAddr parses an address from its string format to a net.Addr.
533
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
534
        var (
3✔
535
                host string
3✔
536
                port int
3✔
537
        )
3✔
538

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

556
        if tor.IsOnionHost(host) {
3✔
557
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
558
        }
×
559

560
        // If the host is part of a TCP address, we'll use the network
561
        // specific ResolveTCPAddr function in order to resolve these
562
        // addresses over Tor in order to prevent leaking your real IP
563
        // address.
564
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
565
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
566
}
567

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

3✔
573
        return func(a net.Addr) (net.Conn, error) {
6✔
574
                lnAddr := a.(*lnwire.NetAddress)
3✔
575
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
576
        }
3✔
577
}
578

579
// newServer creates a new instance of the server which is to listen using the
580
// passed listener address.
581
//
582
//nolint:funlen
583
func newServer(ctx context.Context, cfg *Config, listenAddrs []net.Addr,
584
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
585
        nodeKeyDesc *keychain.KeyDescriptor,
586
        chansToRestore walletunlocker.ChannelsToRecover,
587
        chanPredicate chanacceptor.ChannelAcceptor,
588
        torController *tor.Controller, tlsManager *TLSManager,
589
        leaderElector cluster.LeaderElector,
590
        implCfg *ImplementationCfg) (*server, error) {
3✔
591

3✔
592
        var (
3✔
593
                err         error
3✔
594
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
595

3✔
596
                // We just derived the full descriptor, so we know the public
3✔
597
                // key is set on it.
3✔
598
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
599
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
600
                )
3✔
601
        )
3✔
602

3✔
603
        var serializedPubKey [33]byte
3✔
604
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
605

3✔
606
        netParams := cfg.ActiveNetParams.Params
3✔
607

3✔
608
        // Initialize the sphinx router.
3✔
609
        replayLog := htlcswitch.NewDecayedLog(
3✔
610
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
611
        )
3✔
612
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
613

3✔
614
        writeBufferPool := pool.NewWriteBuffer(
3✔
615
                pool.DefaultWriteBufferGCInterval,
3✔
616
                pool.DefaultWriteBufferExpiryInterval,
3✔
617
        )
3✔
618

3✔
619
        writePool := pool.NewWrite(
3✔
620
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
621
        )
3✔
622

3✔
623
        readBufferPool := pool.NewReadBuffer(
3✔
624
                pool.DefaultReadBufferGCInterval,
3✔
625
                pool.DefaultReadBufferExpiryInterval,
3✔
626
        )
3✔
627

3✔
628
        readPool := pool.NewRead(
3✔
629
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
630
        )
3✔
631

3✔
632
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
633
        // controller, then we'll exit as this is incompatible.
3✔
634
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
635
                implCfg.AuxFundingController.IsNone() {
3✔
636

×
637
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
638
                        "aux controllers")
×
639
        }
×
640

641
        //nolint:ll
642
        featureMgr, err := feature.NewManager(feature.Config{
3✔
643
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
644
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
645
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
646
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
647
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
648
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
649
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
650
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
651
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
652
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
653
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
654
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
655
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
656
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
657
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
658
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
659
        })
3✔
660
        if err != nil {
3✔
661
                return nil, err
×
662
        }
×
663

664
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
665
        registryConfig := invoices.RegistryConfig{
3✔
666
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
667
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
668
                Clock:                       clock.NewDefaultClock(),
3✔
669
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
670
                AcceptAMP:                   cfg.AcceptAMP,
3✔
671
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
672
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
673
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
674
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
675
        }
3✔
676

3✔
677
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
678

3✔
679
        s := &server{
3✔
680
                cfg:            cfg,
3✔
681
                implCfg:        implCfg,
3✔
682
                graphDB:        dbs.GraphDB,
3✔
683
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
684
                addrSource:     addrSource,
3✔
685
                miscDB:         dbs.ChanStateDB,
3✔
686
                invoicesDB:     dbs.InvoiceDB,
3✔
687
                kvPaymentsDB:   dbs.KVPaymentsDB,
3✔
688
                cc:             cc,
3✔
689
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
690
                writePool:      writePool,
3✔
691
                readPool:       readPool,
3✔
692
                chansToRestore: chansToRestore,
3✔
693

3✔
694
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
695
                        cc.ChainNotifier,
3✔
696
                ),
3✔
697
                channelNotifier: channelnotifier.New(
3✔
698
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
699
                ),
3✔
700

3✔
701
                identityECDH:   nodeKeyECDH,
3✔
702
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
703
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
704

3✔
705
                listenAddrs: listenAddrs,
3✔
706

3✔
707
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
708
                // schedule
3✔
709
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
710

3✔
711
                torController: torController,
3✔
712

3✔
713
                persistentPeers:         make(map[string]bool),
3✔
714
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
715
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
716
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
717
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
718
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
719
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
720
                scheduledPeerConnection: make(map[string]func()),
3✔
721
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
722

3✔
723
                peersByPub:                make(map[string]*peer.Brontide),
3✔
724
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
725
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
726
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
727
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
728

3✔
729
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
730

3✔
731
                customMessageServer: subscribe.NewServer(),
3✔
732

3✔
733
                tlsManager: tlsManager,
3✔
734

3✔
735
                featureMgr: featureMgr,
3✔
736
                quit:       make(chan struct{}),
3✔
737
        }
3✔
738

3✔
739
        // Start the low-level services once they are initialized.
3✔
740
        //
3✔
741
        // TODO(yy): break the server startup into four steps,
3✔
742
        // 1. init the low-level services.
3✔
743
        // 2. start the low-level services.
3✔
744
        // 3. init the high-level services.
3✔
745
        // 4. start the high-level services.
3✔
746
        if err := s.startLowLevelServices(); err != nil {
3✔
747
                return nil, err
×
748
        }
×
749

750
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
751
        if err != nil {
3✔
752
                return nil, err
×
753
        }
×
754

755
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
756
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
757
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
758
        )
3✔
759
        s.invoices = invoices.NewRegistry(
3✔
760
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
761
        )
3✔
762

3✔
763
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
764

3✔
765
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
766
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
767

3✔
768
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
769
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
770
                if err != nil {
3✔
771
                        return err
×
772
                }
×
773

774
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
775

3✔
776
                return nil
3✔
777
        }
778

779
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
780
        if err != nil {
3✔
781
                return nil, err
×
782
        }
×
783

784
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
785
                DB:                   dbs.ChanStateDB,
3✔
786
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
787
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
788
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
789
                LocalChannelClose: func(pubKey []byte,
3✔
790
                        request *htlcswitch.ChanClose) {
6✔
791

3✔
792
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
793
                        if err != nil {
3✔
794
                                srvrLog.Errorf("unable to close channel, peer"+
×
795
                                        " with %v id can't be found: %v",
×
796
                                        pubKey, err,
×
797
                                )
×
798
                                return
×
799
                        }
×
800

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

836
        s.witnessBeacon = newPreimageBeacon(
3✔
837
                dbs.ChanStateDB.NewWitnessCache(),
3✔
838
                s.interceptableSwitch.ForwardPacket,
3✔
839
        )
3✔
840

3✔
841
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
842
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
843
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
844
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
845
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
846
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
847
                MessageSigner:            s.nodeSigner,
3✔
848
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
849
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
850
                DB:                       s.chanStateDB,
3✔
851
                Graph:                    dbs.GraphDB,
3✔
852
        }
3✔
853

3✔
854
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
855
        if err != nil {
3✔
856
                return nil, err
×
857
        }
×
858
        s.chanStatusMgr = chanStatusMgr
3✔
859

3✔
860
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
861
        // port forwarding for users behind a NAT.
3✔
862
        if cfg.NAT {
3✔
863
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
864

×
865
                discoveryTimeout := time.Duration(10 * time.Second)
×
866

×
867
                ctx, cancel := context.WithTimeout(
×
868
                        context.Background(), discoveryTimeout,
×
869
                )
×
870
                defer cancel()
×
871
                upnp, err := nat.DiscoverUPnP(ctx)
×
872
                if err == nil {
×
873
                        s.natTraversal = upnp
×
874
                } else {
×
875
                        // If we were not able to discover a UPnP enabled device
×
876
                        // on the local network, we'll fall back to attempting
×
877
                        // to discover a NAT-PMP enabled device.
×
878
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
879
                                "device on the local network: %v", err)
×
880

×
881
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
882
                                "enabled device")
×
883

×
884
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
885
                        if err != nil {
×
886
                                err := fmt.Errorf("unable to discover a "+
×
887
                                        "NAT-PMP enabled device on the local "+
×
888
                                        "network: %v", err)
×
889
                                srvrLog.Error(err)
×
890
                                return nil, err
×
891
                        }
×
892

893
                        s.natTraversal = pmp
×
894
                }
895
        }
896

897
        // If we were requested to automatically configure port forwarding,
898
        // we'll use the ports that the server will be listening on.
899
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
900
        for idx, ip := range cfg.ExternalIPs {
6✔
901
                externalIPStrings[idx] = ip.String()
3✔
902
        }
3✔
903
        if s.natTraversal != nil {
3✔
904
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
905
                for _, listenAddr := range listenAddrs {
×
906
                        // At this point, the listen addresses should have
×
907
                        // already been normalized, so it's safe to ignore the
×
908
                        // errors.
×
909
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
910
                        port, _ := strconv.Atoi(portStr)
×
911

×
912
                        listenPorts = append(listenPorts, uint16(port))
×
913
                }
×
914

915
                ips, err := s.configurePortForwarding(listenPorts...)
×
916
                if err != nil {
×
917
                        srvrLog.Errorf("Unable to automatically set up port "+
×
918
                                "forwarding using %s: %v",
×
919
                                s.natTraversal.Name(), err)
×
920
                } else {
×
921
                        srvrLog.Infof("Automatically set up port forwarding "+
×
922
                                "using %s to advertise external IP",
×
923
                                s.natTraversal.Name())
×
924
                        externalIPStrings = append(externalIPStrings, ips...)
×
925
                }
×
926
        }
927

928
        // If external IP addresses have been specified, add those to the list
929
        // of this server's addresses.
930
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
931
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
932
                cfg.net.ResolveTCPAddr,
3✔
933
        )
3✔
934
        if err != nil {
3✔
935
                return nil, err
×
936
        }
×
937

938
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
939
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
940

3✔
941
        // We'll now reconstruct a node announcement based on our current
3✔
942
        // configuration so we can send it out as a sort of heart beat within
3✔
943
        // the network.
3✔
944
        //
3✔
945
        // We'll start by parsing the node color from configuration.
3✔
946
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
947
        if err != nil {
3✔
948
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
949
                return nil, err
×
950
        }
×
951

952
        // If no alias is provided, default to first 10 characters of public
953
        // key.
954
        alias := cfg.Alias
3✔
955
        if alias == "" {
6✔
956
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
957
        }
3✔
958
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
959
        if err != nil {
3✔
960
                return nil, err
×
961
        }
×
962

963
        // TODO(elle): All previously persisted node announcement fields (ie,
964
        //  not just LastUpdate) should be consulted here to ensure that we
965
        //  aren't overwriting any fields that may have been set during the
966
        //  last run of lnd.
967
        nodeLastUpdate := time.Now()
3✔
968
        srcNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
969
        switch {
3✔
970
        // If we have a source node persisted in the DB already, then we just
971
        // need to make sure that the new LastUpdate time is at least one
972
        // second after the last update time.
973
        case err == nil:
3✔
974
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
6✔
975
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
3✔
976
                }
3✔
977

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

982
        // If the above cases are not matched, then we have an unhandled non
983
        // nil error.
984
        default:
×
985
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
986
        }
987

988
        selfNode := &models.LightningNode{
3✔
989
                HaveNodeAnnouncement: true,
3✔
990
                LastUpdate:           nodeLastUpdate,
3✔
991
                Addresses:            selfAddrs,
3✔
992
                Alias:                nodeAlias.String(),
3✔
993
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
994
                Color:                color,
3✔
995
        }
3✔
996
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
997

3✔
998
        // Based on the disk representation of the node announcement generated
3✔
999
        // above, we'll generate a node announcement that can go out on the
3✔
1000
        // network so we can properly sign it.
3✔
1001
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
1002
        if err != nil {
3✔
1003
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
1004
        }
×
1005

1006
        // With the announcement generated, we'll sign it to properly
1007
        // authenticate the message on the network.
1008
        authSig, err := netann.SignAnnouncement(
3✔
1009
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
1010
        )
3✔
1011
        if err != nil {
3✔
1012
                return nil, fmt.Errorf("unable to generate signature for "+
×
1013
                        "self node announcement: %v", err)
×
1014
        }
×
1015
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
1016
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
1017
                selfNode.AuthSigBytes,
3✔
1018
        )
3✔
1019
        if err != nil {
3✔
1020
                return nil, err
×
1021
        }
×
1022

1023
        // Finally, we'll update the representation on disk, and update our
1024
        // cached in-memory version as well.
1025
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
1026
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1027
        }
×
1028
        s.currentNodeAnn = nodeAnn
3✔
1029

3✔
1030
        // The router will get access to the payment ID sequencer, such that it
3✔
1031
        // can generate unique payment IDs.
3✔
1032
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1033
        if err != nil {
3✔
1034
                return nil, err
×
1035
        }
×
1036

1037
        // Instantiate mission control with config from the sub server.
1038
        //
1039
        // TODO(joostjager): When we are further in the process of moving to sub
1040
        // servers, the mission control instance itself can be moved there too.
1041
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1042

3✔
1043
        // We only initialize a probability estimator if there's no custom one.
3✔
1044
        var estimator routing.Estimator
3✔
1045
        if cfg.Estimator != nil {
3✔
1046
                estimator = cfg.Estimator
×
1047
        } else {
3✔
1048
                switch routingConfig.ProbabilityEstimatorType {
3✔
1049
                case routing.AprioriEstimatorName:
3✔
1050
                        aCfg := routingConfig.AprioriConfig
3✔
1051
                        aprioriConfig := routing.AprioriConfig{
3✔
1052
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1053
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1054
                                AprioriWeight:         aCfg.Weight,
3✔
1055
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1056
                        }
3✔
1057

3✔
1058
                        estimator, err = routing.NewAprioriEstimator(
3✔
1059
                                aprioriConfig,
3✔
1060
                        )
3✔
1061
                        if err != nil {
3✔
1062
                                return nil, err
×
1063
                        }
×
1064

1065
                case routing.BimodalEstimatorName:
×
1066
                        bCfg := routingConfig.BimodalConfig
×
1067
                        bimodalConfig := routing.BimodalConfig{
×
1068
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1069
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1070
                                        bCfg.Scale,
×
1071
                                ),
×
1072
                                BimodalDecayTime: bCfg.DecayTime,
×
1073
                        }
×
1074

×
1075
                        estimator, err = routing.NewBimodalEstimator(
×
1076
                                bimodalConfig,
×
1077
                        )
×
1078
                        if err != nil {
×
1079
                                return nil, err
×
1080
                        }
×
1081

1082
                default:
×
1083
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1084
                                routingConfig.ProbabilityEstimatorType)
×
1085
                }
1086
        }
1087

1088
        mcCfg := &routing.MissionControlConfig{
3✔
1089
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1090
                Estimator:               estimator,
3✔
1091
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1092
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1093
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1094
        }
3✔
1095

3✔
1096
        s.missionController, err = routing.NewMissionController(
3✔
1097
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1098
        )
3✔
1099
        if err != nil {
3✔
1100
                return nil, fmt.Errorf("can't create mission control "+
×
1101
                        "manager: %w", err)
×
1102
        }
×
1103
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1104
                routing.DefaultMissionControlNamespace,
3✔
1105
        )
3✔
1106
        if err != nil {
3✔
1107
                return nil, fmt.Errorf("can't create mission control in the "+
×
1108
                        "default namespace: %w", err)
×
1109
        }
×
1110

1111
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1112
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1113
                int64(routingConfig.AttemptCost),
3✔
1114
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1115
                routingConfig.MinRouteProbability)
3✔
1116

3✔
1117
        pathFindingConfig := routing.PathFindingConfig{
3✔
1118
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1119
                        routingConfig.AttemptCost,
3✔
1120
                ),
3✔
1121
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1122
                MinProbability: routingConfig.MinRouteProbability,
3✔
1123
        }
3✔
1124

3✔
1125
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1126
        if err != nil {
3✔
1127
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1128
        }
×
1129
        paymentSessionSource := &routing.SessionSource{
3✔
1130
                GraphSessionFactory: dbs.GraphDB,
3✔
1131
                SourceNode:          sourceNode,
3✔
1132
                MissionControl:      s.defaultMC,
3✔
1133
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1134
                PathFindingConfig:   pathFindingConfig,
3✔
1135
        }
3✔
1136

3✔
1137
        s.controlTower = routing.NewControlTower(dbs.KVPaymentsDB)
3✔
1138

3✔
1139
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1140
                cfg.Routing.StrictZombiePruning
3✔
1141

3✔
1142
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1143
                SelfNode:            selfNode.PubKeyBytes,
3✔
1144
                Graph:               dbs.GraphDB,
3✔
1145
                Chain:               cc.ChainIO,
3✔
1146
                ChainView:           cc.ChainView,
3✔
1147
                Notifier:            cc.ChainNotifier,
3✔
1148
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1149
                GraphPruneInterval:  time.Hour,
3✔
1150
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1151
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1152
                StrictZombiePruning: strictPruning,
3✔
1153
                IsAlias:             aliasmgr.IsAlias,
3✔
1154
        })
3✔
1155
        if err != nil {
3✔
1156
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1157
        }
×
1158

1159
        s.chanRouter, err = routing.New(routing.Config{
3✔
1160
                SelfNode:           selfNode.PubKeyBytes,
3✔
1161
                RoutingGraph:       dbs.GraphDB,
3✔
1162
                Chain:              cc.ChainIO,
3✔
1163
                Payer:              s.htlcSwitch,
3✔
1164
                Control:            s.controlTower,
3✔
1165
                MissionControl:     s.defaultMC,
3✔
1166
                SessionSource:      paymentSessionSource,
3✔
1167
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1168
                NextPaymentID:      sequencer.NextID,
3✔
1169
                PathFindingConfig:  pathFindingConfig,
3✔
1170
                Clock:              clock.NewDefaultClock(),
3✔
1171
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1172
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1173
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1174
        })
3✔
1175
        if err != nil {
3✔
1176
                return nil, fmt.Errorf("can't create router: %w", err)
×
1177
        }
×
1178

1179
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1180
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1181
        if err != nil {
3✔
1182
                return nil, err
×
1183
        }
×
1184
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1185
        if err != nil {
3✔
1186
                return nil, err
×
1187
        }
×
1188

1189
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1190

3✔
1191
        s.authGossiper = discovery.New(discovery.Config{
3✔
1192
                Graph:                 s.graphBuilder,
3✔
1193
                ChainIO:               s.cc.ChainIO,
3✔
1194
                Notifier:              s.cc.ChainNotifier,
3✔
1195
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1196
                Broadcast:             s.BroadcastMessage,
3✔
1197
                ChanSeries:            chanSeries,
3✔
1198
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1199
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1200
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1201
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1202
                        error) {
3✔
1203

×
1204
                        return s.genNodeAnnouncement(nil)
×
1205
                },
×
1206
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1207
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1208
                RetransmitTicker:        ticker.New(time.Minute * 30),
1209
                RebroadcastInterval:     time.Hour * 24,
1210
                WaitingProofStore:       waitingProofStore,
1211
                MessageStore:            gossipMessageStore,
1212
                AnnSigner:               s.nodeSigner,
1213
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1214
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1215
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1216
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1217
                MinimumBatchSize:        10,
1218
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1219
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1220
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1221
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1222
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1223
                IsAlias:                 aliasmgr.IsAlias,
1224
                SignAliasUpdate:         s.signAliasUpdate,
1225
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1226
                GetAlias:                s.aliasMgr.GetPeerAlias,
1227
                FindChannel:             s.findChannel,
1228
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1229
                ScidCloser:              scidCloserMan,
1230
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1231
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1232
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1233
        }, nodeKeyDesc)
1234

1235
        accessCfg := &accessManConfig{
3✔
1236
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1237
                        error) {
6✔
1238

3✔
1239
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1240
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1241
                                genesisHash[:],
3✔
1242
                        )
3✔
1243
                },
3✔
1244
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1245
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1246
        }
1247

1248
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1249
        if err != nil {
3✔
1250
                return nil, err
×
1251
        }
×
1252

1253
        s.peerAccessMan = peerAccessMan
3✔
1254

3✔
1255
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1256
        //nolint:ll
3✔
1257
        s.localChanMgr = &localchans.Manager{
3✔
1258
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1259
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1260
                ForAllOutgoingChannels: func(ctx context.Context,
3✔
1261
                        cb func(*models.ChannelEdgeInfo,
3✔
1262
                                *models.ChannelEdgePolicy) error,
3✔
1263
                        reset func()) error {
6✔
1264

3✔
1265
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
3✔
1266
                                func(c *models.ChannelEdgeInfo,
3✔
1267
                                        e *models.ChannelEdgePolicy,
3✔
1268
                                        _ *models.ChannelEdgePolicy) error {
6✔
1269

3✔
1270
                                        // NOTE: The invoked callback here may
3✔
1271
                                        // receive a nil channel policy.
3✔
1272
                                        return cb(c, e)
3✔
1273
                                }, reset,
3✔
1274
                        )
1275
                },
1276
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1277
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1278
                FetchChannel:              s.chanStateDB.FetchChannel,
1279
                AddEdge: func(ctx context.Context,
1280
                        edge *models.ChannelEdgeInfo) error {
×
1281

×
1282
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1283
                },
×
1284
        }
1285

1286
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1287
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1288
        )
3✔
1289
        if err != nil {
3✔
1290
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1291
                return nil, err
×
1292
        }
×
1293

1294
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1295
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1296
        )
3✔
1297
        if err != nil {
3✔
1298
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1299
                return nil, err
×
1300
        }
×
1301

1302
        aggregator := sweep.NewBudgetAggregator(
3✔
1303
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1304
                s.implCfg.AuxSweeper,
3✔
1305
        )
3✔
1306

3✔
1307
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1308
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1309
                Wallet:     cc.Wallet,
3✔
1310
                Estimator:  cc.FeeEstimator,
3✔
1311
                Notifier:   cc.ChainNotifier,
3✔
1312
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1313
        })
3✔
1314

3✔
1315
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1316
                FeeEstimator: cc.FeeEstimator,
3✔
1317
                GenSweepScript: newSweepPkScriptGen(
3✔
1318
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1319
                ),
3✔
1320
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1321
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1322
                Mempool:              cc.MempoolNotifier,
3✔
1323
                Notifier:             cc.ChainNotifier,
3✔
1324
                Store:                sweeperStore,
3✔
1325
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1326
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1327
                Aggregator:           aggregator,
3✔
1328
                Publisher:            s.txPublisher,
3✔
1329
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1330
        })
3✔
1331

3✔
1332
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1333
                ChainIO:             cc.ChainIO,
3✔
1334
                ConfDepth:           1,
3✔
1335
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1336
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1337
                Notifier:            cc.ChainNotifier,
3✔
1338
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1339
                Store:               utxnStore,
3✔
1340
                SweepInput:          s.sweeper.SweepInput,
3✔
1341
                Budget:              s.cfg.Sweeper.Budget,
3✔
1342
        })
3✔
1343

3✔
1344
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1345
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1346
                closureType contractcourt.ChannelCloseType) {
6✔
1347
                // TODO(conner): Properly respect the update and error channels
3✔
1348
                // returned by CloseLink.
3✔
1349

3✔
1350
                // Instruct the switch to close the channel.  Provide no close out
3✔
1351
                // delivery script or target fee per kw because user input is not
3✔
1352
                // available when the remote peer closes the channel.
3✔
1353
                s.htlcSwitch.CloseLink(
3✔
1354
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1355
                )
3✔
1356
        }
3✔
1357

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

3✔
1362
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1363
                &contractcourt.BreachConfig{
3✔
1364
                        CloseLink: closeLink,
3✔
1365
                        DB:        s.chanStateDB,
3✔
1366
                        Estimator: s.cc.FeeEstimator,
3✔
1367
                        GenSweepScript: newSweepPkScriptGen(
3✔
1368
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1369
                        ),
3✔
1370
                        Notifier:           cc.ChainNotifier,
3✔
1371
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1372
                        ContractBreaches:   contractBreaches,
3✔
1373
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1374
                        Store: contractcourt.NewRetributionStore(
3✔
1375
                                dbs.ChanStateDB,
3✔
1376
                        ),
3✔
1377
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1378
                },
3✔
1379
        )
3✔
1380

3✔
1381
        //nolint:ll
3✔
1382
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1383
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1384
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1385
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1386
                NewSweepAddr: func() ([]byte, error) {
3✔
1387
                        addr, err := newSweepPkScriptGen(
×
1388
                                cc.Wallet, netParams,
×
1389
                        )().Unpack()
×
1390
                        if err != nil {
×
1391
                                return nil, err
×
1392
                        }
×
1393

1394
                        return addr.DeliveryAddress, nil
×
1395
                },
1396
                PublishTx: cc.Wallet.PublishTransaction,
1397
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1398
                        for _, msg := range msgs {
6✔
1399
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1400
                                if err != nil {
3✔
1401
                                        return err
×
1402
                                }
×
1403
                        }
1404
                        return nil
3✔
1405
                },
1406
                IncubateOutputs: func(chanPoint wire.OutPoint,
1407
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1408
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1409
                        broadcastHeight uint32,
1410
                        deadlineHeight fn.Option[int32]) error {
3✔
1411

3✔
1412
                        return s.utxoNursery.IncubateOutputs(
3✔
1413
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1414
                                broadcastHeight, deadlineHeight,
3✔
1415
                        )
3✔
1416
                },
3✔
1417
                PreimageDB:   s.witnessBeacon,
1418
                Notifier:     cc.ChainNotifier,
1419
                Mempool:      cc.MempoolNotifier,
1420
                Signer:       cc.Wallet.Cfg.Signer,
1421
                FeeEstimator: cc.FeeEstimator,
1422
                ChainIO:      cc.ChainIO,
1423
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1424
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1425
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1426
                        return nil
3✔
1427
                },
3✔
1428
                IsOurAddress: cc.Wallet.IsOurAddress,
1429
                ContractBreach: func(chanPoint wire.OutPoint,
1430
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1431

3✔
1432
                        // processACK will handle the BreachArbitrator ACKing
3✔
1433
                        // the event.
3✔
1434
                        finalErr := make(chan error, 1)
3✔
1435
                        processACK := func(brarErr error) {
6✔
1436
                                if brarErr != nil {
3✔
1437
                                        finalErr <- brarErr
×
1438
                                        return
×
1439
                                }
×
1440

1441
                                // If the BreachArbitrator successfully handled
1442
                                // the event, we can signal that the handoff
1443
                                // was successful.
1444
                                finalErr <- nil
3✔
1445
                        }
1446

1447
                        event := &contractcourt.ContractBreachEvent{
3✔
1448
                                ChanPoint:         chanPoint,
3✔
1449
                                ProcessACK:        processACK,
3✔
1450
                                BreachRetribution: breachRet,
3✔
1451
                        }
3✔
1452

3✔
1453
                        // Send the contract breach event to the
3✔
1454
                        // BreachArbitrator.
3✔
1455
                        select {
3✔
1456
                        case contractBreaches <- event:
3✔
1457
                        case <-s.quit:
×
1458
                                return ErrServerShuttingDown
×
1459
                        }
1460

1461
                        // We'll wait for a final error to be available from
1462
                        // the BreachArbitrator.
1463
                        select {
3✔
1464
                        case err := <-finalErr:
3✔
1465
                                return err
3✔
1466
                        case <-s.quit:
×
1467
                                return ErrServerShuttingDown
×
1468
                        }
1469
                },
1470
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1471
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1472
                },
3✔
1473
                Sweeper:                       s.sweeper,
1474
                Registry:                      s.invoices,
1475
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1476
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1477
                OnionProcessor:                s.sphinx,
1478
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1479
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1480
                Clock:                         clock.NewDefaultClock(),
1481
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1482
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1483
                HtlcNotifier:                  s.htlcNotifier,
1484
                Budget:                        *s.cfg.Sweeper.Budget,
1485

1486
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1487
                QueryIncomingCircuit: func(
1488
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1489

3✔
1490
                        // Get the circuit map.
3✔
1491
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1492

3✔
1493
                        // Lookup the outgoing circuit.
3✔
1494
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1495
                        if pc == nil {
5✔
1496
                                return nil
2✔
1497
                        }
2✔
1498

1499
                        return &pc.Incoming
3✔
1500
                },
1501
                AuxLeafStore: implCfg.AuxLeafStore,
1502
                AuxSigner:    implCfg.AuxSigner,
1503
                AuxResolver:  implCfg.AuxContractResolver,
1504
        }, dbs.ChanStateDB)
1505

1506
        // Select the configuration and funding parameters for Bitcoin.
1507
        chainCfg := cfg.Bitcoin
3✔
1508
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1509
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1510

3✔
1511
        var chanIDSeed [32]byte
3✔
1512
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1513
                return nil, err
×
1514
        }
×
1515

1516
        // Wrap the DeleteChannelEdges method so that the funding manager can
1517
        // use it without depending on several layers of indirection.
1518
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1519
                *models.ChannelEdgePolicy, error) {
6✔
1520

3✔
1521
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1522
                        scid.ToUint64(),
3✔
1523
                )
3✔
1524
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1525
                        // This is unlikely but there is a slim chance of this
×
1526
                        // being hit if lnd was killed via SIGKILL and the
×
1527
                        // funding manager was stepping through the delete
×
1528
                        // alias edge logic.
×
1529
                        return nil, nil
×
1530
                } else if err != nil {
3✔
1531
                        return nil, err
×
1532
                }
×
1533

1534
                // Grab our key to find our policy.
1535
                var ourKey [33]byte
3✔
1536
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1537

3✔
1538
                var ourPolicy *models.ChannelEdgePolicy
3✔
1539
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1540
                        ourPolicy = e1
3✔
1541
                } else {
6✔
1542
                        ourPolicy = e2
3✔
1543
                }
3✔
1544

1545
                if ourPolicy == nil {
3✔
1546
                        // Something is wrong, so return an error.
×
1547
                        return nil, fmt.Errorf("we don't have an edge")
×
1548
                }
×
1549

1550
                err = s.graphDB.DeleteChannelEdges(
3✔
1551
                        false, false, scid.ToUint64(),
3✔
1552
                )
3✔
1553
                return ourPolicy, err
3✔
1554
        }
1555

1556
        // For the reservationTimeout and the zombieSweeperInterval different
1557
        // values are set in case we are in a dev environment so enhance test
1558
        // capacilities.
1559
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1560
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1561

3✔
1562
        // Get the development config for funding manager. If we are not in
3✔
1563
        // development mode, this would be nil.
3✔
1564
        var devCfg *funding.DevConfig
3✔
1565
        if lncfg.IsDevBuild() {
6✔
1566
                devCfg = &funding.DevConfig{
3✔
1567
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1568
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1569
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1570
                }
3✔
1571

3✔
1572
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1573
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1574

3✔
1575
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1576
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1577
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1578
        }
3✔
1579

1580
        //nolint:ll
1581
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1582
                Dev:                devCfg,
3✔
1583
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1584
                IDKey:              nodeKeyDesc.PubKey,
3✔
1585
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1586
                Wallet:             cc.Wallet,
3✔
1587
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1588
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1589
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1590
                },
3✔
1591
                Notifier:     cc.ChainNotifier,
1592
                ChannelDB:    s.chanStateDB,
1593
                FeeEstimator: cc.FeeEstimator,
1594
                SignMessage:  cc.MsgSigner.SignMessage,
1595
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1596
                        error) {
3✔
1597

3✔
1598
                        return s.genNodeAnnouncement(nil)
3✔
1599
                },
3✔
1600
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1601
                NotifyWhenOnline:     s.NotifyWhenOnline,
1602
                TempChanIDSeed:       chanIDSeed,
1603
                FindChannel:          s.findChannel,
1604
                DefaultRoutingPolicy: cc.RoutingPolicy,
1605
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1606
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1607
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1608
                        // For large channels we increase the number
3✔
1609
                        // of confirmations we require for the
3✔
1610
                        // channel to be considered open. As it is
3✔
1611
                        // always the responder that gets to choose
3✔
1612
                        // value, the pushAmt is value being pushed
3✔
1613
                        // to us. This means we have more to lose
3✔
1614
                        // in the case this gets re-orged out, and
3✔
1615
                        // we will require more confirmations before
3✔
1616
                        // we consider it open.
3✔
1617

3✔
1618
                        // In case the user has explicitly specified
3✔
1619
                        // a default value for the number of
3✔
1620
                        // confirmations, we use it.
3✔
1621
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1622
                        if defaultConf != 0 {
6✔
1623
                                return defaultConf
3✔
1624
                        }
3✔
1625

1626
                        minConf := uint64(3)
×
1627
                        maxConf := uint64(6)
×
1628

×
1629
                        // If this is a wumbo channel, then we'll require the
×
1630
                        // max amount of confirmations.
×
1631
                        if chanAmt > MaxFundingAmount {
×
1632
                                return uint16(maxConf)
×
1633
                        }
×
1634

1635
                        // If not we return a value scaled linearly
1636
                        // between 3 and 6, depending on channel size.
1637
                        // TODO(halseth): Use 1 as minimum?
1638
                        maxChannelSize := uint64(
×
1639
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1640
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1641
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1642
                        if conf < minConf {
×
1643
                                conf = minConf
×
1644
                        }
×
1645
                        if conf > maxConf {
×
1646
                                conf = maxConf
×
1647
                        }
×
1648
                        return uint16(conf)
×
1649
                },
1650
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1651
                        // We scale the remote CSV delay (the time the
3✔
1652
                        // remote have to claim funds in case of a unilateral
3✔
1653
                        // close) linearly from minRemoteDelay blocks
3✔
1654
                        // for small channels, to maxRemoteDelay blocks
3✔
1655
                        // for channels of size MaxFundingAmount.
3✔
1656

3✔
1657
                        // In case the user has explicitly specified
3✔
1658
                        // a default value for the remote delay, we
3✔
1659
                        // use it.
3✔
1660
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1661
                        if defaultDelay > 0 {
6✔
1662
                                return defaultDelay
3✔
1663
                        }
3✔
1664

1665
                        // If this is a wumbo channel, then we'll require the
1666
                        // max value.
1667
                        if chanAmt > MaxFundingAmount {
×
1668
                                return maxRemoteDelay
×
1669
                        }
×
1670

1671
                        // If not we scale according to channel size.
1672
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1673
                                chanAmt / MaxFundingAmount)
×
1674
                        if delay < minRemoteDelay {
×
1675
                                delay = minRemoteDelay
×
1676
                        }
×
1677
                        if delay > maxRemoteDelay {
×
1678
                                delay = maxRemoteDelay
×
1679
                        }
×
1680
                        return delay
×
1681
                },
1682
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1683
                        peerKey *btcec.PublicKey) error {
3✔
1684

3✔
1685
                        // First, we'll mark this new peer as a persistent peer
3✔
1686
                        // for re-connection purposes. If the peer is not yet
3✔
1687
                        // tracked or the user hasn't requested it to be perm,
3✔
1688
                        // we'll set false to prevent the server from continuing
3✔
1689
                        // to connect to this peer even if the number of
3✔
1690
                        // channels with this peer is zero.
3✔
1691
                        s.mu.Lock()
3✔
1692
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1693
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1694
                                s.persistentPeers[pubStr] = false
3✔
1695
                        }
3✔
1696
                        s.mu.Unlock()
3✔
1697

3✔
1698
                        // With that taken care of, we'll send this channel to
3✔
1699
                        // the chain arb so it can react to on-chain events.
3✔
1700
                        return s.chainArb.WatchNewChannel(channel)
3✔
1701
                },
1702
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1703
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1704
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1705
                },
3✔
1706
                RequiredRemoteChanReserve: func(chanAmt,
1707
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1708

3✔
1709
                        // By default, we'll require the remote peer to maintain
3✔
1710
                        // at least 1% of the total channel capacity at all
3✔
1711
                        // times. If this value ends up dipping below the dust
3✔
1712
                        // limit, then we'll use the dust limit itself as the
3✔
1713
                        // reserve as required by BOLT #2.
3✔
1714
                        reserve := chanAmt / 100
3✔
1715
                        if reserve < dustLimit {
6✔
1716
                                reserve = dustLimit
3✔
1717
                        }
3✔
1718

1719
                        return reserve
3✔
1720
                },
1721
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1722
                        // By default, we'll allow the remote peer to fully
3✔
1723
                        // utilize the full bandwidth of the channel, minus our
3✔
1724
                        // required reserve.
3✔
1725
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1726
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1727
                },
3✔
1728
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1729
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1730
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1731
                        }
3✔
1732

1733
                        // By default, we'll permit them to utilize the full
1734
                        // channel bandwidth.
1735
                        return uint16(input.MaxHTLCNumber / 2)
×
1736
                },
1737
                ZombieSweeperInterval:         zombieSweeperInterval,
1738
                ReservationTimeout:            reservationTimeout,
1739
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1740
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1741
                MaxPendingChannels:            cfg.MaxPendingChannels,
1742
                RejectPush:                    cfg.RejectPush,
1743
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1744
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1745
                OpenChannelPredicate:          chanPredicate,
1746
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1747
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1748
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1749
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1750
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1751
                DeleteAliasEdge:      deleteAliasEdge,
1752
                AliasManager:         s.aliasMgr,
1753
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1754
                AuxFundingController: implCfg.AuxFundingController,
1755
                AuxSigner:            implCfg.AuxSigner,
1756
                AuxResolver:          implCfg.AuxContractResolver,
1757
        })
1758
        if err != nil {
3✔
1759
                return nil, err
×
1760
        }
×
1761

1762
        // Next, we'll assemble the sub-system that will maintain an on-disk
1763
        // static backup of the latest channel state.
1764
        chanNotifier := &channelNotifier{
3✔
1765
                chanNotifier: s.channelNotifier,
3✔
1766
                addrs:        s.addrSource,
3✔
1767
        }
3✔
1768
        backupFile := chanbackup.NewMultiFile(
3✔
1769
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1770
        )
3✔
1771
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1772
                ctx, s.chanStateDB, s.addrSource,
3✔
1773
        )
3✔
1774
        if err != nil {
3✔
1775
                return nil, err
×
1776
        }
×
1777
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1778
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1779
        )
3✔
1780
        if err != nil {
3✔
1781
                return nil, err
×
1782
        }
×
1783

1784
        // Assemble a peer notifier which will provide clients with subscriptions
1785
        // to peer online and offline events.
1786
        s.peerNotifier = peernotifier.New()
3✔
1787

3✔
1788
        // Create a channel event store which monitors all open channels.
3✔
1789
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1790
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1791
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1792
                },
3✔
1793
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1794
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1795
                },
3✔
1796
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1797
                Clock:           clock.NewDefaultClock(),
1798
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1799
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1800
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1801
        })
1802

1803
        if cfg.WtClient.Active {
6✔
1804
                policy := wtpolicy.DefaultPolicy()
3✔
1805
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1806

3✔
1807
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1808
                // protocol operations on sat/kw.
3✔
1809
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1810
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1811
                )
3✔
1812

3✔
1813
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1814

3✔
1815
                if err := policy.Validate(); err != nil {
3✔
1816
                        return nil, err
×
1817
                }
×
1818

1819
                // authDial is the wrapper around the btrontide.Dial for the
1820
                // watchtower.
1821
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1822
                        netAddr *lnwire.NetAddress,
3✔
1823
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1824

3✔
1825
                        return brontide.Dial(
3✔
1826
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1827
                        )
3✔
1828
                }
3✔
1829

1830
                // buildBreachRetribution is a call-back that can be used to
1831
                // query the BreachRetribution info and channel type given a
1832
                // channel ID and commitment height.
1833
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1834
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1835
                        channeldb.ChannelType, error) {
6✔
1836

3✔
1837
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1838
                                nil, chanID,
3✔
1839
                        )
3✔
1840
                        if err != nil {
3✔
1841
                                return nil, 0, err
×
1842
                        }
×
1843

1844
                        br, err := lnwallet.NewBreachRetribution(
3✔
1845
                                channel, commitHeight, 0, nil,
3✔
1846
                                implCfg.AuxLeafStore,
3✔
1847
                                implCfg.AuxContractResolver,
3✔
1848
                        )
3✔
1849
                        if err != nil {
3✔
1850
                                return nil, 0, err
×
1851
                        }
×
1852

1853
                        return br, channel.ChanType, nil
3✔
1854
                }
1855

1856
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1857

3✔
1858
                // Copy the policy for legacy channels and set the blob flag
3✔
1859
                // signalling support for anchor channels.
3✔
1860
                anchorPolicy := policy
3✔
1861
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1862

3✔
1863
                // Copy the policy for legacy channels and set the blob flag
3✔
1864
                // signalling support for taproot channels.
3✔
1865
                taprootPolicy := policy
3✔
1866
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1867
                        blob.FlagTaprootChannel,
3✔
1868
                )
3✔
1869

3✔
1870
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1871
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1872
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1873
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1874
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1875
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1876
                                error) {
6✔
1877

3✔
1878
                                return s.channelNotifier.
3✔
1879
                                        SubscribeChannelEvents()
3✔
1880
                        },
3✔
1881
                        Signer: cc.Wallet.Cfg.Signer,
1882
                        NewAddress: func() ([]byte, error) {
3✔
1883
                                addr, err := newSweepPkScriptGen(
3✔
1884
                                        cc.Wallet, netParams,
3✔
1885
                                )().Unpack()
3✔
1886
                                if err != nil {
3✔
1887
                                        return nil, err
×
1888
                                }
×
1889

1890
                                return addr.DeliveryAddress, nil
3✔
1891
                        },
1892
                        SecretKeyRing:      s.cc.KeyRing,
1893
                        Dial:               cfg.net.Dial,
1894
                        AuthDial:           authDial,
1895
                        DB:                 dbs.TowerClientDB,
1896
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1897
                        MinBackoff:         10 * time.Second,
1898
                        MaxBackoff:         5 * time.Minute,
1899
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1900
                }, policy, anchorPolicy, taprootPolicy)
1901
                if err != nil {
3✔
1902
                        return nil, err
×
1903
                }
×
1904
        }
1905

1906
        if len(cfg.ExternalHosts) != 0 {
3✔
1907
                advertisedIPs := make(map[string]struct{})
×
1908
                for _, addr := range s.currentNodeAnn.Addresses {
×
1909
                        advertisedIPs[addr.String()] = struct{}{}
×
1910
                }
×
1911

1912
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1913
                        Hosts:         cfg.ExternalHosts,
×
1914
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1915
                        LookupHost: func(host string) (net.Addr, error) {
×
1916
                                return lncfg.ParseAddressString(
×
1917
                                        host, strconv.Itoa(defaultPeerPort),
×
1918
                                        cfg.net.ResolveTCPAddr,
×
1919
                                )
×
1920
                        },
×
1921
                        AdvertisedIPs: advertisedIPs,
1922
                        AnnounceNewIPs: netann.IPAnnouncer(
1923
                                func(modifier ...netann.NodeAnnModifier) (
1924
                                        lnwire.NodeAnnouncement, error) {
×
1925

×
1926
                                        return s.genNodeAnnouncement(
×
1927
                                                nil, modifier...,
×
1928
                                        )
×
1929
                                }),
×
1930
                })
1931
        }
1932

1933
        // Create liveness monitor.
1934
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1935

3✔
1936
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1937
        for i, listenAddr := range listenAddrs {
6✔
1938
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1939
                // doesn't need to call the general lndResolveTCP function
3✔
1940
                // since we are resolving a local address.
3✔
1941

3✔
1942
                // RESOLVE: We are actually partially accepting inbound
3✔
1943
                // connection requests when we call NewListener.
3✔
1944
                listeners[i], err = brontide.NewListener(
3✔
1945
                        nodeKeyECDH, listenAddr.String(),
3✔
1946
                        // TODO(yy): remove this check and unify the inbound
3✔
1947
                        // connection check inside `InboundPeerConnected`.
3✔
1948
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1949
                )
3✔
1950
                if err != nil {
3✔
1951
                        return nil, err
×
1952
                }
×
1953
        }
1954

1955
        // Create the connection manager which will be responsible for
1956
        // maintaining persistent outbound connections and also accepting new
1957
        // incoming connections
1958
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1959
                Listeners:      listeners,
3✔
1960
                OnAccept:       s.InboundPeerConnected,
3✔
1961
                RetryDuration:  time.Second * 5,
3✔
1962
                TargetOutbound: 100,
3✔
1963
                Dial: noiseDial(
3✔
1964
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1965
                ),
3✔
1966
                OnConnection: s.OutboundPeerConnected,
3✔
1967
        })
3✔
1968
        if err != nil {
3✔
1969
                return nil, err
×
1970
        }
×
1971
        s.connMgr = cmgr
3✔
1972

3✔
1973
        // Finally, register the subsystems in blockbeat.
3✔
1974
        s.registerBlockConsumers()
3✔
1975

3✔
1976
        return s, nil
3✔
1977
}
1978

1979
// UpdateRoutingConfig is a callback function to update the routing config
1980
// values in the main cfg.
1981
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1982
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1983

3✔
1984
        switch c := cfg.Estimator.Config().(type) {
3✔
1985
        case routing.AprioriConfig:
3✔
1986
                routerCfg.ProbabilityEstimatorType =
3✔
1987
                        routing.AprioriEstimatorName
3✔
1988

3✔
1989
                targetCfg := routerCfg.AprioriConfig
3✔
1990
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1991
                targetCfg.Weight = c.AprioriWeight
3✔
1992
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1993
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1994

1995
        case routing.BimodalConfig:
3✔
1996
                routerCfg.ProbabilityEstimatorType =
3✔
1997
                        routing.BimodalEstimatorName
3✔
1998

3✔
1999
                targetCfg := routerCfg.BimodalConfig
3✔
2000
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
2001
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
2002
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
2003
        }
2004

2005
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2006
}
2007

2008
// registerBlockConsumers registers the subsystems that consume block events.
2009
// By calling `RegisterQueue`, a list of subsystems are registered in the
2010
// blockbeat for block notifications. When a new block arrives, the subsystems
2011
// in the same queue are notified sequentially, and different queues are
2012
// notified concurrently.
2013
//
2014
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
2015
// a new `RegisterQueue` call.
2016
func (s *server) registerBlockConsumers() {
3✔
2017
        // In this queue, when a new block arrives, it will be received and
3✔
2018
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
2019
        consumers := []chainio.Consumer{
3✔
2020
                s.chainArb,
3✔
2021
                s.sweeper,
3✔
2022
                s.txPublisher,
3✔
2023
        }
3✔
2024
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
2025
}
3✔
2026

2027
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2028
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2029
// may differ from what is on disk.
2030
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2031
        error) {
3✔
2032

3✔
2033
        data, err := u.DataToSign()
3✔
2034
        if err != nil {
3✔
2035
                return nil, err
×
2036
        }
×
2037

2038
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2039
}
2040

2041
// createLivenessMonitor creates a set of health checks using our configured
2042
// values and uses these checks to create a liveness monitor. Available
2043
// health checks,
2044
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2045
//   - diskCheck
2046
//   - tlsHealthCheck
2047
//   - torController, only created when tor is enabled.
2048
//
2049
// If a health check has been disabled by setting attempts to 0, our monitor
2050
// will not run it.
2051
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2052
        leaderElector cluster.LeaderElector) {
3✔
2053

3✔
2054
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2055
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2056
                srvrLog.Info("Disabling chain backend checks for " +
×
2057
                        "nochainbackend mode")
×
2058

×
2059
                chainBackendAttempts = 0
×
2060
        }
×
2061

2062
        chainHealthCheck := healthcheck.NewObservation(
3✔
2063
                "chain backend",
3✔
2064
                cc.HealthCheck,
3✔
2065
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2066
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2067
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2068
                chainBackendAttempts,
3✔
2069
        )
3✔
2070

3✔
2071
        diskCheck := healthcheck.NewObservation(
3✔
2072
                "disk space",
3✔
2073
                func() error {
3✔
2074
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2075
                                cfg.LndDir,
×
2076
                        )
×
2077
                        if err != nil {
×
2078
                                return err
×
2079
                        }
×
2080

2081
                        // If we have more free space than we require,
2082
                        // we return a nil error.
2083
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2084
                                return nil
×
2085
                        }
×
2086

2087
                        return fmt.Errorf("require: %v free space, got: %v",
×
2088
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2089
                                free)
×
2090
                },
2091
                cfg.HealthChecks.DiskCheck.Interval,
2092
                cfg.HealthChecks.DiskCheck.Timeout,
2093
                cfg.HealthChecks.DiskCheck.Backoff,
2094
                cfg.HealthChecks.DiskCheck.Attempts,
2095
        )
2096

2097
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2098
                "tls",
3✔
2099
                func() error {
3✔
2100
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2101
                                s.cc.KeyRing,
×
2102
                        )
×
2103
                        if err != nil {
×
2104
                                return err
×
2105
                        }
×
2106
                        if expired {
×
2107
                                return fmt.Errorf("TLS certificate is "+
×
2108
                                        "expired as of %v", expTime)
×
2109
                        }
×
2110

2111
                        // If the certificate is not outdated, no error needs
2112
                        // to be returned
2113
                        return nil
×
2114
                },
2115
                cfg.HealthChecks.TLSCheck.Interval,
2116
                cfg.HealthChecks.TLSCheck.Timeout,
2117
                cfg.HealthChecks.TLSCheck.Backoff,
2118
                cfg.HealthChecks.TLSCheck.Attempts,
2119
        )
2120

2121
        checks := []*healthcheck.Observation{
3✔
2122
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2123
        }
3✔
2124

3✔
2125
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2126
        if s.torController != nil {
3✔
2127
                torConnectionCheck := healthcheck.NewObservation(
×
2128
                        "tor connection",
×
2129
                        func() error {
×
2130
                                return healthcheck.CheckTorServiceStatus(
×
2131
                                        s.torController,
×
2132
                                        func() error {
×
2133
                                                return s.createNewHiddenService(
×
2134
                                                        context.TODO(),
×
2135
                                                )
×
2136
                                        },
×
2137
                                )
2138
                        },
2139
                        cfg.HealthChecks.TorConnection.Interval,
2140
                        cfg.HealthChecks.TorConnection.Timeout,
2141
                        cfg.HealthChecks.TorConnection.Backoff,
2142
                        cfg.HealthChecks.TorConnection.Attempts,
2143
                )
2144
                checks = append(checks, torConnectionCheck)
×
2145
        }
2146

2147
        // If remote signing is enabled, add the healthcheck for the remote
2148
        // signing RPC interface.
2149
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2150
                // Because we have two cascading timeouts here, we need to add
3✔
2151
                // some slack to the "outer" one of them in case the "inner"
3✔
2152
                // returns exactly on time.
3✔
2153
                overhead := time.Millisecond * 10
3✔
2154

3✔
2155
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2156
                        "remote signer connection",
3✔
2157
                        rpcwallet.HealthCheck(
3✔
2158
                                s.cfg.RemoteSigner,
3✔
2159

3✔
2160
                                // For the health check we might to be even
3✔
2161
                                // stricter than the initial/normal connect, so
3✔
2162
                                // we use the health check timeout here.
3✔
2163
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2164
                        ),
3✔
2165
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2166
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2167
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2168
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2169
                )
3✔
2170
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2171
        }
3✔
2172

2173
        // If we have a leader elector, we add a health check to ensure we are
2174
        // still the leader. During normal operation, we should always be the
2175
        // leader, but there are circumstances where this may change, such as
2176
        // when we lose network connectivity for long enough expiring out lease.
2177
        if leaderElector != nil {
3✔
2178
                leaderCheck := healthcheck.NewObservation(
×
2179
                        "leader status",
×
2180
                        func() error {
×
2181
                                // Check if we are still the leader. Note that
×
2182
                                // we don't need to use a timeout context here
×
2183
                                // as the healthcheck observer will handle the
×
2184
                                // timeout case for us.
×
2185
                                timeoutCtx, cancel := context.WithTimeout(
×
2186
                                        context.Background(),
×
2187
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2188
                                )
×
2189
                                defer cancel()
×
2190

×
2191
                                leader, err := leaderElector.IsLeader(
×
2192
                                        timeoutCtx,
×
2193
                                )
×
2194
                                if err != nil {
×
2195
                                        return fmt.Errorf("unable to check if "+
×
2196
                                                "still leader: %v", err)
×
2197
                                }
×
2198

2199
                                if !leader {
×
2200
                                        srvrLog.Debug("Not the current leader")
×
2201
                                        return fmt.Errorf("not the current " +
×
2202
                                                "leader")
×
2203
                                }
×
2204

2205
                                return nil
×
2206
                        },
2207
                        cfg.HealthChecks.LeaderCheck.Interval,
2208
                        cfg.HealthChecks.LeaderCheck.Timeout,
2209
                        cfg.HealthChecks.LeaderCheck.Backoff,
2210
                        cfg.HealthChecks.LeaderCheck.Attempts,
2211
                )
2212

2213
                checks = append(checks, leaderCheck)
×
2214
        }
2215

2216
        // If we have not disabled all of our health checks, we create a
2217
        // liveness monitor with our configured checks.
2218
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2219
                &healthcheck.Config{
3✔
2220
                        Checks:   checks,
3✔
2221
                        Shutdown: srvrLog.Criticalf,
3✔
2222
                },
3✔
2223
        )
3✔
2224
}
2225

2226
// Started returns true if the server has been started, and false otherwise.
2227
// NOTE: This function is safe for concurrent access.
2228
func (s *server) Started() bool {
3✔
2229
        return atomic.LoadInt32(&s.active) != 0
3✔
2230
}
3✔
2231

2232
// cleaner is used to aggregate "cleanup" functions during an operation that
2233
// starts several subsystems. In case one of the subsystem fails to start
2234
// and a proper resource cleanup is required, the "run" method achieves this
2235
// by running all these added "cleanup" functions.
2236
type cleaner []func() error
2237

2238
// add is used to add a cleanup function to be called when
2239
// the run function is executed.
2240
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2241
        return append(c, cleanup)
3✔
2242
}
3✔
2243

2244
// run is used to run all the previousely added cleanup functions.
2245
func (c cleaner) run() {
×
2246
        for i := len(c) - 1; i >= 0; i-- {
×
2247
                if err := c[i](); err != nil {
×
2248
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2249
                }
×
2250
        }
2251
}
2252

2253
// startLowLevelServices starts the low-level services of the server. These
2254
// services must be started successfully before running the main server. The
2255
// services are,
2256
// 1. the chain notifier.
2257
//
2258
// TODO(yy): identify and add more low-level services here.
2259
func (s *server) startLowLevelServices() error {
3✔
2260
        var startErr error
3✔
2261

3✔
2262
        cleanup := cleaner{}
3✔
2263

3✔
2264
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2265
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2266
                startErr = err
×
2267
        }
×
2268

2269
        if startErr != nil {
3✔
2270
                cleanup.run()
×
2271
        }
×
2272

2273
        return startErr
3✔
2274
}
2275

2276
// Start starts the main daemon server, all requested listeners, and any helper
2277
// goroutines.
2278
// NOTE: This function is safe for concurrent access.
2279
//
2280
//nolint:funlen
2281
func (s *server) Start(ctx context.Context) error {
3✔
2282
        // Get the current blockbeat.
3✔
2283
        beat, err := s.getStartingBeat()
3✔
2284
        if err != nil {
3✔
2285
                return err
×
2286
        }
×
2287

2288
        var startErr error
3✔
2289

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

3✔
2295
        s.start.Do(func() {
6✔
2296
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2297
                if err := s.customMessageServer.Start(); err != nil {
3✔
2298
                        startErr = err
×
2299
                        return
×
2300
                }
×
2301

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

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

2318
                // Start the notification server. This is used so channel
2319
                // management goroutines can be notified when a funding
2320
                // transaction reaches a sufficient number of confirmations, or
2321
                // when the input for the funding transaction is spent in an
2322
                // attempt at an uncooperative close by the counterparty.
2323
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2324
                if err := s.sigPool.Start(); err != nil {
3✔
2325
                        startErr = err
×
2326
                        return
×
2327
                }
×
2328

2329
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2330
                if err := s.writePool.Start(); err != nil {
3✔
2331
                        startErr = err
×
2332
                        return
×
2333
                }
×
2334

2335
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2336
                if err := s.readPool.Start(); err != nil {
3✔
2337
                        startErr = err
×
2338
                        return
×
2339
                }
×
2340

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

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

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

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

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

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

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

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

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

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

2405
                // htlcSwitch must be started before chainArb since the latter
2406
                // relies on htlcSwitch to deliver resolution message upon
2407
                // start.
2408
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2409
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2410
                        startErr = err
×
2411
                        return
×
2412
                }
×
2413

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

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

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

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

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

2444
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2445
                if err := s.chanRouter.Start(); err != nil {
3✔
2446
                        startErr = err
×
2447
                        return
×
2448
                }
×
2449
                // The authGossiper depends on the chanRouter and therefore
2450
                // should be started after it.
2451
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2452
                if err := s.authGossiper.Start(); err != nil {
3✔
2453
                        startErr = err
×
2454
                        return
×
2455
                }
×
2456

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

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

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

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

2481
                cleanup.add(func() error {
3✔
2482
                        s.missionController.StopStoreTickers()
×
2483
                        return nil
×
2484
                })
×
2485
                s.missionController.RunStoreTickers()
3✔
2486

3✔
2487
                // Before we start the connMgr, we'll check to see if we have
3✔
2488
                // any backups to recover. We do this now as we want to ensure
3✔
2489
                // that have all the information we need to handle channel
3✔
2490
                // recovery _before_ we even accept connections from any peers.
3✔
2491
                chanRestorer := &chanDBRestorer{
3✔
2492
                        db:         s.chanStateDB,
3✔
2493
                        secretKeys: s.cc.KeyRing,
3✔
2494
                        chainArb:   s.chainArb,
3✔
2495
                }
3✔
2496
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2497
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2498
                                s.chansToRestore.PackedSingleChanBackups,
×
2499
                                s.cc.KeyRing, chanRestorer, s,
×
2500
                        )
×
2501
                        if err != nil {
×
2502
                                startErr = fmt.Errorf("unable to unpack single "+
×
2503
                                        "backups: %v", err)
×
2504
                                return
×
2505
                        }
×
2506
                }
2507
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2508
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2509
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2510
                                s.cc.KeyRing, chanRestorer, s,
3✔
2511
                        )
3✔
2512
                        if err != nil {
3✔
2513
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2514
                                        "backup: %v", err)
×
2515
                                return
×
2516
                        }
×
2517
                }
2518

2519
                // chanSubSwapper must be started after the `channelNotifier`
2520
                // because it depends on channel events as a synchronization
2521
                // point.
2522
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2523
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2524
                        startErr = err
×
2525
                        return
×
2526
                }
×
2527

2528
                if s.torController != nil {
3✔
2529
                        cleanup = cleanup.add(s.torController.Stop)
×
2530
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2531
                                startErr = err
×
2532
                                return
×
2533
                        }
×
2534
                }
2535

2536
                if s.natTraversal != nil {
3✔
2537
                        s.wg.Add(1)
×
2538
                        go s.watchExternalIP()
×
2539
                }
×
2540

2541
                // Start connmgr last to prevent connections before init.
2542
                cleanup = cleanup.add(func() error {
3✔
2543
                        s.connMgr.Stop()
×
2544
                        return nil
×
2545
                })
×
2546

2547
                // RESOLVE: s.connMgr.Start() is called here, but
2548
                // brontide.NewListener() is called in newServer. This means
2549
                // that we are actually listening and partially accepting
2550
                // inbound connections even before the connMgr starts.
2551
                //
2552
                // TODO(yy): move the log into the connMgr's `Start` method.
2553
                srvrLog.Info("connMgr starting...")
3✔
2554
                s.connMgr.Start()
3✔
2555
                srvrLog.Debug("connMgr started")
3✔
2556

3✔
2557
                // If peers are specified as a config option, we'll add those
3✔
2558
                // peers first.
3✔
2559
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2560
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2561
                                peerAddrCfg,
3✔
2562
                        )
3✔
2563
                        if err != nil {
3✔
2564
                                startErr = fmt.Errorf("unable to parse peer "+
×
2565
                                        "pubkey from config: %v", err)
×
2566
                                return
×
2567
                        }
×
2568
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2569
                        if err != nil {
3✔
2570
                                startErr = fmt.Errorf("unable to parse peer "+
×
2571
                                        "address provided as a config option: "+
×
2572
                                        "%v", err)
×
2573
                                return
×
2574
                        }
×
2575

2576
                        peerAddr := &lnwire.NetAddress{
3✔
2577
                                IdentityKey: parsedPubkey,
3✔
2578
                                Address:     addr,
3✔
2579
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2580
                        }
3✔
2581

3✔
2582
                        err = s.ConnectToPeer(
3✔
2583
                                peerAddr, true,
3✔
2584
                                s.cfg.ConnectionTimeout,
3✔
2585
                        )
3✔
2586
                        if err != nil {
3✔
2587
                                startErr = fmt.Errorf("unable to connect to "+
×
2588
                                        "peer address provided as a config "+
×
2589
                                        "option: %v", err)
×
2590
                                return
×
2591
                        }
×
2592
                }
2593

2594
                // Subscribe to NodeAnnouncements that advertise new addresses
2595
                // our persistent peers.
2596
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2597
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2598
                                "addr: %v", err)
×
2599

×
2600
                        startErr = err
×
2601
                        return
×
2602
                }
×
2603

2604
                // With all the relevant sub-systems started, we'll now attempt
2605
                // to establish persistent connections to our direct channel
2606
                // collaborators within the network. Before doing so however,
2607
                // we'll prune our set of link nodes found within the database
2608
                // to ensure we don't reconnect to any nodes we no longer have
2609
                // open channels with.
2610
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2611
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2612

×
2613
                        startErr = err
×
2614
                        return
×
2615
                }
×
2616

2617
                if err := s.establishPersistentConnections(ctx); err != nil {
3✔
2618
                        srvrLog.Errorf("Failed to establish persistent "+
×
2619
                                "connections: %v", err)
×
2620
                }
×
2621

2622
                // setSeedList is a helper function that turns multiple DNS seed
2623
                // server tuples from the command line or config file into the
2624
                // data structure we need and does a basic formal sanity check
2625
                // in the process.
2626
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2627
                        if len(tuples) == 0 {
×
2628
                                return
×
2629
                        }
×
2630

2631
                        result := make([][2]string, len(tuples))
×
2632
                        for idx, tuple := range tuples {
×
2633
                                tuple = strings.TrimSpace(tuple)
×
2634
                                if len(tuple) == 0 {
×
2635
                                        return
×
2636
                                }
×
2637

2638
                                servers := strings.Split(tuple, ",")
×
2639
                                if len(servers) > 2 || len(servers) == 0 {
×
2640
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2641
                                                "seed tuple: %v", servers)
×
2642
                                        return
×
2643
                                }
×
2644

2645
                                copy(result[idx][:], servers)
×
2646
                        }
2647

2648
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2649
                }
2650

2651
                // Let users overwrite the DNS seed nodes. We only allow them
2652
                // for bitcoin mainnet/testnet/signet.
2653
                if s.cfg.Bitcoin.MainNet {
3✔
2654
                        setSeedList(
×
2655
                                s.cfg.Bitcoin.DNSSeeds,
×
2656
                                chainreg.BitcoinMainnetGenesis,
×
2657
                        )
×
2658
                }
×
2659
                if s.cfg.Bitcoin.TestNet3 {
3✔
2660
                        setSeedList(
×
2661
                                s.cfg.Bitcoin.DNSSeeds,
×
2662
                                chainreg.BitcoinTestnetGenesis,
×
2663
                        )
×
2664
                }
×
2665
                if s.cfg.Bitcoin.TestNet4 {
3✔
2666
                        setSeedList(
×
2667
                                s.cfg.Bitcoin.DNSSeeds,
×
2668
                                chainreg.BitcoinTestnet4Genesis,
×
2669
                        )
×
2670
                }
×
2671
                if s.cfg.Bitcoin.SigNet {
3✔
2672
                        setSeedList(
×
2673
                                s.cfg.Bitcoin.DNSSeeds,
×
2674
                                chainreg.BitcoinSignetGenesis,
×
2675
                        )
×
2676
                }
×
2677

2678
                // If network bootstrapping hasn't been disabled, then we'll
2679
                // configure the set of active bootstrappers, and launch a
2680
                // dedicated goroutine to maintain a set of persistent
2681
                // connections.
2682
                if !s.cfg.NoNetBootstrap {
6✔
2683
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2684
                        if err != nil {
3✔
2685
                                startErr = err
×
2686
                                return
×
2687
                        }
×
2688

2689
                        s.wg.Add(1)
3✔
2690
                        go s.peerBootstrapper(
3✔
2691
                                ctx, defaultMinPeers, bootstrappers,
3✔
2692
                        )
3✔
2693
                } else {
3✔
2694
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2695
                }
3✔
2696

2697
                // Start the blockbeat after all other subsystems have been
2698
                // started so they are ready to receive new blocks.
2699
                cleanup = cleanup.add(func() error {
3✔
2700
                        s.blockbeatDispatcher.Stop()
×
2701
                        return nil
×
2702
                })
×
2703
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2704
                        startErr = err
×
2705
                        return
×
2706
                }
×
2707

2708
                // Set the active flag now that we've completed the full
2709
                // startup.
2710
                atomic.StoreInt32(&s.active, 1)
3✔
2711
        })
2712

2713
        if startErr != nil {
3✔
2714
                cleanup.run()
×
2715
        }
×
2716
        return startErr
3✔
2717
}
2718

2719
// Stop gracefully shutsdown the main daemon server. This function will signal
2720
// any active goroutines, or helper objects to exit, then blocks until they've
2721
// all successfully exited. Additionally, any/all listeners are closed.
2722
// NOTE: This function is safe for concurrent access.
2723
func (s *server) Stop() error {
3✔
2724
        s.stop.Do(func() {
6✔
2725
                atomic.StoreInt32(&s.stopping, 1)
3✔
2726

3✔
2727
                ctx := context.Background()
3✔
2728

3✔
2729
                close(s.quit)
3✔
2730

3✔
2731
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2732
                s.connMgr.Stop()
3✔
2733

3✔
2734
                // Stop dispatching blocks to other systems immediately.
3✔
2735
                s.blockbeatDispatcher.Stop()
3✔
2736

3✔
2737
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2738
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2739
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2740
                }
×
2741
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2742
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2743
                }
×
2744
                if err := s.sphinx.Stop(); err != nil {
3✔
2745
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2746
                }
×
2747
                if err := s.invoices.Stop(); err != nil {
3✔
2748
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2749
                }
×
2750
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2751
                        srvrLog.Warnf("failed to stop interceptable "+
×
2752
                                "switch: %v", err)
×
2753
                }
×
2754
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2755
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2756
                                "modifier: %v", err)
×
2757
                }
×
2758
                if err := s.chanRouter.Stop(); err != nil {
3✔
2759
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2760
                }
×
2761
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2762
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2763
                }
×
2764
                if err := s.graphDB.Stop(); err != nil {
3✔
2765
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2766
                }
×
2767
                if err := s.chainArb.Stop(); err != nil {
3✔
2768
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2769
                }
×
2770
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2771
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2772
                }
×
2773
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2774
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2775
                                err)
×
2776
                }
×
2777
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2778
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2779
                }
×
2780
                if err := s.authGossiper.Stop(); err != nil {
3✔
2781
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2782
                }
×
2783
                if err := s.sweeper.Stop(); err != nil {
3✔
2784
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2785
                }
×
2786
                if err := s.txPublisher.Stop(); err != nil {
3✔
2787
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2788
                }
×
2789
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2790
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2791
                }
×
2792
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2793
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2794
                }
×
2795
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2796
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2797
                }
×
2798

2799
                // Update channel.backup file. Make sure to do it before
2800
                // stopping chanSubSwapper.
2801
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2802
                        ctx, s.chanStateDB, s.addrSource,
3✔
2803
                )
3✔
2804
                if err != nil {
3✔
2805
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2806
                                err)
×
2807
                } else {
3✔
2808
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2809
                        if err != nil {
6✔
2810
                                srvrLog.Warnf("Manual update of channel "+
3✔
2811
                                        "backup failed: %v", err)
3✔
2812
                        }
3✔
2813
                }
2814

2815
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2816
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2817
                }
×
2818
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2819
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2820
                }
×
2821
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2822
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2823
                                err)
×
2824
                }
×
2825
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2826
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2827
                                err)
×
2828
                }
×
2829
                s.missionController.StopStoreTickers()
3✔
2830

3✔
2831
                // Disconnect from each active peers to ensure that
3✔
2832
                // peerTerminationWatchers signal completion to each peer.
3✔
2833
                for _, peer := range s.Peers() {
6✔
2834
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2835
                        if err != nil {
3✔
2836
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2837
                                        "received error: %v", peer.IdentityKey(),
×
2838
                                        err,
×
2839
                                )
×
2840
                        }
×
2841
                }
2842

2843
                // Now that all connections have been torn down, stop the tower
2844
                // client which will reliably flush all queued states to the
2845
                // tower. If this is halted for any reason, the force quit timer
2846
                // will kick in and abort to allow this method to return.
2847
                if s.towerClientMgr != nil {
6✔
2848
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2849
                                srvrLog.Warnf("Unable to shut down tower "+
×
2850
                                        "client manager: %v", err)
×
2851
                        }
×
2852
                }
2853

2854
                if s.hostAnn != nil {
3✔
2855
                        if err := s.hostAnn.Stop(); err != nil {
×
2856
                                srvrLog.Warnf("unable to shut down host "+
×
2857
                                        "annoucner: %v", err)
×
2858
                        }
×
2859
                }
2860

2861
                if s.livenessMonitor != nil {
6✔
2862
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2863
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2864
                                        "monitor: %v", err)
×
2865
                        }
×
2866
                }
2867

2868
                // Wait for all lingering goroutines to quit.
2869
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2870
                s.wg.Wait()
3✔
2871

3✔
2872
                srvrLog.Debug("Stopping buffer pools...")
3✔
2873
                s.sigPool.Stop()
3✔
2874
                s.writePool.Stop()
3✔
2875
                s.readPool.Stop()
3✔
2876
        })
2877

2878
        return nil
3✔
2879
}
2880

2881
// Stopped returns true if the server has been instructed to shutdown.
2882
// NOTE: This function is safe for concurrent access.
2883
func (s *server) Stopped() bool {
3✔
2884
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2885
}
3✔
2886

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

×
2899
        externalIPs := make([]string, 0, len(ports))
×
2900
        for _, port := range ports {
×
2901
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2902
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2903
                        continue
×
2904
                }
2905

2906
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2907
                externalIPs = append(externalIPs, hostIP)
×
2908
        }
2909

2910
        return externalIPs, nil
×
2911
}
2912

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

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

×
2937
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2938
        // up by the server.
×
2939
        defer s.removePortForwarding()
×
2940

×
2941
        // Keep track of the external IPs set by the user to avoid replacing
×
2942
        // them when detecting a new IP.
×
2943
        ipsSetByUser := make(map[string]struct{})
×
2944
        for _, ip := range s.cfg.ExternalIPs {
×
2945
                ipsSetByUser[ip.String()] = struct{}{}
×
2946
        }
×
2947

2948
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2949

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

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

2980
                        if ip.Equal(s.lastDetectedIP) {
×
2981
                                continue
×
2982
                        }
2983

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

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

3001
                                newAddrs = append(newAddrs, addr)
×
3002
                        }
3003

3004
                        // Skip the update if we weren't able to resolve any of
3005
                        // the new addresses.
3006
                        if len(newAddrs) == 0 {
×
3007
                                srvrLog.Debug("Skipping node announcement " +
×
3008
                                        "update due to not being able to " +
×
3009
                                        "resolve any new addresses")
×
3010
                                continue
×
3011
                        }
3012

3013
                        // Now, we'll need to update the addresses in our node's
3014
                        // announcement in order to propagate the update
3015
                        // throughout the network. We'll only include addresses
3016
                        // that have a different IP from the previous one, as
3017
                        // the previous IP is no longer valid.
3018
                        currentNodeAnn := s.getNodeAnnouncement()
×
3019

×
3020
                        for _, addr := range currentNodeAnn.Addresses {
×
3021
                                host, _, err := net.SplitHostPort(addr.String())
×
3022
                                if err != nil {
×
3023
                                        srvrLog.Debugf("Unable to determine "+
×
3024
                                                "host from address %v: %v",
×
3025
                                                addr, err)
×
3026
                                        continue
×
3027
                                }
3028

3029
                                // We'll also make sure to include external IPs
3030
                                // set manually by the user.
3031
                                _, setByUser := ipsSetByUser[addr.String()]
×
3032
                                if setByUser || host != s.lastDetectedIP.String() {
×
3033
                                        newAddrs = append(newAddrs, addr)
×
3034
                                }
×
3035
                        }
3036

3037
                        // Then, we'll generate a new timestamped node
3038
                        // announcement with the updated addresses and broadcast
3039
                        // it to our peers.
3040
                        newNodeAnn, err := s.genNodeAnnouncement(
×
3041
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
3042
                        )
×
3043
                        if err != nil {
×
3044
                                srvrLog.Debugf("Unable to generate new node "+
×
3045
                                        "announcement: %v", err)
×
3046
                                continue
×
3047
                        }
3048

3049
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3050
                        if err != nil {
×
3051
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3052
                                        "announcement to peers: %v", err)
×
3053
                                continue
×
3054
                        }
3055

3056
                        // Finally, update the last IP seen to the current one.
3057
                        s.lastDetectedIP = ip
×
3058
                case <-s.quit:
×
3059
                        break out
×
3060
                }
3061
        }
3062
}
3063

3064
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3065
// based on the server, and currently active bootstrap mechanisms as defined
3066
// within the current configuration.
3067
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
3✔
3068
        srvrLog.Infof("Initializing peer network bootstrappers!")
3✔
3069

3✔
3070
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3071

3✔
3072
        // First, we'll create an instance of the ChannelGraphBootstrapper as
3✔
3073
        // this can be used by default if we've already partially seeded the
3✔
3074
        // network.
3✔
3075
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
3✔
3076
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
3✔
3077
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
3✔
3078
        )
3✔
3079
        if err != nil {
3✔
3080
                return nil, err
×
3081
        }
×
3082
        bootStrappers = append(bootStrappers, graphBootstrapper)
3✔
3083

3✔
3084
        // If this isn't using simnet or regtest mode, then one of our
3✔
3085
        // additional bootstrapping sources will be the set of running DNS
3✔
3086
        // seeds.
3✔
3087
        if !s.cfg.Bitcoin.IsLocalNetwork() {
3✔
3088
                //nolint:ll
×
3089
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3090

×
3091
                // If we have a set of DNS seeds for this chain, then we'll add
×
3092
                // it as an additional bootstrapping source.
×
3093
                if ok {
×
3094
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3095
                                "seeds: %v", dnsSeeds)
×
3096

×
3097
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3098
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3099
                        )
×
3100
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3101
                }
×
3102
        }
3103

3104
        return bootStrappers, nil
3✔
3105
}
3106

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

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

3✔
3119
        // We should ignore ourselves from bootstrapping.
3✔
3120
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3121
        ignore[selfKey] = struct{}{}
3✔
3122

3✔
3123
        // Ignore all connected peers.
3✔
3124
        for _, peer := range s.peersByPub {
3✔
3125
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3126
                ignore[nID] = struct{}{}
×
3127
        }
×
3128

3129
        // Ignore all persistent peers as they have a dedicated reconnecting
3130
        // process.
3131
        for pubKeyStr := range s.persistentPeers {
3✔
3132
                var nID autopilot.NodeID
×
3133
                copy(nID[:], []byte(pubKeyStr))
×
3134
                ignore[nID] = struct{}{}
×
3135
        }
×
3136

3137
        return ignore
3✔
3138
}
3139

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

3✔
3148
        defer s.wg.Done()
3✔
3149

3✔
3150
        // Before we continue, init the ignore peers map.
3✔
3151
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3152

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

3✔
3157
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3158
        // peers.
3✔
3159
        //
3✔
3160
        // We'll use a 15 second backoff, and double the time every time an
3✔
3161
        // epoch fails up to a ceiling.
3✔
3162
        backOff := time.Second * 15
3✔
3163

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

3✔
3169
        // We'll use the number of attempts and errors to determine if we need
3✔
3170
        // to increase the time between discovery epochs.
3✔
3171
        var epochErrors uint32 // To be used atomically.
3✔
3172
        var epochAttempts uint32
3✔
3173

3✔
3174
        for {
6✔
3175
                select {
3✔
3176
                // The ticker has just woken us up, so we'll need to check if
3177
                // we need to attempt to connect our to any more peers.
3178
                case <-sampleTicker.C:
×
3179
                        // Obtain the current number of peers, so we can gauge
×
3180
                        // if we need to sample more peers or not.
×
3181
                        s.mu.RLock()
×
3182
                        numActivePeers := uint32(len(s.peersByPub))
×
3183
                        s.mu.RUnlock()
×
3184

×
3185
                        // If we have enough peers, then we can loop back
×
3186
                        // around to the next round as we're done here.
×
3187
                        if numActivePeers >= numTargetPeers {
×
3188
                                continue
×
3189
                        }
3190

3191
                        // If all of our attempts failed during this last back
3192
                        // off period, then will increase our backoff to 5
3193
                        // minute ceiling to avoid an excessive number of
3194
                        // queries
3195
                        //
3196
                        // TODO(roasbeef): add reverse policy too?
3197

3198
                        if epochAttempts > 0 &&
×
3199
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3200

×
3201
                                sampleTicker.Stop()
×
3202

×
3203
                                backOff *= 2
×
3204
                                if backOff > bootstrapBackOffCeiling {
×
3205
                                        backOff = bootstrapBackOffCeiling
×
3206
                                }
×
3207

3208
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3209
                                        "%v", backOff)
×
3210
                                sampleTicker = time.NewTicker(backOff)
×
3211
                                continue
×
3212
                        }
3213

3214
                        atomic.StoreUint32(&epochErrors, 0)
×
3215
                        epochAttempts = 0
×
3216

×
3217
                        // Since we know need more peers, we'll compute the
×
3218
                        // exact number we need to reach our threshold.
×
3219
                        numNeeded := numTargetPeers - numActivePeers
×
3220

×
3221
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3222
                                "peers", numNeeded)
×
3223

×
3224
                        // With the number of peers we need calculated, we'll
×
3225
                        // query the network bootstrappers to sample a set of
×
3226
                        // random addrs for us.
×
3227
                        //
×
3228
                        // Before we continue, get a copy of the ignore peers
×
3229
                        // map.
×
3230
                        ignoreList = s.createBootstrapIgnorePeers()
×
3231

×
3232
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3233
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3234
                        )
×
3235
                        if err != nil {
×
3236
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3237
                                        "peers: %v", err)
×
3238
                                continue
×
3239
                        }
3240

3241
                        // Finally, we'll launch a new goroutine for each
3242
                        // prospective peer candidates.
3243
                        for _, addr := range peerAddrs {
×
3244
                                epochAttempts++
×
3245

×
3246
                                go func(a *lnwire.NetAddress) {
×
3247
                                        // TODO(roasbeef): can do AS, subnet,
×
3248
                                        // country diversity, etc
×
3249
                                        errChan := make(chan error, 1)
×
3250
                                        s.connectToPeer(
×
3251
                                                a, errChan,
×
3252
                                                s.cfg.ConnectionTimeout,
×
3253
                                        )
×
3254
                                        select {
×
3255
                                        case err := <-errChan:
×
3256
                                                if err == nil {
×
3257
                                                        return
×
3258
                                                }
×
3259

3260
                                                srvrLog.Errorf("Unable to "+
×
3261
                                                        "connect to %v: %v",
×
3262
                                                        a, err)
×
3263
                                                atomic.AddUint32(&epochErrors, 1)
×
3264
                                        case <-s.quit:
×
3265
                                        }
3266
                                }(addr)
3267
                        }
3268
                case <-s.quit:
3✔
3269
                        return
3✔
3270
                }
3271
        }
3272
}
3273

3274
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3275
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3276
// query back off each time we encounter a failure.
3277
const bootstrapBackOffCeiling = time.Minute * 5
3278

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

3✔
3286
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3287
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3288

3✔
3289
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3290
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3291
        var delaySignal <-chan time.Time
3✔
3292
        delayTime := time.Second * 2
3✔
3293

3✔
3294
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3295
        // then the main peer bootstrap logic.
3✔
3296
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3297

3✔
3298
        for attempts := 0; ; attempts++ {
6✔
3299
                // Check if the server has been requested to shut down in order
3✔
3300
                // to prevent blocking.
3✔
3301
                if s.Stopped() {
3✔
3302
                        return
×
3303
                }
×
3304

3305
                // We can exit our aggressive initial peer bootstrapping stage
3306
                // if we've reached out target number of peers.
3307
                s.mu.RLock()
3✔
3308
                numActivePeers := uint32(len(s.peersByPub))
3✔
3309
                s.mu.RUnlock()
3✔
3310

3✔
3311
                if numActivePeers >= numTargetPeers {
6✔
3312
                        return
3✔
3313
                }
3✔
3314

3315
                if attempts > 0 {
3✔
3316
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3317
                                "bootstrap peers (attempt #%v)", delayTime,
×
3318
                                attempts)
×
3319

×
3320
                        // We've completed at least one iterating and haven't
×
3321
                        // finished, so we'll start to insert a delay period
×
3322
                        // between each attempt.
×
3323
                        delaySignal = time.After(delayTime)
×
3324
                        select {
×
3325
                        case <-delaySignal:
×
3326
                        case <-s.quit:
×
3327
                                return
×
3328
                        }
3329

3330
                        // After our delay, we'll double the time we wait up to
3331
                        // the max back off period.
3332
                        delayTime *= 2
×
3333
                        if delayTime > backOffCeiling {
×
3334
                                delayTime = backOffCeiling
×
3335
                        }
×
3336
                }
3337

3338
                // Otherwise, we'll request for the remaining number of peers
3339
                // in order to reach our target.
3340
                peersNeeded := numTargetPeers - numActivePeers
3✔
3341
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3342
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3343
                )
3✔
3344
                if err != nil {
3✔
3345
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3346
                                "peers: %v", err)
×
3347
                        continue
×
3348
                }
3349

3350
                // Then, we'll attempt to establish a connection to the
3351
                // different peer addresses retrieved by our bootstrappers.
3352
                var wg sync.WaitGroup
3✔
3353
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3354
                        wg.Add(1)
3✔
3355
                        go func(addr *lnwire.NetAddress) {
6✔
3356
                                defer wg.Done()
3✔
3357

3✔
3358
                                errChan := make(chan error, 1)
3✔
3359
                                go s.connectToPeer(
3✔
3360
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3361
                                )
3✔
3362

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

3386
                wg.Wait()
3✔
3387
        }
3388
}
3389

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

3402
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3403
        if err != nil {
×
3404
                return err
×
3405
        }
×
3406

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

×
3419
        switch {
×
3420
        case s.cfg.Tor.V2:
×
3421
                onionCfg.Type = tor.V2
×
3422
        case s.cfg.Tor.V3:
×
3423
                onionCfg.Type = tor.V3
×
3424
        }
3425

3426
        addr, err := s.torController.AddOnion(onionCfg)
×
3427
        if err != nil {
×
3428
                return err
×
3429
        }
×
3430

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

3443
        // Finally, we'll update the on-disk version of our announcement so it
3444
        // will eventually propagate to nodes in the network.
3445
        selfNode := &models.LightningNode{
×
3446
                HaveNodeAnnouncement: true,
×
3447
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3448
                Addresses:            newNodeAnn.Addresses,
×
3449
                Alias:                newNodeAnn.Alias.String(),
×
3450
                Features: lnwire.NewFeatureVector(
×
3451
                        newNodeAnn.Features, lnwire.Features,
×
3452
                ),
×
3453
                Color:        newNodeAnn.RGBColor,
×
3454
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3455
        }
×
3456
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3457
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3458
                return fmt.Errorf("can't set self node: %w", err)
×
3459
        }
×
3460

3461
        return nil
×
3462
}
3463

3464
// findChannel finds a channel given a public key and ChannelID. It is an
3465
// optimization that is quicker than seeking for a channel given only the
3466
// ChannelID.
3467
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3468
        *channeldb.OpenChannel, error) {
3✔
3469

3✔
3470
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3471
        if err != nil {
3✔
3472
                return nil, err
×
3473
        }
×
3474

3475
        for _, channel := range nodeChans {
6✔
3476
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3477
                        return channel, nil
3✔
3478
                }
3✔
3479
        }
3480

3481
        return nil, fmt.Errorf("unable to find channel")
3✔
3482
}
3483

3484
// getNodeAnnouncement fetches the current, fully signed node announcement.
3485
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3486
        s.mu.Lock()
3✔
3487
        defer s.mu.Unlock()
3✔
3488

3✔
3489
        return *s.currentNodeAnn
3✔
3490
}
3✔
3491

3492
// genNodeAnnouncement generates and returns the current fully signed node
3493
// announcement. The time stamp of the announcement will be updated in order
3494
// to ensure it propagates through the network.
3495
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3496
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3497

3✔
3498
        s.mu.Lock()
3✔
3499
        defer s.mu.Unlock()
3✔
3500

3✔
3501
        // Create a shallow copy of the current node announcement to work on.
3✔
3502
        // This ensures the original announcement remains unchanged
3✔
3503
        // until the new announcement is fully signed and valid.
3✔
3504
        newNodeAnn := *s.currentNodeAnn
3✔
3505

3✔
3506
        // First, try to update our feature manager with the updated set of
3✔
3507
        // features.
3✔
3508
        if features != nil {
6✔
3509
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3510
                        feature.SetNodeAnn: features,
3✔
3511
                }
3✔
3512
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3513
                if err != nil {
6✔
3514
                        return lnwire.NodeAnnouncement{}, err
3✔
3515
                }
3✔
3516

3517
                // If we could successfully update our feature manager, add
3518
                // an update modifier to include these new features to our
3519
                // set.
3520
                modifiers = append(
3✔
3521
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3522
                )
3✔
3523
        }
3524

3525
        // Always update the timestamp when refreshing to ensure the update
3526
        // propagates.
3527
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3528

3✔
3529
        // Apply the requested changes to the node announcement.
3✔
3530
        for _, modifier := range modifiers {
6✔
3531
                modifier(&newNodeAnn)
3✔
3532
        }
3✔
3533

3534
        // Sign a new update after applying all of the passed modifiers.
3535
        err := netann.SignNodeAnnouncement(
3✔
3536
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3537
        )
3✔
3538
        if err != nil {
3✔
3539
                return lnwire.NodeAnnouncement{}, err
×
3540
        }
×
3541

3542
        // If signing succeeds, update the current announcement.
3543
        *s.currentNodeAnn = newNodeAnn
3✔
3544

3✔
3545
        return *s.currentNodeAnn, nil
3✔
3546
}
3547

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

3✔
3556
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3557
        if err != nil {
6✔
3558
                return fmt.Errorf("unable to generate new node "+
3✔
3559
                        "announcement: %v", err)
3✔
3560
        }
3✔
3561

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

3570
        selfNode.HaveNodeAnnouncement = true
3✔
3571
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3572
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3573
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3574
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3575
        selfNode.Color = newNodeAnn.RGBColor
3✔
3576
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3577

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

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

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

3592
        return nil
3✔
3593
}
3594

3595
type nodeAddresses struct {
3596
        pubKey    *btcec.PublicKey
3597
        addresses []net.Addr
3598
}
3599

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

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

3618
        for _, node := range linkNodes {
6✔
3619
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3620
                nodeAddrs := &nodeAddresses{
3✔
3621
                        pubKey:    node.IdentityPub,
3✔
3622
                        addresses: node.Addresses,
3✔
3623
                }
3✔
3624
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3625
        }
3✔
3626

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

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

3644
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3645

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

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

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

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

3684
                // Construct a slice of the deduped addresses.
3685
                var addrs []net.Addr
3✔
3686
                for _, addr := range addrSet {
6✔
3687
                        addrs = append(addrs, addr)
3✔
3688
                }
3✔
3689

3690
                n := &nodeAddresses{
3✔
3691
                        addresses: addrs,
3✔
3692
                }
3✔
3693
                n.pubKey, err = channelPeer.PubKey()
3✔
3694
                if err != nil {
3✔
3695
                        return err
×
3696
                }
×
3697

3698
                graphAddrs[pubStr] = n
3✔
3699
                return nil
3✔
3700
        }
3701
        err = s.graphDB.ForEachSourceNodeChannel(
3✔
3702
                ctx, forEachSrcNodeChan, func() {
6✔
3703
                        clear(graphAddrs)
3✔
3704
                },
3✔
3705
        )
3706
        if err != nil {
3✔
3707
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3708
                        "%v", err)
×
3709

×
3710
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3711
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3712

×
3713
                        return err
×
3714
                }
×
3715
        }
3716

3717
        // Combine the addresses from the link nodes and the channel graph.
3718
        for pubStr, nodeAddr := range graphAddrs {
6✔
3719
                nodeAddrsMap[pubStr] = nodeAddr
3✔
3720
        }
3✔
3721

3722
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3723
                len(nodeAddrsMap))
3✔
3724

3✔
3725
        // Acquire and hold server lock until all persistent connection requests
3✔
3726
        // have been recorded and sent to the connection manager.
3✔
3727
        s.mu.Lock()
3✔
3728
        defer s.mu.Unlock()
3✔
3729

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

3744
                for _, address := range nodeAddr.addresses {
6✔
3745
                        // Create a wrapper address which couples the IP and
3✔
3746
                        // the pubkey so the brontide authenticated connection
3✔
3747
                        // can be established.
3✔
3748
                        lnAddr := &lnwire.NetAddress{
3✔
3749
                                IdentityKey: nodeAddr.pubKey,
3✔
3750
                                Address:     address,
3✔
3751
                        }
3✔
3752

3✔
3753
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3754
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3755
                }
3✔
3756

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

3✔
3767
                        go s.connectToPersistentPeer(pubStr)
3✔
3768
                } else {
3✔
3769
                        go s.delayInitialReconnect(pubStr)
×
3770
                }
×
3771

3772
                numOutboundConns++
3✔
3773
        }
3774

3775
        return nil
3✔
3776
}
3777

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

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

3✔
3797
        s.mu.Lock()
3✔
3798
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3799
                delete(s.persistentPeers, pubKeyStr)
3✔
3800
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3801
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3802
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3803
                s.mu.Unlock()
3✔
3804

3✔
3805
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3806
                        "peer has no open channels", compressedPubKey)
3✔
3807

3✔
3808
                return
3✔
3809
        }
3✔
3810
        s.mu.Unlock()
3✔
3811
}
3812

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

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

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

3853
                peers = append(peers, sPeer)
3✔
3854
        }
3855
        s.mu.RUnlock()
3✔
3856

3✔
3857
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3858
        // all messages to each of peers.
3✔
3859
        var wg sync.WaitGroup
3✔
3860
        for _, sPeer := range peers {
6✔
3861
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3862
                        sPeer.PubKey())
3✔
3863

3✔
3864
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3865
                wg.Add(1)
3✔
3866
                s.wg.Add(1)
3✔
3867
                go func(p lnpeer.Peer) {
6✔
3868
                        defer s.wg.Done()
3✔
3869
                        defer wg.Done()
3✔
3870

3✔
3871
                        p.SendMessageLazy(false, msgs...)
3✔
3872
                }(sPeer)
3✔
3873
        }
3874

3875
        // Wait for all messages to have been dispatched before returning to
3876
        // caller.
3877
        wg.Wait()
3✔
3878

3✔
3879
        return nil
3✔
3880
}
3881

3882
// NotifyWhenOnline can be called by other subsystems to get notified when a
3883
// particular peer comes online. The peer itself is sent across the peerChan.
3884
//
3885
// NOTE: This function is safe for concurrent access.
3886
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3887
        peerChan chan<- lnpeer.Peer) {
3✔
3888

3✔
3889
        s.mu.Lock()
3✔
3890

3✔
3891
        // Compute the target peer's identifier.
3✔
3892
        pubStr := string(peerKey[:])
3✔
3893

3✔
3894
        // Check if peer is connected.
3✔
3895
        peer, ok := s.peersByPub[pubStr]
3✔
3896
        if ok {
6✔
3897
                // Unlock here so that the mutex isn't held while we are
3✔
3898
                // waiting for the peer to become active.
3✔
3899
                s.mu.Unlock()
3✔
3900

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

3916
                // Connected, can return early.
3917
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3918

3✔
3919
                select {
3✔
3920
                case peerChan <- peer:
3✔
3921
                case <-s.quit:
×
3922
                }
3923

3924
                return
3✔
3925
        }
3926

3927
        // Not connected, store this listener such that it can be notified when
3928
        // the peer comes online.
3929
        s.peerConnectedListeners[pubStr] = append(
3✔
3930
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3931
        )
3✔
3932
        s.mu.Unlock()
3✔
3933
}
3934

3935
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3936
// the given public key has been disconnected. The notification is signaled by
3937
// closing the channel returned.
3938
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3939
        s.mu.Lock()
3✔
3940
        defer s.mu.Unlock()
3✔
3941

3✔
3942
        c := make(chan struct{})
3✔
3943

3✔
3944
        // If the peer is already offline, we can immediately trigger the
3✔
3945
        // notification.
3✔
3946
        peerPubKeyStr := string(peerPubKey[:])
3✔
3947
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3948
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3949
                close(c)
×
3950
                return c
×
3951
        }
×
3952

3953
        // Otherwise, the peer is online, so we'll keep track of the channel to
3954
        // trigger the notification once the server detects the peer
3955
        // disconnects.
3956
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3957
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3958
        )
3✔
3959

3✔
3960
        return c
3✔
3961
}
3962

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

3✔
3972
        pubStr := string(peerKey.SerializeCompressed())
3✔
3973

3✔
3974
        return s.findPeerByPubStr(pubStr)
3✔
3975
}
3✔
3976

3977
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3978
// which should be a string representation of the peer's serialized, compressed
3979
// public key.
3980
//
3981
// NOTE: This function is safe for concurrent access.
3982
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3983
        s.mu.RLock()
3✔
3984
        defer s.mu.RUnlock()
3✔
3985

3✔
3986
        return s.findPeerByPubStr(pubStr)
3✔
3987
}
3✔
3988

3989
// findPeerByPubStr is an internal method that retrieves the specified peer from
3990
// the server's internal state using.
3991
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3992
        peer, ok := s.peersByPub[pubStr]
3✔
3993
        if !ok {
6✔
3994
                return nil, ErrPeerNotConnected
3✔
3995
        }
3✔
3996

3997
        return peer, nil
3✔
3998
}
3999

4000
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
4001
// exponential backoff. If no previous backoff was known, the default is
4002
// returned.
4003
func (s *server) nextPeerBackoff(pubStr string,
4004
        startTime time.Time) time.Duration {
3✔
4005

3✔
4006
        // Now, determine the appropriate backoff to use for the retry.
3✔
4007
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
4008
        if !ok {
6✔
4009
                // If an existing backoff was unknown, use the default.
3✔
4010
                return s.cfg.MinBackoff
3✔
4011
        }
3✔
4012

4013
        // If the peer failed to start properly, we'll just use the previous
4014
        // backoff to compute the subsequent randomized exponential backoff
4015
        // duration. This will roughly double on average.
4016
        if startTime.IsZero() {
3✔
4017
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4018
        }
×
4019

4020
        // The peer succeeded in starting. If the connection didn't last long
4021
        // enough to be considered stable, we'll continue to back off retries
4022
        // with this peer.
4023
        connDuration := time.Since(startTime)
3✔
4024
        if connDuration < defaultStableConnDuration {
6✔
4025
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4026
        }
3✔
4027

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

4038
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4039
        // the stable connection lasted much longer than our previous backoff.
4040
        // To reward such good behavior, we'll reconnect after the default
4041
        // timeout.
4042
        return s.cfg.MinBackoff
×
4043
}
4044

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

×
4055
        // The connection that comes from the node with a "smaller" pubkey
×
4056
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4057
        // should drop our established connection.
×
4058
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4059
}
×
4060

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

4072
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4073
        pubSer := nodePub.SerializeCompressed()
3✔
4074
        pubStr := string(pubSer)
3✔
4075

3✔
4076
        var pubBytes [33]byte
3✔
4077
        copy(pubBytes[:], pubSer)
3✔
4078

3✔
4079
        s.mu.Lock()
3✔
4080
        defer s.mu.Unlock()
3✔
4081

3✔
4082
        // If we already have an outbound connection to this peer, then ignore
3✔
4083
        // this new connection.
3✔
4084
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4085
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4086
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4087
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4088

3✔
4089
                conn.Close()
3✔
4090
                return
3✔
4091
        }
3✔
4092

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

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

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

4118
        case nil:
3✔
4119
                ctx := btclog.WithCtx(
3✔
4120
                        context.TODO(),
3✔
4121
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4122
                )
3✔
4123

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

×
4133
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4134
                                "peer, but already have outbound "+
×
4135
                                "connection, dropping conn",
×
4136
                                fmt.Errorf("already have outbound conn"))
×
4137
                        conn.Close()
×
4138
                        return
×
4139
                }
×
4140

4141
                // Otherwise, if we should drop the connection, then we'll
4142
                // disconnect our already connected peer.
4143
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4144

3✔
4145
                s.cancelConnReqs(pubStr, nil)
3✔
4146

3✔
4147
                // Remove the current peer from the server's internal state and
3✔
4148
                // signal that the peer termination watcher does not need to
3✔
4149
                // execute for this peer.
3✔
4150
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4151
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4152
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4153
                        s.peerConnected(conn, nil, true)
3✔
4154
                }
3✔
4155
        }
4156
}
4157

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

4168
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4169
        pubSer := nodePub.SerializeCompressed()
3✔
4170
        pubStr := string(pubSer)
3✔
4171

3✔
4172
        var pubBytes [33]byte
3✔
4173
        copy(pubBytes[:], pubSer)
3✔
4174

3✔
4175
        s.mu.Lock()
3✔
4176
        defer s.mu.Unlock()
3✔
4177

3✔
4178
        // If we already have an inbound connection to this peer, then ignore
3✔
4179
        // this new connection.
3✔
4180
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4181
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4182
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4183
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4184

3✔
4185
                if connReq != nil {
6✔
4186
                        s.connMgr.Remove(connReq.ID())
3✔
4187
                }
3✔
4188
                conn.Close()
3✔
4189
                return
3✔
4190
        }
4191
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4192
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4193
                s.connMgr.Remove(connReq.ID())
×
4194
                conn.Close()
×
4195
                return
×
4196
        }
×
4197

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

×
4204
                if connReq != nil {
×
4205
                        s.connMgr.Remove(connReq.ID())
×
4206
                }
×
4207

4208
                conn.Close()
×
4209
                return
×
4210
        }
4211

4212
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4213
                conn.RemoteAddr())
3✔
4214

3✔
4215
        if connReq != nil {
6✔
4216
                // A successful connection was returned by the connmgr.
3✔
4217
                // Immediately cancel all pending requests, excluding the
3✔
4218
                // outbound connection we just established.
3✔
4219
                ignore := connReq.ID()
3✔
4220
                s.cancelConnReqs(pubStr, &ignore)
3✔
4221
        } else {
6✔
4222
                // This was a successful connection made by some other
3✔
4223
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4224
                s.cancelConnReqs(pubStr, nil)
3✔
4225
        }
3✔
4226

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

4238
        case nil:
3✔
4239
                ctx := btclog.WithCtx(
3✔
4240
                        context.TODO(),
3✔
4241
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
3✔
4242
                )
3✔
4243

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

×
4253
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4254
                                "to peer, but already have inbound "+
×
4255
                                "connection, dropping conn",
×
4256
                                fmt.Errorf("already have inbound conn"))
×
4257
                        if connReq != nil {
×
4258
                                s.connMgr.Remove(connReq.ID())
×
4259
                        }
×
4260
                        conn.Close()
×
4261
                        return
×
4262
                }
4263

4264
                // Otherwise, _their_ connection should be dropped. So we'll
4265
                // disconnect the peer and send the now obsolete peer to the
4266
                // server for garbage collection.
4267
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
3✔
4268

3✔
4269
                // Remove the current peer from the server's internal state and
3✔
4270
                // signal that the peer termination watcher does not need to
3✔
4271
                // execute for this peer.
3✔
4272
                s.removePeerUnsafe(ctx, connectedPeer)
3✔
4273
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4274
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4275
                        s.peerConnected(conn, connReq, false)
3✔
4276
                }
3✔
4277
        }
4278
}
4279

4280
// UnassignedConnID is the default connection ID that a request can have before
4281
// it actually is submitted to the connmgr.
4282
// TODO(conner): move into connmgr package, or better, add connmgr method for
4283
// generating atomic IDs
4284
const UnassignedConnID uint64 = 0
4285

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

4300
        // Next, check to see if we have any outstanding persistent connection
4301
        // requests to this peer. If so, then we'll remove all of these
4302
        // connection requests, and also delete the entry from the map.
4303
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4304
        if !ok {
6✔
4305
                return
3✔
4306
        }
3✔
4307

4308
        for _, connReq := range connReqs {
6✔
4309
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4310

3✔
4311
                // Atomically capture the current request identifier.
3✔
4312
                connID := connReq.ID()
3✔
4313

3✔
4314
                // Skip any zero IDs, this indicates the request has not
3✔
4315
                // yet been schedule.
3✔
4316
                if connID == UnassignedConnID {
4✔
4317
                        continue
1✔
4318
                }
4319

4320
                // Skip a particular connection ID if instructed.
4321
                if skip != nil && connID == *skip {
6✔
4322
                        continue
3✔
4323
                }
4324

4325
                s.connMgr.Remove(connID)
3✔
4326
        }
4327

4328
        delete(s.persistentConnReqs, pubStr)
3✔
4329
}
4330

4331
// handleCustomMessage dispatches an incoming custom peers message to
4332
// subscribers.
4333
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4334
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4335
                peer, msg.Type)
3✔
4336

3✔
4337
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4338
                Peer: peer,
3✔
4339
                Msg:  msg,
3✔
4340
        })
3✔
4341
}
3✔
4342

4343
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4344
// messages.
4345
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4346
        return s.customMessageServer.Subscribe()
3✔
4347
}
3✔
4348

4349
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4350
// the channelNotifier's NotifyOpenChannelEvent.
4351
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4352
        remotePub *btcec.PublicKey) {
3✔
4353

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

4360
        // Notify subscribers about this open channel event.
4361
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4362
}
4363

4364
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4365
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4366
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4367
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4368

3✔
4369
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4370
        // peer.
3✔
4371
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4372
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4373
                        "channel[%v] pending open",
×
4374
                        remotePub.SerializeCompressed(), op)
×
4375
        }
×
4376

4377
        // Notify subscribers about this event.
4378
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4379
}
4380

4381
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4382
// calls the channelNotifier's NotifyFundingTimeout.
4383
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4384
        remotePub *btcec.PublicKey) {
3✔
4385

3✔
4386
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4387
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4388
        if err != nil {
3✔
4389
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4390
                        "channel[%v] pending close",
×
4391
                        remotePub.SerializeCompressed(), op)
×
4392
        }
×
4393

4394
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4395
                // If we encounter an error while attempting to disconnect the
×
4396
                // peer, log the error.
×
4397
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4398
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4399
                }
×
4400
        }
4401

4402
        // Notify subscribers about this event.
4403
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4404
}
4405

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

3✔
4413
        brontideConn := conn.(*brontide.Conn)
3✔
4414
        addr := conn.RemoteAddr()
3✔
4415
        pubKey := brontideConn.RemotePub()
3✔
4416

3✔
4417
        // Only restrict access for inbound connections, which means if the
3✔
4418
        // remote node's public key is banned or the restricted slots are used
3✔
4419
        // up, we will drop the connection.
3✔
4420
        //
3✔
4421
        // TODO(yy): Consider perform this check in
3✔
4422
        // `peerAccessMan.addPeerAccess`.
3✔
4423
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4424
        if inbound && err != nil {
3✔
4425
                pubSer := pubKey.SerializeCompressed()
×
4426

×
4427
                // Clean up the persistent peer maps if we're dropping this
×
4428
                // connection.
×
4429
                s.bannedPersistentPeerConnection(string(pubSer))
×
4430

×
4431
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4432
                        "of restricted-access connection slots: %v.", pubSer,
×
4433
                        err)
×
4434

×
4435
                conn.Close()
×
4436

×
4437
                return
×
4438
        }
×
4439

4440
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4441
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4442

3✔
4443
        peerAddr := &lnwire.NetAddress{
3✔
4444
                IdentityKey: pubKey,
3✔
4445
                Address:     addr,
3✔
4446
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4447
        }
3✔
4448

3✔
4449
        // With the brontide connection established, we'll now craft the feature
3✔
4450
        // vectors to advertise to the remote node.
3✔
4451
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4452
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4453

3✔
4454
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4455
        // found, create a fresh buffer.
3✔
4456
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4457
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4458
        if !ok {
6✔
4459
                var err error
3✔
4460
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4461
                if err != nil {
3✔
4462
                        srvrLog.Errorf("unable to create peer %v", err)
×
4463
                        return
×
4464
                }
×
4465
        }
4466

4467
        // If we directly set the peer.Config TowerClient member to the
4468
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4469
        // the peer.Config's TowerClient member will not evaluate to nil even
4470
        // though the underlying value is nil. To avoid this gotcha which can
4471
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4472
        // TowerClient if needed.
4473
        var towerClient wtclient.ClientManager
3✔
4474
        if s.towerClientMgr != nil {
6✔
4475
                towerClient = s.towerClientMgr
3✔
4476
        }
3✔
4477

4478
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4479
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4480

3✔
4481
        // Now that we've established a connection, create a peer, and it to the
3✔
4482
        // set of currently active peers. Configure the peer with the incoming
3✔
4483
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4484
        // offered that would trigger channel closure. In case of outgoing
3✔
4485
        // htlcs, an extra block is added to prevent the channel from being
3✔
4486
        // closed when the htlc is outstanding and a new block comes in.
3✔
4487
        pCfg := peer.Config{
3✔
4488
                Conn:                    brontideConn,
3✔
4489
                ConnReq:                 connReq,
3✔
4490
                Addr:                    peerAddr,
3✔
4491
                Inbound:                 inbound,
3✔
4492
                Features:                initFeatures,
3✔
4493
                LegacyFeatures:          legacyFeatures,
3✔
4494
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4495
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4496
                ErrorBuffer:             errBuffer,
3✔
4497
                WritePool:               s.writePool,
3✔
4498
                ReadPool:                s.readPool,
3✔
4499
                Switch:                  s.htlcSwitch,
3✔
4500
                InterceptSwitch:         s.interceptableSwitch,
3✔
4501
                ChannelDB:               s.chanStateDB,
3✔
4502
                ChannelGraph:            s.graphDB,
3✔
4503
                ChainArb:                s.chainArb,
3✔
4504
                AuthGossiper:            s.authGossiper,
3✔
4505
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4506
                ChainIO:                 s.cc.ChainIO,
3✔
4507
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4508
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4509
                SigPool:                 s.sigPool,
3✔
4510
                Wallet:                  s.cc.Wallet,
3✔
4511
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4512
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4513
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4514
                Sphinx:                  s.sphinx,
3✔
4515
                WitnessBeacon:           s.witnessBeacon,
3✔
4516
                Invoices:                s.invoices,
3✔
4517
                ChannelNotifier:         s.channelNotifier,
3✔
4518
                HtlcNotifier:            s.htlcNotifier,
3✔
4519
                TowerClient:             towerClient,
3✔
4520
                DisconnectPeer:          s.DisconnectPeer,
3✔
4521
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4522
                        lnwire.NodeAnnouncement, error) {
6✔
4523

3✔
4524
                        return s.genNodeAnnouncement(nil)
3✔
4525
                },
3✔
4526

4527
                PongBuf: s.pongBuf,
4528

4529
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4530

4531
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4532

4533
                FundingManager: s.fundingMgr,
4534

4535
                Hodl:                    s.cfg.Hodl,
4536
                UnsafeReplay:            s.cfg.UnsafeReplay,
4537
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4538
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4539
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4540
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4541
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4542
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4543
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4544
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4545
                HandleCustomMessage:    s.handleCustomMessage,
4546
                GetAliases:             s.aliasMgr.GetAliases,
4547
                RequestAlias:           s.aliasMgr.RequestAlias,
4548
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4549
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4550
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4551
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4552
                MaxFeeExposure:         thresholdMSats,
4553
                Quit:                   s.quit,
4554
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4555
                AuxSigner:              s.implCfg.AuxSigner,
4556
                MsgRouter:              s.implCfg.MsgRouter,
4557
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4558
                AuxResolver:            s.implCfg.AuxContractResolver,
4559
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4560
                ShouldFwdExpEndorsement: func() bool {
3✔
4561
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4562
                                return false
3✔
4563
                        }
3✔
4564

4565
                        return clock.NewDefaultClock().Now().Before(
3✔
4566
                                EndorsementExperimentEnd,
3✔
4567
                        )
3✔
4568
                },
4569
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4570
        }
4571

4572
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4573
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4574

3✔
4575
        p := peer.NewBrontide(pCfg)
3✔
4576

3✔
4577
        // Update the access manager with the access permission for this peer.
3✔
4578
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4579

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

3✔
4583
        s.addPeer(p)
3✔
4584

3✔
4585
        // Once we have successfully added the peer to the server, we can
3✔
4586
        // delete the previous error buffer from the server's map of error
3✔
4587
        // buffers.
3✔
4588
        delete(s.peerErrors, pkStr)
3✔
4589

3✔
4590
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4591
        // includes sending and receiving Init messages, which would be a DOS
3✔
4592
        // vector if we held the server's mutex throughout the procedure.
3✔
4593
        s.wg.Add(1)
3✔
4594
        go s.peerInitializer(p)
3✔
4595
}
4596

4597
// addPeer adds the passed peer to the server's global state of all active
4598
// peers.
4599
func (s *server) addPeer(p *peer.Brontide) {
3✔
4600
        if p == nil {
3✔
4601
                return
×
4602
        }
×
4603

4604
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4605

3✔
4606
        // Ignore new peers if we're shutting down.
3✔
4607
        if s.Stopped() {
3✔
4608
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4609
                        pubBytes)
×
4610
                p.Disconnect(ErrServerShuttingDown)
×
4611

×
4612
                return
×
4613
        }
×
4614

4615
        // Track the new peer in our indexes so we can quickly look it up either
4616
        // according to its public key, or its peer ID.
4617
        // TODO(roasbeef): pipe all requests through to the
4618
        // queryHandler/peerManager
4619

4620
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4621
        // be human-readable.
4622
        pubStr := string(pubBytes)
3✔
4623

3✔
4624
        s.peersByPub[pubStr] = p
3✔
4625

3✔
4626
        if p.Inbound() {
6✔
4627
                s.inboundPeers[pubStr] = p
3✔
4628
        } else {
6✔
4629
                s.outboundPeers[pubStr] = p
3✔
4630
        }
3✔
4631

4632
        // Inform the peer notifier of a peer online event so that it can be reported
4633
        // to clients listening for peer events.
4634
        var pubKey [33]byte
3✔
4635
        copy(pubKey[:], pubBytes)
3✔
4636
}
4637

4638
// peerInitializer asynchronously starts a newly connected peer after it has
4639
// been added to the server's peer map. This method sets up a
4640
// peerTerminationWatcher for the given peer, and ensures that it executes even
4641
// if the peer failed to start. In the event of a successful connection, this
4642
// method reads the negotiated, local feature-bits and spawns the appropriate
4643
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4644
// be signaled of the new peer once the method returns.
4645
//
4646
// NOTE: This MUST be launched as a goroutine.
4647
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4648
        defer s.wg.Done()
3✔
4649

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

3✔
4652
        // Avoid initializing peers while the server is exiting.
3✔
4653
        if s.Stopped() {
3✔
4654
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4655
                        pubBytes)
×
4656
                return
×
4657
        }
×
4658

4659
        // Create a channel that will be used to signal a successful start of
4660
        // the link. This prevents the peer termination watcher from beginning
4661
        // its duty too early.
4662
        ready := make(chan struct{})
3✔
4663

3✔
4664
        // Before starting the peer, launch a goroutine to watch for the
3✔
4665
        // unexpected termination of this peer, which will ensure all resources
3✔
4666
        // are properly cleaned up, and re-establish persistent connections when
3✔
4667
        // necessary. The peer termination watcher will be short circuited if
3✔
4668
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4669
        // that the server has already handled the removal of this peer.
3✔
4670
        s.wg.Add(1)
3✔
4671
        go s.peerTerminationWatcher(p, ready)
3✔
4672

3✔
4673
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4674
        // will unblock the peerTerminationWatcher.
3✔
4675
        if err := p.Start(); err != nil {
6✔
4676
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4677

3✔
4678
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4679
                return
3✔
4680
        }
3✔
4681

4682
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4683
        // was successful, and to begin watching the peer's wait group.
4684
        close(ready)
3✔
4685

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

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

3✔
4692
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4693
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4694
        pubStr := string(pubBytes)
3✔
4695
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4696
                select {
3✔
4697
                case peerChan <- p:
3✔
4698
                case <-s.quit:
×
4699
                        return
×
4700
                }
4701
        }
4702
        delete(s.peerConnectedListeners, pubStr)
3✔
4703

3✔
4704
        // Since the peer has been fully initialized, now it's time to notify
3✔
4705
        // the RPC about the peer online event.
3✔
4706
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
3✔
4707
}
4708

4709
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4710
// and then cleans up all resources allocated to the peer, notifies relevant
4711
// sub-systems of its demise, and finally handles re-connecting to the peer if
4712
// it's persistent. If the server intentionally disconnects a peer, it should
4713
// have a corresponding entry in the ignorePeerTermination map which will cause
4714
// the cleanup routine to exit early. The passed `ready` chan is used to
4715
// synchronize when WaitForDisconnect should begin watching on the peer's
4716
// waitgroup. The ready chan should only be signaled if the peer starts
4717
// successfully, otherwise the peer should be disconnected instead.
4718
//
4719
// NOTE: This MUST be launched as a goroutine.
4720
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4721
        defer s.wg.Done()
3✔
4722

3✔
4723
        ctx := btclog.WithCtx(
3✔
4724
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
3✔
4725
        )
3✔
4726

3✔
4727
        p.WaitForDisconnect(ready)
3✔
4728

3✔
4729
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4730

3✔
4731
        // If the server is exiting then we can bail out early ourselves as all
3✔
4732
        // the other sub-systems will already be shutting down.
3✔
4733
        if s.Stopped() {
6✔
4734
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
3✔
4735
                return
3✔
4736
        }
3✔
4737

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

3✔
4744
        pubKey := p.IdentityKey()
3✔
4745

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

3✔
4750
        // Tell the switch to remove all links associated with this peer.
3✔
4751
        // Passing nil as the target link indicates that all links associated
3✔
4752
        // with this interface should be closed.
3✔
4753
        //
3✔
4754
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4755
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4756
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4757
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4758
        }
×
4759

4760
        for _, link := range links {
6✔
4761
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4762
        }
3✔
4763

4764
        s.mu.Lock()
3✔
4765
        defer s.mu.Unlock()
3✔
4766

3✔
4767
        // If there were any notification requests for when this peer
3✔
4768
        // disconnected, we can trigger them now.
3✔
4769
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
3✔
4770
        pubStr := string(pubKey.SerializeCompressed())
3✔
4771
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4772
                close(offlineChan)
3✔
4773
        }
3✔
4774
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4775

3✔
4776
        // If the server has already removed this peer, we can short circuit the
3✔
4777
        // peer termination watcher and skip cleanup.
3✔
4778
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4779
                delete(s.ignorePeerTermination, p)
3✔
4780

3✔
4781
                pubKey := p.PubKey()
3✔
4782
                pubStr := string(pubKey[:])
3✔
4783

3✔
4784
                // If a connection callback is present, we'll go ahead and
3✔
4785
                // execute it now that previous peer has fully disconnected. If
3✔
4786
                // the callback is not present, this likely implies the peer was
3✔
4787
                // purposefully disconnected via RPC, and that no reconnect
3✔
4788
                // should be attempted.
3✔
4789
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4790
                if ok {
6✔
4791
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4792
                        connCallback()
3✔
4793
                }
3✔
4794
                return
3✔
4795
        }
4796

4797
        // First, cleanup any remaining state the server has regarding the peer
4798
        // in question.
4799
        s.removePeerUnsafe(ctx, p)
3✔
4800

3✔
4801
        // Next, check to see if this is a persistent peer or not.
3✔
4802
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4803
                return
3✔
4804
        }
3✔
4805

4806
        // Get the last address that we used to connect to the peer.
4807
        addrs := []net.Addr{
3✔
4808
                p.NetAddress().Address,
3✔
4809
        }
3✔
4810

3✔
4811
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4812
        // reconnection purposes.
3✔
4813
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4814
        switch {
3✔
4815
        // We found advertised addresses, so use them.
4816
        case err == nil:
3✔
4817
                addrs = advertisedAddrs
3✔
4818

4819
        // The peer doesn't have an advertised address.
4820
        case err == errNoAdvertisedAddr:
3✔
4821
                // If it is an outbound peer then we fall back to the existing
3✔
4822
                // peer address.
3✔
4823
                if !p.Inbound() {
6✔
4824
                        break
3✔
4825
                }
4826

4827
                // Fall back to the existing peer address if
4828
                // we're not accepting connections over Tor.
4829
                if s.torController == nil {
6✔
4830
                        break
3✔
4831
                }
4832

4833
                // If we are, the peer's address won't be known
4834
                // to us (we'll see a private address, which is
4835
                // the address used by our onion service to dial
4836
                // to lnd), so we don't have enough information
4837
                // to attempt a reconnect.
4838
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4839
                        "to inbound peer without advertised address")
×
4840
                return
×
4841

4842
        // We came across an error retrieving an advertised
4843
        // address, log it, and fall back to the existing peer
4844
        // address.
4845
        default:
3✔
4846
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
3✔
4847
                        "address for peer", err)
3✔
4848
        }
4849

4850
        // Make an easy lookup map so that we can check if an address
4851
        // is already in the address list that we have stored for this peer.
4852
        existingAddrs := make(map[string]bool)
3✔
4853
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4854
                existingAddrs[addr.String()] = true
3✔
4855
        }
3✔
4856

4857
        // Add any missing addresses for this peer to persistentPeerAddr.
4858
        for _, addr := range addrs {
6✔
4859
                if existingAddrs[addr.String()] {
3✔
4860
                        continue
×
4861
                }
4862

4863
                s.persistentPeerAddrs[pubStr] = append(
3✔
4864
                        s.persistentPeerAddrs[pubStr],
3✔
4865
                        &lnwire.NetAddress{
3✔
4866
                                IdentityKey: p.IdentityKey(),
3✔
4867
                                Address:     addr,
3✔
4868
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4869
                        },
3✔
4870
                )
3✔
4871
        }
4872

4873
        // Record the computed backoff in the backoff map.
4874
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4875
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4876

3✔
4877
        // Initialize a retry canceller for this peer if one does not
3✔
4878
        // exist.
3✔
4879
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4880
        if !ok {
6✔
4881
                cancelChan = make(chan struct{})
3✔
4882
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4883
        }
3✔
4884

4885
        // We choose not to wait group this go routine since the Connect
4886
        // call can stall for arbitrarily long if we shutdown while an
4887
        // outbound connection attempt is being made.
4888
        go func() {
6✔
4889
                srvrLog.DebugS(ctx, "Scheduling connection "+
3✔
4890
                        "re-establishment to persistent peer",
3✔
4891
                        "reconnecting_in", backoff)
3✔
4892

3✔
4893
                select {
3✔
4894
                case <-time.After(backoff):
3✔
4895
                case <-cancelChan:
3✔
4896
                        return
3✔
4897
                case <-s.quit:
3✔
4898
                        return
3✔
4899
                }
4900

4901
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
3✔
4902
                        "connection")
3✔
4903

3✔
4904
                s.connectToPersistentPeer(pubStr)
3✔
4905
        }()
4906
}
4907

4908
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4909
// to connect to the peer. It creates connection requests if there are
4910
// currently none for a given address and it removes old connection requests
4911
// if the associated address is no longer in the latest address list for the
4912
// peer.
4913
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4914
        s.mu.Lock()
3✔
4915
        defer s.mu.Unlock()
3✔
4916

3✔
4917
        // Create an easy lookup map of the addresses we have stored for the
3✔
4918
        // peer. We will remove entries from this map if we have existing
3✔
4919
        // connection requests for the associated address and then any leftover
3✔
4920
        // entries will indicate which addresses we should create new
3✔
4921
        // connection requests for.
3✔
4922
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4923
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4924
                addrMap[addr.String()] = addr
3✔
4925
        }
3✔
4926

4927
        // Go through each of the existing connection requests and
4928
        // check if they correspond to the latest set of addresses. If
4929
        // there is a connection requests that does not use one of the latest
4930
        // advertised addresses then remove that connection request.
4931
        var updatedConnReqs []*connmgr.ConnReq
3✔
4932
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4933
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4934

3✔
4935
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4936
                // If the existing connection request is using one of the
4937
                // latest advertised addresses for the peer then we add it to
4938
                // updatedConnReqs and remove the associated address from
4939
                // addrMap so that we don't recreate this connReq later on.
4940
                case true:
×
4941
                        updatedConnReqs = append(
×
4942
                                updatedConnReqs, connReq,
×
4943
                        )
×
4944
                        delete(addrMap, lnAddr)
×
4945

4946
                // If the existing connection request is using an address that
4947
                // is not one of the latest advertised addresses for the peer
4948
                // then we remove the connecting request from the connection
4949
                // manager.
4950
                case false:
3✔
4951
                        srvrLog.Info(
3✔
4952
                                "Removing conn req:", connReq.Addr.String(),
3✔
4953
                        )
3✔
4954
                        s.connMgr.Remove(connReq.ID())
3✔
4955
                }
4956
        }
4957

4958
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4959

3✔
4960
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4961
        if !ok {
6✔
4962
                cancelChan = make(chan struct{})
3✔
4963
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4964
        }
3✔
4965

4966
        // Any addresses left in addrMap are new ones that we have not made
4967
        // connection requests for. So create new connection requests for those.
4968
        // If there is more than one address in the address map, stagger the
4969
        // creation of the connection requests for those.
4970
        go func() {
6✔
4971
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4972
                defer ticker.Stop()
3✔
4973

3✔
4974
                for _, addr := range addrMap {
6✔
4975
                        // Send the persistent connection request to the
3✔
4976
                        // connection manager, saving the request itself so we
3✔
4977
                        // can cancel/restart the process as needed.
3✔
4978
                        connReq := &connmgr.ConnReq{
3✔
4979
                                Addr:      addr,
3✔
4980
                                Permanent: true,
3✔
4981
                        }
3✔
4982

3✔
4983
                        s.mu.Lock()
3✔
4984
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4985
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4986
                        )
3✔
4987
                        s.mu.Unlock()
3✔
4988

3✔
4989
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4990
                                "channel peer %v", addr)
3✔
4991

3✔
4992
                        go s.connMgr.Connect(connReq)
3✔
4993

3✔
4994
                        select {
3✔
4995
                        case <-s.quit:
3✔
4996
                                return
3✔
4997
                        case <-cancelChan:
3✔
4998
                                return
3✔
4999
                        case <-ticker.C:
3✔
5000
                        }
5001
                }
5002
        }()
5003
}
5004

5005
// removePeerUnsafe removes the passed peer from the server's state of all
5006
// active peers.
5007
//
5008
// NOTE: Server mutex must be held when calling this function.
5009
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
3✔
5010
        if p == nil {
3✔
5011
                return
×
5012
        }
×
5013

5014
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5015

3✔
5016
        // Exit early if we have already been instructed to shutdown, the peers
3✔
5017
        // will be disconnected in the server shutdown process.
3✔
5018
        if s.Stopped() {
3✔
5019
                return
×
5020
        }
×
5021

5022
        // Capture the peer's public key and string representation.
5023
        pKey := p.PubKey()
3✔
5024
        pubSer := pKey[:]
3✔
5025
        pubStr := string(pubSer)
3✔
5026

3✔
5027
        delete(s.peersByPub, pubStr)
3✔
5028

3✔
5029
        if p.Inbound() {
6✔
5030
                delete(s.inboundPeers, pubStr)
3✔
5031
        } else {
6✔
5032
                delete(s.outboundPeers, pubStr)
3✔
5033
        }
3✔
5034

5035
        // When removing the peer we make sure to disconnect it asynchronously
5036
        // to avoid blocking the main server goroutine because it is holding the
5037
        // server's mutex. Disconnecting the peer might block and wait until the
5038
        // peer has fully started up. This can happen if an inbound and outbound
5039
        // race condition occurs.
5040
        s.wg.Add(1)
3✔
5041
        go func() {
6✔
5042
                defer s.wg.Done()
3✔
5043

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

3✔
5046
                // If this peer had an active persistent connection request,
3✔
5047
                // remove it.
3✔
5048
                if p.ConnReq() != nil {
6✔
5049
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5050
                }
3✔
5051

5052
                // Remove the peer's access permission from the access manager.
5053
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5054
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
3✔
5055

3✔
5056
                // Copy the peer's error buffer across to the server if it has
3✔
5057
                // any items in it so that we can restore peer errors across
3✔
5058
                // connections. We need to look up the error after the peer has
3✔
5059
                // been disconnected because we write the error in the
3✔
5060
                // `Disconnect` method.
3✔
5061
                s.mu.Lock()
3✔
5062
                if p.ErrorBuffer().Total() > 0 {
6✔
5063
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5064
                }
3✔
5065
                s.mu.Unlock()
3✔
5066

3✔
5067
                // Inform the peer notifier of a peer offline event so that it
3✔
5068
                // can be reported to clients listening for peer events.
3✔
5069
                var pubKey [33]byte
3✔
5070
                copy(pubKey[:], pubSer)
3✔
5071

3✔
5072
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5073
        }()
5074
}
5075

5076
// ConnectToPeer requests that the server connect to a Lightning Network peer
5077
// at the specified address. This function will *block* until either a
5078
// connection is established, or the initial handshake process fails.
5079
//
5080
// NOTE: This function is safe for concurrent access.
5081
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5082
        perm bool, timeout time.Duration) error {
3✔
5083

3✔
5084
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5085

3✔
5086
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5087
        // better granularity.  In certain conditions, this method requires
3✔
5088
        // making an outbound connection to a remote peer, which requires the
3✔
5089
        // lock to be released, and subsequently reacquired.
3✔
5090
        s.mu.Lock()
3✔
5091

3✔
5092
        // Ensure we're not already connected to this peer.
3✔
5093
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5094

3✔
5095
        // When there's no error it means we already have a connection with this
3✔
5096
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5097
        // set, we will ignore the existing connection and continue.
3✔
5098
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5099
                s.mu.Unlock()
3✔
5100
                return &errPeerAlreadyConnected{peer: peer}
3✔
5101
        }
3✔
5102

5103
        // Peer was not found, continue to pursue connection with peer.
5104

5105
        // If there's already a pending connection request for this pubkey,
5106
        // then we ignore this request to ensure we don't create a redundant
5107
        // connection.
5108
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5109
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5110
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5111
        }
3✔
5112

5113
        // If there's not already a pending or active connection to this node,
5114
        // then instruct the connection manager to attempt to establish a
5115
        // persistent connection to the peer.
5116
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5117
        if perm {
6✔
5118
                connReq := &connmgr.ConnReq{
3✔
5119
                        Addr:      addr,
3✔
5120
                        Permanent: true,
3✔
5121
                }
3✔
5122

3✔
5123
                // Since the user requested a permanent connection, we'll set
3✔
5124
                // the entry to true which will tell the server to continue
3✔
5125
                // reconnecting even if the number of channels with this peer is
3✔
5126
                // zero.
3✔
5127
                s.persistentPeers[targetPub] = true
3✔
5128
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5129
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5130
                }
3✔
5131
                s.persistentConnReqs[targetPub] = append(
3✔
5132
                        s.persistentConnReqs[targetPub], connReq,
3✔
5133
                )
3✔
5134
                s.mu.Unlock()
3✔
5135

3✔
5136
                go s.connMgr.Connect(connReq)
3✔
5137

3✔
5138
                return nil
3✔
5139
        }
5140
        s.mu.Unlock()
3✔
5141

3✔
5142
        // If we're not making a persistent connection, then we'll attempt to
3✔
5143
        // connect to the target peer. If the we can't make the connection, or
3✔
5144
        // the crypto negotiation breaks down, then return an error to the
3✔
5145
        // caller.
3✔
5146
        errChan := make(chan error, 1)
3✔
5147
        s.connectToPeer(addr, errChan, timeout)
3✔
5148

3✔
5149
        select {
3✔
5150
        case err := <-errChan:
3✔
5151
                return err
3✔
5152
        case <-s.quit:
×
5153
                return ErrServerShuttingDown
×
5154
        }
5155
}
5156

5157
// connectToPeer establishes a connection to a remote peer. errChan is used to
5158
// notify the caller if the connection attempt has failed. Otherwise, it will be
5159
// closed.
5160
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5161
        errChan chan<- error, timeout time.Duration) {
3✔
5162

3✔
5163
        conn, err := brontide.Dial(
3✔
5164
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5165
        )
3✔
5166
        if err != nil {
6✔
5167
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5168
                select {
3✔
5169
                case errChan <- err:
3✔
5170
                case <-s.quit:
×
5171
                }
5172
                return
3✔
5173
        }
5174

5175
        close(errChan)
3✔
5176

3✔
5177
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5178
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5179

3✔
5180
        s.OutboundPeerConnected(nil, conn)
3✔
5181
}
5182

5183
// DisconnectPeer sends the request to server to close the connection with peer
5184
// identified by public key.
5185
//
5186
// NOTE: This function is safe for concurrent access.
5187
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5188
        pubBytes := pubKey.SerializeCompressed()
3✔
5189
        pubStr := string(pubBytes)
3✔
5190

3✔
5191
        s.mu.Lock()
3✔
5192
        defer s.mu.Unlock()
3✔
5193

3✔
5194
        // Check that were actually connected to this peer. If not, then we'll
3✔
5195
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5196
        // currently connected to.
3✔
5197
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5198
        if err == ErrPeerNotConnected {
6✔
5199
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5200
        }
3✔
5201

5202
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5203

3✔
5204
        s.cancelConnReqs(pubStr, nil)
3✔
5205

3✔
5206
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5207
        // them from this map so we don't attempt to re-connect after we
3✔
5208
        // disconnect.
3✔
5209
        delete(s.persistentPeers, pubStr)
3✔
5210
        delete(s.persistentPeersBackoff, pubStr)
3✔
5211

3✔
5212
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5213
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5214
        //
3✔
5215
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5216
        // goroutine because we might hold the server's mutex.
3✔
5217
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5218

3✔
5219
        return nil
3✔
5220
}
5221

5222
// OpenChannel sends a request to the server to open a channel to the specified
5223
// peer identified by nodeKey with the passed channel funding parameters.
5224
//
5225
// NOTE: This function is safe for concurrent access.
5226
func (s *server) OpenChannel(
5227
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5228

3✔
5229
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5230
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5231
        // not blocked if the caller is not reading the updates.
3✔
5232
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5233
        req.Err = make(chan error, 1)
3✔
5234

3✔
5235
        // First attempt to locate the target peer to open a channel with, if
3✔
5236
        // we're unable to locate the peer then this request will fail.
3✔
5237
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5238
        s.mu.RLock()
3✔
5239
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5240
        if !ok {
3✔
5241
                s.mu.RUnlock()
×
5242

×
5243
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5244
                return req.Updates, req.Err
×
5245
        }
×
5246
        req.Peer = peer
3✔
5247
        s.mu.RUnlock()
3✔
5248

3✔
5249
        // We'll wait until the peer is active before beginning the channel
3✔
5250
        // opening process.
3✔
5251
        select {
3✔
5252
        case <-peer.ActiveSignal():
3✔
5253
        case <-peer.QuitSignal():
×
5254
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5255
                return req.Updates, req.Err
×
5256
        case <-s.quit:
×
5257
                req.Err <- ErrServerShuttingDown
×
5258
                return req.Updates, req.Err
×
5259
        }
5260

5261
        // If the fee rate wasn't specified at this point we fail the funding
5262
        // because of the missing fee rate information. The caller of the
5263
        // `OpenChannel` method needs to make sure that default values for the
5264
        // fee rate are set beforehand.
5265
        if req.FundingFeePerKw == 0 {
3✔
5266
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5267
                        "the channel opening transaction")
×
5268

×
5269
                return req.Updates, req.Err
×
5270
        }
×
5271

5272
        // Spawn a goroutine to send the funding workflow request to the funding
5273
        // manager. This allows the server to continue handling queries instead
5274
        // of blocking on this request which is exported as a synchronous
5275
        // request to the outside world.
5276
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5277

3✔
5278
        return req.Updates, req.Err
3✔
5279
}
5280

5281
// Peers returns a slice of all active peers.
5282
//
5283
// NOTE: This function is safe for concurrent access.
5284
func (s *server) Peers() []*peer.Brontide {
3✔
5285
        s.mu.RLock()
3✔
5286
        defer s.mu.RUnlock()
3✔
5287

3✔
5288
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5289
        for _, peer := range s.peersByPub {
6✔
5290
                peers = append(peers, peer)
3✔
5291
        }
3✔
5292

5293
        return peers
3✔
5294
}
5295

5296
// computeNextBackoff uses a truncated exponential backoff to compute the next
5297
// backoff using the value of the exiting backoff. The returned duration is
5298
// randomized in either direction by 1/20 to prevent tight loops from
5299
// stabilizing.
5300
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5301
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5302
        nextBackoff := 2 * currBackoff
3✔
5303
        if nextBackoff > maxBackoff {
6✔
5304
                nextBackoff = maxBackoff
3✔
5305
        }
3✔
5306

5307
        // Using 1/10 of our duration as a margin, compute a random offset to
5308
        // avoid the nodes entering connection cycles.
5309
        margin := nextBackoff / 10
3✔
5310

3✔
5311
        var wiggle big.Int
3✔
5312
        wiggle.SetUint64(uint64(margin))
3✔
5313
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5314
                // Randomizing is not mission critical, so we'll just return the
×
5315
                // current backoff.
×
5316
                return nextBackoff
×
5317
        }
×
5318

5319
        // Otherwise add in our wiggle, but subtract out half of the margin so
5320
        // that the backoff can tweaked by 1/20 in either direction.
5321
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5322
}
5323

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

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

3✔
5332
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5333
        if err != nil {
3✔
5334
                return nil, err
×
5335
        }
×
5336

5337
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5338
        if err != nil {
6✔
5339
                return nil, err
3✔
5340
        }
3✔
5341

5342
        if len(node.Addresses) == 0 {
6✔
5343
                return nil, errNoAdvertisedAddr
3✔
5344
        }
3✔
5345

5346
        return node.Addresses, nil
3✔
5347
}
5348

5349
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5350
// channel update for a target channel.
5351
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5352
        *lnwire.ChannelUpdate1, error) {
3✔
5353

3✔
5354
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5355
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5356
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5357
                if err != nil {
6✔
5358
                        return nil, err
3✔
5359
                }
3✔
5360

5361
                return netann.ExtractChannelUpdate(
3✔
5362
                        ourPubKey[:], info, edge1, edge2,
3✔
5363
                )
3✔
5364
        }
5365
}
5366

5367
// applyChannelUpdate applies the channel update to the different sub-systems of
5368
// the server. The useAlias boolean denotes whether or not to send an alias in
5369
// place of the real SCID.
5370
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5371
        op *wire.OutPoint, useAlias bool) error {
3✔
5372

3✔
5373
        var (
3✔
5374
                peerAlias    *lnwire.ShortChannelID
3✔
5375
                defaultAlias lnwire.ShortChannelID
3✔
5376
        )
3✔
5377

3✔
5378
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5379

3✔
5380
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5381
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5382
        if useAlias {
6✔
5383
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5384
                if foundAlias != defaultAlias {
6✔
5385
                        peerAlias = &foundAlias
3✔
5386
                }
3✔
5387
        }
5388

5389
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5390
                update, discovery.RemoteAlias(peerAlias),
3✔
5391
        )
3✔
5392
        select {
3✔
5393
        case err := <-errChan:
3✔
5394
                return err
3✔
5395
        case <-s.quit:
×
5396
                return ErrServerShuttingDown
×
5397
        }
5398
}
5399

5400
// SendCustomMessage sends a custom message to the peer with the specified
5401
// pubkey.
5402
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5403
        data []byte) error {
3✔
5404

3✔
5405
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5406
        if err != nil {
6✔
5407
                return err
3✔
5408
        }
3✔
5409

5410
        // We'll wait until the peer is active.
5411
        select {
3✔
5412
        case <-peer.ActiveSignal():
3✔
5413
        case <-peer.QuitSignal():
×
5414
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5415
        case <-s.quit:
×
5416
                return ErrServerShuttingDown
×
5417
        }
5418

5419
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5420
        if err != nil {
6✔
5421
                return err
3✔
5422
        }
3✔
5423

5424
        // Send the message as low-priority. For now we assume that all
5425
        // application-defined message are low priority.
5426
        return peer.SendMessageLazy(true, msg)
3✔
5427
}
5428

5429
// newSweepPkScriptGen creates closure that generates a new public key script
5430
// which should be used to sweep any funds into the on-chain wallet.
5431
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5432
// (p2wkh) output.
5433
func newSweepPkScriptGen(
5434
        wallet lnwallet.WalletController,
5435
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5436

3✔
5437
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5438
                sweepAddr, err := wallet.NewAddress(
3✔
5439
                        lnwallet.TaprootPubkey, false,
3✔
5440
                        lnwallet.DefaultAccountName,
3✔
5441
                )
3✔
5442
                if err != nil {
3✔
5443
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5444
                }
×
5445

5446
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5447
                if err != nil {
3✔
5448
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5449
                }
×
5450

5451
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5452
                        wallet, netParams, addr,
3✔
5453
                )
3✔
5454
                if err != nil {
3✔
5455
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5456
                }
×
5457

5458
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5459
                        DeliveryAddress: addr,
3✔
5460
                        InternalKey:     internalKeyDesc,
3✔
5461
                })
3✔
5462
        }
5463
}
5464

5465
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5466
// finished.
5467
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5468
        // Get a list of closed channels.
3✔
5469
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5470
        if err != nil {
3✔
5471
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5472
                return nil
×
5473
        }
×
5474

5475
        // Save the SCIDs in a map.
5476
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5477
        for _, c := range channels {
6✔
5478
                // If the channel is not pending, its FC has been finalized.
3✔
5479
                if !c.IsPending {
6✔
5480
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5481
                }
3✔
5482
        }
5483

5484
        // Double check whether the reported closed channel has indeed finished
5485
        // closing.
5486
        //
5487
        // NOTE: There are misalignments regarding when a channel's FC is
5488
        // marked as finalized. We double check the pending channels to make
5489
        // sure the returned SCIDs are indeed terminated.
5490
        //
5491
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5492
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5493
        if err != nil {
3✔
5494
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5495
                return nil
×
5496
        }
×
5497

5498
        for _, c := range pendings {
6✔
5499
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5500
                        continue
3✔
5501
                }
5502

5503
                // If the channel is still reported as pending, remove it from
5504
                // the map.
5505
                delete(closedSCIDs, c.ShortChannelID)
×
5506

×
5507
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5508
                        c.ShortChannelID)
×
5509
        }
5510

5511
        return closedSCIDs
3✔
5512
}
5513

5514
// getStartingBeat returns the current beat. This is used during the startup to
5515
// initialize blockbeat consumers.
5516
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5517
        // beat is the current blockbeat.
3✔
5518
        var beat *chainio.Beat
3✔
5519

3✔
5520
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5521
        // we will skip fetching the best block.
3✔
5522
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5523
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5524
                        "mode")
×
5525

×
5526
                return &chainio.Beat{}, nil
×
5527
        }
×
5528

5529
        // We should get a notification with the current best block immediately
5530
        // by passing a nil block.
5531
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5532
        if err != nil {
3✔
5533
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5534
        }
×
5535
        defer blockEpochs.Cancel()
3✔
5536

3✔
5537
        // We registered for the block epochs with a nil request. The notifier
3✔
5538
        // should send us the current best block immediately. So we need to
3✔
5539
        // wait for it here because we need to know the current best height.
3✔
5540
        select {
3✔
5541
        case bestBlock := <-blockEpochs.Epochs:
3✔
5542
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5543
                        bestBlock.Hash, bestBlock.Height)
3✔
5544

3✔
5545
                // Update the current blockbeat.
3✔
5546
                beat = chainio.NewBeat(*bestBlock)
3✔
5547

5548
        case <-s.quit:
×
5549
                srvrLog.Debug("LND shutting down")
×
5550
        }
5551

5552
        return beat, nil
3✔
5553
}
5554

5555
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5556
// point has an active RBF chan closer.
5557
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5558
        chanPoint wire.OutPoint) bool {
3✔
5559

3✔
5560
        pubBytes := peerPub.SerializeCompressed()
3✔
5561

3✔
5562
        s.mu.RLock()
3✔
5563
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5564
        s.mu.RUnlock()
3✔
5565
        if !ok {
3✔
5566
                return false
×
5567
        }
×
5568

5569
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5570
}
5571

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

3✔
5580
        // First, we'll attempt to look up the channel based on it's
3✔
5581
        // ChannelPoint.
3✔
5582
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5583
        if err != nil {
3✔
5584
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5585
        }
×
5586

5587
        // From the channel, we can now get the pubkey of the peer, then use
5588
        // that to eventually get the chan closer.
5589
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5590

3✔
5591
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5592
        s.mu.RLock()
3✔
5593
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5594
        s.mu.RUnlock()
3✔
5595
        if !ok {
3✔
5596
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5597
                        "not online", chanPoint)
×
5598
        }
×
5599

5600
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5601
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5602
        )
3✔
5603
        if err != nil {
3✔
5604
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5605
                        "%w", err)
×
5606
        }
×
5607

5608
        return closeUpdates, nil
3✔
5609
}
5610

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

3✔
5619
        // If the channel is present in the switch, then the request should flow
3✔
5620
        // through the switch instead.
3✔
5621
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5622
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5623
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5624
                        "invalid request", chanPoint)
×
5625
        }
×
5626

5627
        // At this point, we know that the channel isn't present in the link, so
5628
        // we'll check to see if we have an entry in the active chan closer map.
5629
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5630
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5631
        )
3✔
5632
        if err != nil {
3✔
5633
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5634
                        "ChannelPoint(%v)", chanPoint)
×
5635
        }
×
5636

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

© 2025 Coveralls, Inc