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

lightningnetwork / lnd / 16930624683

13 Aug 2025 07:31AM UTC coverage: 66.908% (+10.0%) from 56.955%
16930624683

Pull #10148

github

web-flow
Merge faa71c073 into 8810793e6
Pull Request #10148: graph/db+sqldb: different defaults for SQLite and Postgres query options

11 of 80 new or added lines in 7 files covered. (13.75%)

62 existing lines in 9 files now uncovered.

135807 of 202975 relevant lines covered (66.91%)

21557.94 hits per line

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

69.36
/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 " +
×
638
                        "overlay channels are not supported " +
×
639
                        "in a standalone lnd build")
×
640
        }
×
641

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

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

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

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

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

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

3✔
706
                listenAddrs: listenAddrs,
3✔
707

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

3✔
712
                torController: torController,
3✔
713

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

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

3✔
730
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
731

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

3✔
734
                tlsManager: tlsManager,
3✔
735

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

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

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

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

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

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

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

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

3✔
777
                return nil
3✔
778
        }
779

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1255
        s.peerAccessMan = peerAccessMan
3✔
1256

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

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

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

×
1284
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1285
                },
×
1286
        }
1287

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1574
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1575
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1576

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

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

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

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

1628
                        minConf := uint64(3)
×
1629
                        maxConf := uint64(6)
×
1630

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1815
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1816

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

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

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

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

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

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

1855
                        return br, channel.ChanType, nil
3✔
1856
                }
1857

1858
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1859

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1978
        return s, nil
3✔
1979
}
1980

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

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

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

1997
        case routing.BimodalConfig:
3✔
1998
                routerCfg.ProbabilityEstimatorType =
3✔
1999
                        routing.BimodalEstimatorName
3✔
2000

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

2007
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
2008
}
2009

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

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

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

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

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

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

×
2061
                chainBackendAttempts = 0
×
2062
        }
×
2063

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2215
                checks = append(checks, leaderCheck)
×
2216
        }
2217

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

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

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

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

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

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

3✔
2264
        cleanup := cleaner{}
3✔
2265

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

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

2275
        return startErr
3✔
2276
}
2277

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

2290
        var startErr error
3✔
2291

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2602
                        startErr = err
×
2603
                        return
×
2604
                }
×
2605

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

×
2615
                        startErr = err
×
2616
                        return
×
2617
                }
×
2618

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

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

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

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

2647
                                copy(result[idx][:], servers)
×
2648
                        }
2649

2650
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2651
                }
2652

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

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

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

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

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

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

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

3✔
2729
                ctx := context.Background()
3✔
2730

3✔
2731
                close(s.quit)
3✔
2732

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

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

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

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

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

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

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

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

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

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

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

2880
        return nil
3✔
2881
}
2882

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

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

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

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

2912
        return externalIPs, nil
×
2913
}
2914

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

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

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

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

2950
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2951

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

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

2982
                        if ip.Equal(s.lastDetectedIP) {
×
2983
                                continue
×
2984
                        }
2985

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

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

3003
                                newAddrs = append(newAddrs, addr)
×
3004
                        }
3005

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

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

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

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

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

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

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

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

3✔
3072
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3073

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

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

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

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

3106
        return bootStrappers, nil
3✔
3107
}
3108

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

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

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

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

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

3139
        return ignore
3✔
3140
}
3141

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

3✔
3150
        defer s.wg.Done()
3✔
3151

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

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

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

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

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

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

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

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

3200
                        if epochAttempts > 0 &&
×
3201
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3202

×
3203
                                sampleTicker.Stop()
×
3204

×
3205
                                backOff *= 2
×
3206
                                if backOff > bootstrapBackOffCeiling {
×
3207
                                        backOff = bootstrapBackOffCeiling
×
3208
                                }
×
3209

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

3216
                        atomic.StoreUint32(&epochErrors, 0)
×
3217
                        epochAttempts = 0
×
3218

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3313
                if numActivePeers >= numTargetPeers {
6✔
3314
                        return
3✔
3315
                }
3✔
3316

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

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

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

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

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

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

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

3388
                wg.Wait()
3✔
3389
        }
3390
}
3391

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

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

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

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

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

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

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

3463
        return nil
×
3464
}
3465

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

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

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

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

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

3✔
3491
        return *s.currentNodeAnn
3✔
3492
}
3✔
3493

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

3✔
3500
        s.mu.Lock()
3✔
3501
        defer s.mu.Unlock()
3✔
3502

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

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

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

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

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

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

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

3✔
3547
        return *s.currentNodeAnn, nil
3✔
3548
}
3549

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

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

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

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

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

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

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

3594
        return nil
3✔
3595
}
3596

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

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

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

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

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

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

3646
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3647

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

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

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

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

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

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

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

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

×
3715
                        return err
×
3716
                }
×
3717
        }
3718

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

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

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

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

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

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

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

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

3774
                numOutboundConns++
3✔
3775
        }
3776

3777
        return nil
3✔
3778
}
3779

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

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

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

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

3✔
3810
                return
3✔
3811
        }
3✔
3812
        s.mu.Unlock()
3✔
3813
}
3814

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

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

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

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

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

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

3✔
3873
                        p.SendMessageLazy(false, msgs...)
3✔
3874
                }(sPeer)
3✔
3875
        }
3876

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

3✔
3881
        return nil
3✔
3882
}
3883

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

3✔
3891
        s.mu.Lock()
3✔
3892

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

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

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

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

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

3926
                return
3✔
3927
        }
3928

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

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

3✔
3944
        c := make(chan struct{})
3✔
3945

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

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

3✔
3962
        return c
3✔
3963
}
3964

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

3✔
3974
        pubStr := string(peerKey.SerializeCompressed())
3✔
3975

3✔
3976
        return s.findPeerByPubStr(pubStr)
3✔
3977
}
3✔
3978

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

3✔
3988
        return s.findPeerByPubStr(pubStr)
3✔
3989
}
3✔
3990

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

3999
        return peer, nil
3✔
4000
}
4001

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

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

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

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

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

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

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

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

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

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

3✔
4078
        var pubBytes [33]byte
3✔
4079
        copy(pubBytes[:], pubSer)
3✔
4080

3✔
4081
        s.mu.Lock()
3✔
4082
        defer s.mu.Unlock()
3✔
4083

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

3✔
4091
                conn.Close()
3✔
4092
                return
3✔
4093
        }
3✔
4094

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

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

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

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

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

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

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

3✔
4147
                s.cancelConnReqs(pubStr, nil)
3✔
4148

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

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

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

3✔
4174
        var pubBytes [33]byte
3✔
4175
        copy(pubBytes[:], pubSer)
3✔
4176

3✔
4177
        s.mu.Lock()
3✔
4178
        defer s.mu.Unlock()
3✔
4179

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

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

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

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

4210
                conn.Close()
×
4211
                return
×
4212
        }
4213

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4327
                s.connMgr.Remove(connID)
3✔
4328
        }
4329

4330
        delete(s.persistentConnReqs, pubStr)
3✔
4331
}
4332

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
4437
                conn.Close()
×
4438

×
4439
                return
×
4440
        }
×
4441

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

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

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

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

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

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

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

3✔
4526
                        return s.genNodeAnnouncement(nil)
3✔
4527
                },
3✔
4528

4529
                PongBuf: s.pongBuf,
4530

4531
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4532

4533
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4534

4535
                FundingManager: s.fundingMgr,
4536

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

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

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

3✔
4577
        p := peer.NewBrontide(pCfg)
3✔
4578

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

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

3✔
4585
        s.addPeer(p)
3✔
4586

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

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

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

4606
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4607

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

×
4614
                return
×
4615
        }
×
4616

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

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

3✔
4626
        s.peersByPub[pubStr] = p
3✔
4627

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

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

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

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

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

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

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

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

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

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

3✔
4688
        s.mu.Lock()
3✔
4689
        defer s.mu.Unlock()
3✔
4690

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

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

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

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

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

3✔
4729
        p.WaitForDisconnect(ready)
3✔
4730

3✔
4731
        srvrLog.DebugS(ctx, "Peer has been disconnected")
3✔
4732

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

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

3✔
4746
        pubKey := p.IdentityKey()
3✔
4747

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

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

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

4766
        s.mu.Lock()
3✔
4767
        defer s.mu.Unlock()
3✔
4768

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

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

3✔
4783
                pubKey := p.PubKey()
3✔
4784
                pubStr := string(pubKey[:])
3✔
4785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
4906
                s.connectToPersistentPeer(pubStr)
3✔
4907
        }()
4908
}
4909

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

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

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

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

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

4960
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4961

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

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

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

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

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

3✔
4994
                        go s.connMgr.Connect(connReq)
3✔
4995

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

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

5016
        srvrLog.DebugS(ctx, "Removing peer")
3✔
5017

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

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

3✔
5029
        delete(s.peersByPub, pubStr)
3✔
5030

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

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

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

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

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

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

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

3✔
5074
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5075
        }()
5076
}
5077

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

3✔
5086
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5087

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

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

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

5105
        // Peer was not found, continue to pursue connection with peer.
5106

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

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

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

3✔
5138
                go s.connMgr.Connect(connReq)
3✔
5139

3✔
5140
                return nil
3✔
5141
        }
5142
        s.mu.Unlock()
3✔
5143

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

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

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

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

5177
        close(errChan)
3✔
5178

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

3✔
5182
        s.OutboundPeerConnected(nil, conn)
3✔
5183
}
5184

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

3✔
5193
        s.mu.Lock()
3✔
5194
        defer s.mu.Unlock()
3✔
5195

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

5204
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5205

3✔
5206
        s.cancelConnReqs(pubStr, nil)
3✔
5207

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

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

3✔
5221
        return nil
3✔
5222
}
5223

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

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

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

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

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

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

×
5271
                return req.Updates, req.Err
×
5272
        }
×
5273

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

3✔
5280
        return req.Updates, req.Err
3✔
5281
}
5282

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

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

5295
        return peers
3✔
5296
}
5297

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

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

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

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

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

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

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

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

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

5348
        return node.Addresses, nil
3✔
5349
}
5350

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

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

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

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

3✔
5375
        var (
3✔
5376
                peerAlias    *lnwire.ShortChannelID
3✔
5377
                defaultAlias lnwire.ShortChannelID
3✔
5378
        )
3✔
5379

3✔
5380
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5381

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5513
        return closedSCIDs
3✔
5514
}
5515

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

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

×
5528
                return &chainio.Beat{}, nil
×
5529
        }
×
5530

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

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

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

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

5554
        return beat, nil
3✔
5555
}
5556

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

3✔
5562
        pubBytes := peerPub.SerializeCompressed()
3✔
5563

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

5571
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5572
}
5573

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

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

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

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

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

5610
        return closeUpdates, nil
3✔
5611
}
5612

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

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

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

5639
        return updates, nil
3✔
5640
}
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