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

lightningnetwork / lnd / 15260961044

26 May 2025 07:40PM UTC coverage: 58.586% (+0.6%) from 57.977%
15260961044

Pull #9868

github

web-flow
Merge 68fbe502c into 93a6ab875
Pull Request #9868: PoC Onion messaging using `msgmux`

138 of 202 new or added lines in 7 files covered. (68.32%)

49 existing lines in 9 files now uncovered.

97608 of 166605 relevant lines covered (58.59%)

1.82 hits per line

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

64.21
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

196
// peerSlotStatus determines whether a peer gets access to one of our free
197
// slots or gets to bypass this safety mechanism.
198
type peerSlotStatus struct {
199
        // state determines which privileges the peer has with our server.
200
        state peerAccessStatus
201
}
202

203
// server is the main server of the Lightning Network Daemon. The server houses
204
// global state pertaining to the wallet, database, and the rpcserver.
205
// Additionally, the server is also used as a central messaging bus to interact
206
// with any of its companion objects.
207
type server struct {
208
        active   int32 // atomic
209
        stopping int32 // atomic
210

211
        start sync.Once
212
        stop  sync.Once
213

214
        cfg *Config
215

216
        implCfg *ImplementationCfg
217

218
        // identityECDH is an ECDH capable wrapper for the private key used
219
        // to authenticate any incoming connections.
220
        identityECDH keychain.SingleKeyECDH
221

222
        // identityKeyLoc is the key locator for the above wrapped identity key.
223
        identityKeyLoc keychain.KeyLocator
224

225
        // nodeSigner is an implementation of the MessageSigner implementation
226
        // that's backed by the identity private key of the running lnd node.
227
        nodeSigner *netann.NodeSigner
228

229
        chanStatusMgr *netann.ChanStatusManager
230

231
        // listenAddrs is the list of addresses the server is currently
232
        // listening on.
233
        listenAddrs []net.Addr
234

235
        // torController is a client that will communicate with a locally
236
        // running Tor server. This client will handle initiating and
237
        // authenticating the connection to the Tor server, automatically
238
        // creating and setting up onion services, etc.
239
        torController *tor.Controller
240

241
        // natTraversal is the specific NAT traversal technique used to
242
        // automatically set up port forwarding rules in order to advertise to
243
        // the network that the node is accepting inbound connections.
244
        natTraversal nat.Traversal
245

246
        // lastDetectedIP is the last IP detected by the NAT traversal technique
247
        // above. This IP will be watched periodically in a goroutine in order
248
        // to handle dynamic IP changes.
249
        lastDetectedIP net.IP
250

251
        mu sync.RWMutex
252

253
        // peersByPub is a map of the active peers.
254
        //
255
        // NOTE: The key used here is the raw bytes of the peer's public key to
256
        // string conversion, which means it cannot be printed using `%s` as it
257
        // will just print the binary.
258
        //
259
        // TODO(yy): Use the hex string instead.
260
        peersByPub map[string]*peer.Brontide
261

262
        inboundPeers  map[string]*peer.Brontide
263
        outboundPeers map[string]*peer.Brontide
264

265
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
266
        peerDisconnectedListeners map[string][]chan<- struct{}
267

268
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
269
        // will continue to send messages even if there are no active channels
270
        // and the value below is false. Once it's pruned, all its connections
271
        // will be closed, thus the Brontide.Start will return an error.
272
        persistentPeers        map[string]bool
273
        persistentPeersBackoff map[string]time.Duration
274
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
275
        persistentConnReqs     map[string][]*connmgr.ConnReq
276
        persistentRetryCancels map[string]chan struct{}
277

278
        // peerErrors keeps a set of peer error buffers for peers that have
279
        // disconnected from us. This allows us to track historic peer errors
280
        // over connections. The string of the peer's compressed pubkey is used
281
        // as a key for this map.
282
        peerErrors map[string]*queue.CircularBuffer
283

284
        // ignorePeerTermination tracks peers for which the server has initiated
285
        // a disconnect. Adding a peer to this map causes the peer termination
286
        // watcher to short circuit in the event that peers are purposefully
287
        // disconnected.
288
        ignorePeerTermination map[*peer.Brontide]struct{}
289

290
        // scheduledPeerConnection maps a pubkey string to a callback that
291
        // should be executed in the peerTerminationWatcher the prior peer with
292
        // the same pubkey exits.  This allows the server to wait until the
293
        // prior peer has cleaned up successfully, before adding the new peer
294
        // intended to replace it.
295
        scheduledPeerConnection map[string]func()
296

297
        // pongBuf is a shared pong reply buffer we'll use across all active
298
        // peer goroutines. We know the max size of a pong message
299
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
300
        // avoid allocations each time we need to send a pong message.
301
        pongBuf []byte
302

303
        cc *chainreg.ChainControl
304

305
        fundingMgr *funding.Manager
306

307
        graphDB *graphdb.ChannelGraph
308

309
        chanStateDB *channeldb.ChannelStateDB
310

311
        addrSource channeldb.AddrSource
312

313
        // miscDB is the DB that contains all "other" databases within the main
314
        // channel DB that haven't been separated out yet.
315
        miscDB *channeldb.DB
316

317
        invoicesDB invoices.InvoiceDB
318

319
        aliasMgr *aliasmgr.Manager
320

321
        htlcSwitch *htlcswitch.Switch
322

323
        interceptableSwitch *htlcswitch.InterceptableSwitch
324

325
        invoices *invoices.InvoiceRegistry
326

327
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
328

329
        channelNotifier *channelnotifier.ChannelNotifier
330

331
        peerNotifier *peernotifier.PeerNotifier
332

333
        htlcNotifier *htlcswitch.HtlcNotifier
334

335
        witnessBeacon contractcourt.WitnessBeacon
336

337
        breachArbitrator *contractcourt.BreachArbitrator
338

339
        missionController *routing.MissionController
340
        defaultMC         *routing.MissionControl
341

342
        graphBuilder *graph.Builder
343

344
        chanRouter *routing.ChannelRouter
345

346
        controlTower routing.ControlTower
347

348
        authGossiper *discovery.AuthenticatedGossiper
349

350
        localChanMgr *localchans.Manager
351

352
        utxoNursery *contractcourt.UtxoNursery
353

354
        sweeper *sweep.UtxoSweeper
355

356
        chainArb *contractcourt.ChainArbitrator
357

358
        sphinx *hop.OnionProcessor
359

360
        towerClientMgr *wtclient.Manager
361

362
        connMgr *connmgr.ConnManager
363

364
        sigPool *lnwallet.SigPool
365

366
        writePool *pool.Write
367

368
        readPool *pool.Read
369

370
        tlsManager *TLSManager
371

372
        // featureMgr dispatches feature vectors for various contexts within the
373
        // daemon.
374
        featureMgr *feature.Manager
375

376
        // currentNodeAnn is the node announcement that has been broadcast to
377
        // the network upon startup, if the attributes of the node (us) has
378
        // changed since last start.
379
        currentNodeAnn *lnwire.NodeAnnouncement
380

381
        // chansToRestore is the set of channels that upon starting, the server
382
        // should attempt to restore/recover.
383
        chansToRestore walletunlocker.ChannelsToRecover
384

385
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
386
        // backups are consistent at all times. It interacts with the
387
        // channelNotifier to be notified of newly opened and closed channels.
388
        chanSubSwapper *chanbackup.SubSwapper
389

390
        // chanEventStore tracks the behaviour of channels and their remote peers to
391
        // provide insights into their health and performance.
392
        chanEventStore *chanfitness.ChannelEventStore
393

394
        hostAnn *netann.HostAnnouncer
395

396
        // livenessMonitor monitors that lnd has access to critical resources.
397
        livenessMonitor *healthcheck.Monitor
398

399
        customMessageServer *subscribe.Server
400

401
        onionMessageServer *subscribe.Server
402

403
        // txPublisher is a publisher with fee-bumping capability.
404
        txPublisher *sweep.TxPublisher
405

406
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
407
        // of new blocks.
408
        blockbeatDispatcher *chainio.BlockbeatDispatcher
409

410
        // peerAccessMan implements peer access controls.
411
        peerAccessMan *accessMan
412

413
        quit chan struct{}
414

415
        wg sync.WaitGroup
416
}
417

418
// updatePersistentPeerAddrs subscribes to topology changes and stores
419
// advertised addresses for any NodeAnnouncements from our persisted peers.
420
func (s *server) updatePersistentPeerAddrs() error {
3✔
421
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
422
        if err != nil {
3✔
423
                return err
×
424
        }
×
425

426
        s.wg.Add(1)
3✔
427
        go func() {
6✔
428
                defer func() {
6✔
429
                        graphSub.Cancel()
3✔
430
                        s.wg.Done()
3✔
431
                }()
3✔
432

433
                for {
6✔
434
                        select {
3✔
435
                        case <-s.quit:
3✔
436
                                return
3✔
437

438
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
439
                                // If the router is shutting down, then we will
3✔
440
                                // as well.
3✔
441
                                if !ok {
3✔
442
                                        return
×
443
                                }
×
444

445
                                for _, update := range topChange.NodeUpdates {
6✔
446
                                        pubKeyStr := string(
3✔
447
                                                update.IdentityKey.
3✔
448
                                                        SerializeCompressed(),
3✔
449
                                        )
3✔
450

3✔
451
                                        // We only care about updates from
3✔
452
                                        // our persistentPeers.
3✔
453
                                        s.mu.RLock()
3✔
454
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
455
                                        s.mu.RUnlock()
3✔
456
                                        if !ok {
6✔
457
                                                continue
3✔
458
                                        }
459

460
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
461
                                                len(update.Addresses))
3✔
462

3✔
463
                                        for _, addr := range update.Addresses {
6✔
464
                                                addrs = append(addrs,
3✔
465
                                                        &lnwire.NetAddress{
3✔
466
                                                                IdentityKey: update.IdentityKey,
3✔
467
                                                                Address:     addr,
3✔
468
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
469
                                                        },
3✔
470
                                                )
3✔
471
                                        }
3✔
472

473
                                        s.mu.Lock()
3✔
474

3✔
475
                                        // Update the stored addresses for this
3✔
476
                                        // to peer to reflect the new set.
3✔
477
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
478

3✔
479
                                        // If there are no outstanding
3✔
480
                                        // connection requests for this peer
3✔
481
                                        // then our work is done since we are
3✔
482
                                        // not currently trying to connect to
3✔
483
                                        // them.
3✔
484
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
485
                                                s.mu.Unlock()
3✔
486
                                                continue
3✔
487
                                        }
488

489
                                        s.mu.Unlock()
3✔
490

3✔
491
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
492
                                }
493
                        }
494
                }
495
        }()
496

497
        return nil
3✔
498
}
499

500
// CustomMessage is a custom message that is received from a peer.
501
type CustomMessage struct {
502
        // Peer is the peer pubkey
503
        Peer [33]byte
504

505
        // Msg is the custom wire message.
506
        Msg *lnwire.Custom
507
}
508

509
// parseAddr parses an address from its string format to a net.Addr.
510
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
511
        var (
3✔
512
                host string
3✔
513
                port int
3✔
514
        )
3✔
515

3✔
516
        // Split the address into its host and port components.
3✔
517
        h, p, err := net.SplitHostPort(address)
3✔
518
        if err != nil {
3✔
519
                // If a port wasn't specified, we'll assume the address only
×
520
                // contains the host so we'll use the default port.
×
521
                host = address
×
522
                port = defaultPeerPort
×
523
        } else {
3✔
524
                // Otherwise, we'll note both the host and ports.
3✔
525
                host = h
3✔
526
                portNum, err := strconv.Atoi(p)
3✔
527
                if err != nil {
3✔
528
                        return nil, err
×
529
                }
×
530
                port = portNum
3✔
531
        }
532

533
        if tor.IsOnionHost(host) {
3✔
534
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
535
        }
×
536

537
        // If the host is part of a TCP address, we'll use the network
538
        // specific ResolveTCPAddr function in order to resolve these
539
        // addresses over Tor in order to prevent leaking your real IP
540
        // address.
541
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
542
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
543
}
544

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

3✔
550
        return func(a net.Addr) (net.Conn, error) {
6✔
551
                lnAddr := a.(*lnwire.NetAddress)
3✔
552
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
553
        }
3✔
554
}
555

556
// newServer creates a new instance of the server which is to listen using the
557
// passed listener address.
558
//
559
//nolint:funlen
560
func newServer(_ context.Context, cfg *Config, listenAddrs []net.Addr,
561
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
562
        nodeKeyDesc *keychain.KeyDescriptor,
563
        chansToRestore walletunlocker.ChannelsToRecover,
564
        chanPredicate chanacceptor.ChannelAcceptor,
565
        torController *tor.Controller, tlsManager *TLSManager,
566
        leaderElector cluster.LeaderElector,
567
        implCfg *ImplementationCfg) (*server, error) {
3✔
568

3✔
569
        var (
3✔
570
                err         error
3✔
571
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
572

3✔
573
                // We just derived the full descriptor, so we know the public
3✔
574
                // key is set on it.
3✔
575
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
576
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
577
                )
3✔
578
        )
3✔
579

3✔
580
        var serializedPubKey [33]byte
3✔
581
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
582

3✔
583
        netParams := cfg.ActiveNetParams.Params
3✔
584

3✔
585
        // Initialize the sphinx router.
3✔
586
        replayLog := htlcswitch.NewDecayedLog(
3✔
587
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
588
        )
3✔
589
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
590

3✔
591
        writeBufferPool := pool.NewWriteBuffer(
3✔
592
                pool.DefaultWriteBufferGCInterval,
3✔
593
                pool.DefaultWriteBufferExpiryInterval,
3✔
594
        )
3✔
595

3✔
596
        writePool := pool.NewWrite(
3✔
597
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
598
        )
3✔
599

3✔
600
        readBufferPool := pool.NewReadBuffer(
3✔
601
                pool.DefaultReadBufferGCInterval,
3✔
602
                pool.DefaultReadBufferExpiryInterval,
3✔
603
        )
3✔
604

3✔
605
        readPool := pool.NewRead(
3✔
606
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
607
        )
3✔
608

3✔
609
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
610
        // controller, then we'll exit as this is incompatible.
3✔
611
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
612
                implCfg.AuxFundingController.IsNone() {
3✔
613

×
614
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
615
                        "aux controllers")
×
616
        }
×
617

618
        //nolint:ll
619
        featureMgr, err := feature.NewManager(feature.Config{
3✔
620
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
621
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
622
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
623
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
624
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
625
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
626
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
627
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
628
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
629
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
630
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
631
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
632
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
633
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
634
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
635
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
636
        })
3✔
637
        if err != nil {
3✔
638
                return nil, err
×
639
        }
×
640

641
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
642
        registryConfig := invoices.RegistryConfig{
3✔
643
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
644
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
645
                Clock:                       clock.NewDefaultClock(),
3✔
646
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
647
                AcceptAMP:                   cfg.AcceptAMP,
3✔
648
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
649
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
650
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
651
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
652
        }
3✔
653

3✔
654
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
655

3✔
656
        s := &server{
3✔
657
                cfg:            cfg,
3✔
658
                implCfg:        implCfg,
3✔
659
                graphDB:        dbs.GraphDB,
3✔
660
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
661
                addrSource:     addrSource,
3✔
662
                miscDB:         dbs.ChanStateDB,
3✔
663
                invoicesDB:     dbs.InvoiceDB,
3✔
664
                cc:             cc,
3✔
665
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
666
                writePool:      writePool,
3✔
667
                readPool:       readPool,
3✔
668
                chansToRestore: chansToRestore,
3✔
669

3✔
670
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
671
                        cc.ChainNotifier,
3✔
672
                ),
3✔
673
                channelNotifier: channelnotifier.New(
3✔
674
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
675
                ),
3✔
676

3✔
677
                identityECDH:   nodeKeyECDH,
3✔
678
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
679
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
680

3✔
681
                listenAddrs: listenAddrs,
3✔
682

3✔
683
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
684
                // schedule
3✔
685
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
686

3✔
687
                torController: torController,
3✔
688

3✔
689
                persistentPeers:         make(map[string]bool),
3✔
690
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
691
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
692
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
693
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
694
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
695
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
696
                scheduledPeerConnection: make(map[string]func()),
3✔
697
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
698

3✔
699
                peersByPub:                make(map[string]*peer.Brontide),
3✔
700
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
701
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
702
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
703
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
704

3✔
705
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
706

3✔
707
                customMessageServer: subscribe.NewServer(),
3✔
708

3✔
709
                onionMessageServer: subscribe.NewServer(),
3✔
710

3✔
711
                tlsManager: tlsManager,
3✔
712

3✔
713
                featureMgr: featureMgr,
3✔
714
                quit:       make(chan struct{}),
3✔
715
        }
3✔
716

3✔
717
        // Start the low-level services once they are initialized.
3✔
718
        //
3✔
719
        // TODO(yy): break the server startup into four steps,
3✔
720
        // 1. init the low-level services.
3✔
721
        // 2. start the low-level services.
3✔
722
        // 3. init the high-level services.
3✔
723
        // 4. start the high-level services.
3✔
724
        if err := s.startLowLevelServices(); err != nil {
3✔
725
                return nil, err
×
726
        }
×
727

728
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
729
        if err != nil {
3✔
730
                return nil, err
×
731
        }
×
732

733
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
734
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
735
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
736
        )
3✔
737
        s.invoices = invoices.NewRegistry(
3✔
738
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
739
        )
3✔
740

3✔
741
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
742

3✔
743
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
744
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
745

3✔
746
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
747
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
748
                if err != nil {
3✔
749
                        return err
×
750
                }
×
751

752
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
753

3✔
754
                return nil
3✔
755
        }
756

757
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
758
        if err != nil {
3✔
759
                return nil, err
×
760
        }
×
761

762
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
763
                DB:                   dbs.ChanStateDB,
3✔
764
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
765
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
766
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
767
                LocalChannelClose: func(pubKey []byte,
3✔
768
                        request *htlcswitch.ChanClose) {
6✔
769

3✔
770
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
771
                        if err != nil {
3✔
772
                                srvrLog.Errorf("unable to close channel, peer"+
×
773
                                        " with %v id can't be found: %v",
×
774
                                        pubKey, err,
×
775
                                )
×
776
                                return
×
777
                        }
×
778

779
                        peer.HandleLocalCloseChanReqs(request)
3✔
780
                },
781
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
782
                SwitchPackager:         channeldb.NewSwitchPackager(),
783
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
784
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
785
                Notifier:               s.cc.ChainNotifier,
786
                HtlcNotifier:           s.htlcNotifier,
787
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
788
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
789
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
790
                AllowCircularRoute:     cfg.AllowCircularRoute,
791
                RejectHTLC:             cfg.RejectHTLC,
792
                Clock:                  clock.NewDefaultClock(),
793
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
794
                MaxFeeExposure:         thresholdMSats,
795
                SignAliasUpdate:        s.signAliasUpdate,
796
                IsAlias:                aliasmgr.IsAlias,
797
        }, uint32(currentHeight))
798
        if err != nil {
3✔
799
                return nil, err
×
800
        }
×
801
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
802
                &htlcswitch.InterceptableSwitchConfig{
3✔
803
                        Switch:             s.htlcSwitch,
3✔
804
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
805
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
806
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
807
                        Notifier:           s.cc.ChainNotifier,
3✔
808
                },
3✔
809
        )
3✔
810
        if err != nil {
3✔
811
                return nil, err
×
812
        }
×
813

814
        s.witnessBeacon = newPreimageBeacon(
3✔
815
                dbs.ChanStateDB.NewWitnessCache(),
3✔
816
                s.interceptableSwitch.ForwardPacket,
3✔
817
        )
3✔
818

3✔
819
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
820
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
821
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
822
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
823
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
824
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
825
                MessageSigner:            s.nodeSigner,
3✔
826
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
827
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
828
                DB:                       s.chanStateDB,
3✔
829
                Graph:                    dbs.GraphDB,
3✔
830
        }
3✔
831

3✔
832
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
833
        if err != nil {
3✔
834
                return nil, err
×
835
        }
×
836
        s.chanStatusMgr = chanStatusMgr
3✔
837

3✔
838
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
839
        // port forwarding for users behind a NAT.
3✔
840
        if cfg.NAT {
3✔
841
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
842

×
843
                discoveryTimeout := time.Duration(10 * time.Second)
×
844

×
845
                ctx, cancel := context.WithTimeout(
×
846
                        context.Background(), discoveryTimeout,
×
847
                )
×
848
                defer cancel()
×
849
                upnp, err := nat.DiscoverUPnP(ctx)
×
850
                if err == nil {
×
851
                        s.natTraversal = upnp
×
852
                } else {
×
853
                        // If we were not able to discover a UPnP enabled device
×
854
                        // on the local network, we'll fall back to attempting
×
855
                        // to discover a NAT-PMP enabled device.
×
856
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
857
                                "device on the local network: %v", err)
×
858

×
859
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
860
                                "enabled device")
×
861

×
862
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
863
                        if err != nil {
×
864
                                err := fmt.Errorf("unable to discover a "+
×
865
                                        "NAT-PMP enabled device on the local "+
×
866
                                        "network: %v", err)
×
867
                                srvrLog.Error(err)
×
868
                                return nil, err
×
869
                        }
×
870

871
                        s.natTraversal = pmp
×
872
                }
873
        }
874

875
        // If we were requested to automatically configure port forwarding,
876
        // we'll use the ports that the server will be listening on.
877
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
878
        for idx, ip := range cfg.ExternalIPs {
6✔
879
                externalIPStrings[idx] = ip.String()
3✔
880
        }
3✔
881
        if s.natTraversal != nil {
3✔
882
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
883
                for _, listenAddr := range listenAddrs {
×
884
                        // At this point, the listen addresses should have
×
885
                        // already been normalized, so it's safe to ignore the
×
886
                        // errors.
×
887
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
888
                        port, _ := strconv.Atoi(portStr)
×
889

×
890
                        listenPorts = append(listenPorts, uint16(port))
×
891
                }
×
892

893
                ips, err := s.configurePortForwarding(listenPorts...)
×
894
                if err != nil {
×
895
                        srvrLog.Errorf("Unable to automatically set up port "+
×
896
                                "forwarding using %s: %v",
×
897
                                s.natTraversal.Name(), err)
×
898
                } else {
×
899
                        srvrLog.Infof("Automatically set up port forwarding "+
×
900
                                "using %s to advertise external IP",
×
901
                                s.natTraversal.Name())
×
902
                        externalIPStrings = append(externalIPStrings, ips...)
×
903
                }
×
904
        }
905

906
        // If external IP addresses have been specified, add those to the list
907
        // of this server's addresses.
908
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
909
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
910
                cfg.net.ResolveTCPAddr,
3✔
911
        )
3✔
912
        if err != nil {
3✔
913
                return nil, err
×
914
        }
×
915

916
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
917
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
918

3✔
919
        // We'll now reconstruct a node announcement based on our current
3✔
920
        // configuration so we can send it out as a sort of heart beat within
3✔
921
        // the network.
3✔
922
        //
3✔
923
        // We'll start by parsing the node color from configuration.
3✔
924
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
925
        if err != nil {
3✔
926
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
927
                return nil, err
×
928
        }
×
929

930
        // If no alias is provided, default to first 10 characters of public
931
        // key.
932
        alias := cfg.Alias
3✔
933
        if alias == "" {
6✔
934
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
935
        }
3✔
936
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
937
        if err != nil {
3✔
938
                return nil, err
×
939
        }
×
940
        selfNode := &models.LightningNode{
3✔
941
                HaveNodeAnnouncement: true,
3✔
942
                LastUpdate:           time.Now(),
3✔
943
                Addresses:            selfAddrs,
3✔
944
                Alias:                nodeAlias.String(),
3✔
945
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
946
                Color:                color,
3✔
947
        }
3✔
948
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
949

3✔
950
        // Based on the disk representation of the node announcement generated
3✔
951
        // above, we'll generate a node announcement that can go out on the
3✔
952
        // network so we can properly sign it.
3✔
953
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
954
        if err != nil {
3✔
955
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
956
        }
×
957

958
        // With the announcement generated, we'll sign it to properly
959
        // authenticate the message on the network.
960
        authSig, err := netann.SignAnnouncement(
3✔
961
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
962
        )
3✔
963
        if err != nil {
3✔
964
                return nil, fmt.Errorf("unable to generate signature for "+
×
965
                        "self node announcement: %v", err)
×
966
        }
×
967
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
968
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
969
                selfNode.AuthSigBytes,
3✔
970
        )
3✔
971
        if err != nil {
3✔
972
                return nil, err
×
973
        }
×
974

975
        // Finally, we'll update the representation on disk, and update our
976
        // cached in-memory version as well.
977
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
978
                return nil, fmt.Errorf("can't set self node: %w", err)
×
979
        }
×
980
        s.currentNodeAnn = nodeAnn
3✔
981

3✔
982
        // The router will get access to the payment ID sequencer, such that it
3✔
983
        // can generate unique payment IDs.
3✔
984
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
985
        if err != nil {
3✔
986
                return nil, err
×
987
        }
×
988

989
        // Instantiate mission control with config from the sub server.
990
        //
991
        // TODO(joostjager): When we are further in the process of moving to sub
992
        // servers, the mission control instance itself can be moved there too.
993
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
994

3✔
995
        // We only initialize a probability estimator if there's no custom one.
3✔
996
        var estimator routing.Estimator
3✔
997
        if cfg.Estimator != nil {
3✔
998
                estimator = cfg.Estimator
×
999
        } else {
3✔
1000
                switch routingConfig.ProbabilityEstimatorType {
3✔
1001
                case routing.AprioriEstimatorName:
3✔
1002
                        aCfg := routingConfig.AprioriConfig
3✔
1003
                        aprioriConfig := routing.AprioriConfig{
3✔
1004
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1005
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1006
                                AprioriWeight:         aCfg.Weight,
3✔
1007
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1008
                        }
3✔
1009

3✔
1010
                        estimator, err = routing.NewAprioriEstimator(
3✔
1011
                                aprioriConfig,
3✔
1012
                        )
3✔
1013
                        if err != nil {
3✔
1014
                                return nil, err
×
1015
                        }
×
1016

1017
                case routing.BimodalEstimatorName:
×
1018
                        bCfg := routingConfig.BimodalConfig
×
1019
                        bimodalConfig := routing.BimodalConfig{
×
1020
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1021
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1022
                                        bCfg.Scale,
×
1023
                                ),
×
1024
                                BimodalDecayTime: bCfg.DecayTime,
×
1025
                        }
×
1026

×
1027
                        estimator, err = routing.NewBimodalEstimator(
×
1028
                                bimodalConfig,
×
1029
                        )
×
1030
                        if err != nil {
×
1031
                                return nil, err
×
1032
                        }
×
1033

1034
                default:
×
1035
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1036
                                routingConfig.ProbabilityEstimatorType)
×
1037
                }
1038
        }
1039

1040
        mcCfg := &routing.MissionControlConfig{
3✔
1041
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1042
                Estimator:               estimator,
3✔
1043
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1044
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1045
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1046
        }
3✔
1047

3✔
1048
        s.missionController, err = routing.NewMissionController(
3✔
1049
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1050
        )
3✔
1051
        if err != nil {
3✔
1052
                return nil, fmt.Errorf("can't create mission control "+
×
1053
                        "manager: %w", err)
×
1054
        }
×
1055
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1056
                routing.DefaultMissionControlNamespace,
3✔
1057
        )
3✔
1058
        if err != nil {
3✔
1059
                return nil, fmt.Errorf("can't create mission control in the "+
×
1060
                        "default namespace: %w", err)
×
1061
        }
×
1062

1063
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1064
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1065
                int64(routingConfig.AttemptCost),
3✔
1066
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1067
                routingConfig.MinRouteProbability)
3✔
1068

3✔
1069
        pathFindingConfig := routing.PathFindingConfig{
3✔
1070
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1071
                        routingConfig.AttemptCost,
3✔
1072
                ),
3✔
1073
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1074
                MinProbability: routingConfig.MinRouteProbability,
3✔
1075
        }
3✔
1076

3✔
1077
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1078
        if err != nil {
3✔
1079
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1080
        }
×
1081
        paymentSessionSource := &routing.SessionSource{
3✔
1082
                GraphSessionFactory: dbs.GraphDB,
3✔
1083
                SourceNode:          sourceNode,
3✔
1084
                MissionControl:      s.defaultMC,
3✔
1085
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1086
                PathFindingConfig:   pathFindingConfig,
3✔
1087
        }
3✔
1088

3✔
1089
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1090

3✔
1091
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1092

3✔
1093
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1094
                cfg.Routing.StrictZombiePruning
3✔
1095

3✔
1096
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1097
                SelfNode:            selfNode.PubKeyBytes,
3✔
1098
                Graph:               dbs.GraphDB,
3✔
1099
                Chain:               cc.ChainIO,
3✔
1100
                ChainView:           cc.ChainView,
3✔
1101
                Notifier:            cc.ChainNotifier,
3✔
1102
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1103
                GraphPruneInterval:  time.Hour,
3✔
1104
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1105
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1106
                StrictZombiePruning: strictPruning,
3✔
1107
                IsAlias:             aliasmgr.IsAlias,
3✔
1108
        })
3✔
1109
        if err != nil {
3✔
1110
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1111
        }
×
1112

1113
        s.chanRouter, err = routing.New(routing.Config{
3✔
1114
                SelfNode:           selfNode.PubKeyBytes,
3✔
1115
                RoutingGraph:       dbs.GraphDB,
3✔
1116
                Chain:              cc.ChainIO,
3✔
1117
                Payer:              s.htlcSwitch,
3✔
1118
                Control:            s.controlTower,
3✔
1119
                MissionControl:     s.defaultMC,
3✔
1120
                SessionSource:      paymentSessionSource,
3✔
1121
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1122
                NextPaymentID:      sequencer.NextID,
3✔
1123
                PathFindingConfig:  pathFindingConfig,
3✔
1124
                Clock:              clock.NewDefaultClock(),
3✔
1125
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1126
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1127
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1128
        })
3✔
1129
        if err != nil {
3✔
1130
                return nil, fmt.Errorf("can't create router: %w", err)
×
1131
        }
×
1132

1133
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1134
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1135
        if err != nil {
3✔
1136
                return nil, err
×
1137
        }
×
1138
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1139
        if err != nil {
3✔
1140
                return nil, err
×
1141
        }
×
1142

1143
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1144

3✔
1145
        s.authGossiper = discovery.New(discovery.Config{
3✔
1146
                Graph:                 s.graphBuilder,
3✔
1147
                ChainIO:               s.cc.ChainIO,
3✔
1148
                Notifier:              s.cc.ChainNotifier,
3✔
1149
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1150
                Broadcast:             s.BroadcastMessage,
3✔
1151
                ChanSeries:            chanSeries,
3✔
1152
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1153
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1154
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1155
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1156
                        error) {
3✔
1157

×
1158
                        return s.genNodeAnnouncement(nil)
×
1159
                },
×
1160
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1161
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1162
                RetransmitTicker:        ticker.New(time.Minute * 30),
1163
                RebroadcastInterval:     time.Hour * 24,
1164
                WaitingProofStore:       waitingProofStore,
1165
                MessageStore:            gossipMessageStore,
1166
                AnnSigner:               s.nodeSigner,
1167
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1168
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1169
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1170
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1171
                MinimumBatchSize:        10,
1172
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1173
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1174
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1175
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1176
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1177
                IsAlias:                 aliasmgr.IsAlias,
1178
                SignAliasUpdate:         s.signAliasUpdate,
1179
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1180
                GetAlias:                s.aliasMgr.GetPeerAlias,
1181
                FindChannel:             s.findChannel,
1182
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1183
                ScidCloser:              scidCloserMan,
1184
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1185
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1186
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1187
        }, nodeKeyDesc)
1188

1189
        accessCfg := &accessManConfig{
3✔
1190
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1191
                        error) {
6✔
1192

3✔
1193
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1194
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1195
                                genesisHash[:],
3✔
1196
                        )
3✔
1197
                },
3✔
1198
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1199
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1200
        }
1201

1202
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1203
        if err != nil {
3✔
1204
                return nil, err
×
1205
        }
×
1206

1207
        s.peerAccessMan = peerAccessMan
3✔
1208

3✔
1209
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1210
        //nolint:ll
3✔
1211
        s.localChanMgr = &localchans.Manager{
3✔
1212
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1213
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1214
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1215
                        *models.ChannelEdgePolicy) error) error {
6✔
1216

3✔
1217
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1218
                                func(c *models.ChannelEdgeInfo,
3✔
1219
                                        e *models.ChannelEdgePolicy,
3✔
1220
                                        _ *models.ChannelEdgePolicy) error {
6✔
1221

3✔
1222
                                        // NOTE: The invoked callback here may
3✔
1223
                                        // receive a nil channel policy.
3✔
1224
                                        return cb(c, e)
3✔
1225
                                },
3✔
1226
                        )
1227
                },
1228
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1229
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1230
                FetchChannel:              s.chanStateDB.FetchChannel,
1231
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1232
                        return s.graphBuilder.AddEdge(edge)
×
1233
                },
×
1234
        }
1235

1236
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1237
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1238
        )
3✔
1239
        if err != nil {
3✔
1240
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1241
                return nil, err
×
1242
        }
×
1243

1244
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1245
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1246
        )
3✔
1247
        if err != nil {
3✔
1248
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1249
                return nil, err
×
1250
        }
×
1251

1252
        aggregator := sweep.NewBudgetAggregator(
3✔
1253
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1254
                s.implCfg.AuxSweeper,
3✔
1255
        )
3✔
1256

3✔
1257
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1258
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1259
                Wallet:     cc.Wallet,
3✔
1260
                Estimator:  cc.FeeEstimator,
3✔
1261
                Notifier:   cc.ChainNotifier,
3✔
1262
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1263
        })
3✔
1264

3✔
1265
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1266
                FeeEstimator: cc.FeeEstimator,
3✔
1267
                GenSweepScript: newSweepPkScriptGen(
3✔
1268
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1269
                ),
3✔
1270
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1271
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1272
                Mempool:              cc.MempoolNotifier,
3✔
1273
                Notifier:             cc.ChainNotifier,
3✔
1274
                Store:                sweeperStore,
3✔
1275
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1276
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1277
                Aggregator:           aggregator,
3✔
1278
                Publisher:            s.txPublisher,
3✔
1279
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1280
        })
3✔
1281

3✔
1282
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1283
                ChainIO:             cc.ChainIO,
3✔
1284
                ConfDepth:           1,
3✔
1285
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1286
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1287
                Notifier:            cc.ChainNotifier,
3✔
1288
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1289
                Store:               utxnStore,
3✔
1290
                SweepInput:          s.sweeper.SweepInput,
3✔
1291
                Budget:              s.cfg.Sweeper.Budget,
3✔
1292
        })
3✔
1293

3✔
1294
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1295
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1296
                closureType contractcourt.ChannelCloseType) {
6✔
1297
                // TODO(conner): Properly respect the update and error channels
3✔
1298
                // returned by CloseLink.
3✔
1299

3✔
1300
                // Instruct the switch to close the channel.  Provide no close out
3✔
1301
                // delivery script or target fee per kw because user input is not
3✔
1302
                // available when the remote peer closes the channel.
3✔
1303
                s.htlcSwitch.CloseLink(
3✔
1304
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1305
                )
3✔
1306
        }
3✔
1307

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

3✔
1312
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1313
                &contractcourt.BreachConfig{
3✔
1314
                        CloseLink: closeLink,
3✔
1315
                        DB:        s.chanStateDB,
3✔
1316
                        Estimator: s.cc.FeeEstimator,
3✔
1317
                        GenSweepScript: newSweepPkScriptGen(
3✔
1318
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1319
                        ),
3✔
1320
                        Notifier:           cc.ChainNotifier,
3✔
1321
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1322
                        ContractBreaches:   contractBreaches,
3✔
1323
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1324
                        Store: contractcourt.NewRetributionStore(
3✔
1325
                                dbs.ChanStateDB,
3✔
1326
                        ),
3✔
1327
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1328
                },
3✔
1329
        )
3✔
1330

3✔
1331
        //nolint:ll
3✔
1332
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1333
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1334
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1335
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1336
                NewSweepAddr: func() ([]byte, error) {
3✔
1337
                        addr, err := newSweepPkScriptGen(
×
1338
                                cc.Wallet, netParams,
×
1339
                        )().Unpack()
×
1340
                        if err != nil {
×
1341
                                return nil, err
×
1342
                        }
×
1343

1344
                        return addr.DeliveryAddress, nil
×
1345
                },
1346
                PublishTx: cc.Wallet.PublishTransaction,
1347
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1348
                        for _, msg := range msgs {
6✔
1349
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1350
                                if err != nil {
3✔
1351
                                        return err
×
1352
                                }
×
1353
                        }
1354
                        return nil
3✔
1355
                },
1356
                IncubateOutputs: func(chanPoint wire.OutPoint,
1357
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1358
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1359
                        broadcastHeight uint32,
1360
                        deadlineHeight fn.Option[int32]) error {
3✔
1361

3✔
1362
                        return s.utxoNursery.IncubateOutputs(
3✔
1363
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1364
                                broadcastHeight, deadlineHeight,
3✔
1365
                        )
3✔
1366
                },
3✔
1367
                PreimageDB:   s.witnessBeacon,
1368
                Notifier:     cc.ChainNotifier,
1369
                Mempool:      cc.MempoolNotifier,
1370
                Signer:       cc.Wallet.Cfg.Signer,
1371
                FeeEstimator: cc.FeeEstimator,
1372
                ChainIO:      cc.ChainIO,
1373
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1374
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1375
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1376
                        return nil
3✔
1377
                },
3✔
1378
                IsOurAddress: cc.Wallet.IsOurAddress,
1379
                ContractBreach: func(chanPoint wire.OutPoint,
1380
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1381

3✔
1382
                        // processACK will handle the BreachArbitrator ACKing
3✔
1383
                        // the event.
3✔
1384
                        finalErr := make(chan error, 1)
3✔
1385
                        processACK := func(brarErr error) {
6✔
1386
                                if brarErr != nil {
3✔
1387
                                        finalErr <- brarErr
×
1388
                                        return
×
1389
                                }
×
1390

1391
                                // If the BreachArbitrator successfully handled
1392
                                // the event, we can signal that the handoff
1393
                                // was successful.
1394
                                finalErr <- nil
3✔
1395
                        }
1396

1397
                        event := &contractcourt.ContractBreachEvent{
3✔
1398
                                ChanPoint:         chanPoint,
3✔
1399
                                ProcessACK:        processACK,
3✔
1400
                                BreachRetribution: breachRet,
3✔
1401
                        }
3✔
1402

3✔
1403
                        // Send the contract breach event to the
3✔
1404
                        // BreachArbitrator.
3✔
1405
                        select {
3✔
1406
                        case contractBreaches <- event:
3✔
1407
                        case <-s.quit:
×
1408
                                return ErrServerShuttingDown
×
1409
                        }
1410

1411
                        // We'll wait for a final error to be available from
1412
                        // the BreachArbitrator.
1413
                        select {
3✔
1414
                        case err := <-finalErr:
3✔
1415
                                return err
3✔
1416
                        case <-s.quit:
×
1417
                                return ErrServerShuttingDown
×
1418
                        }
1419
                },
1420
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1421
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1422
                },
3✔
1423
                Sweeper:                       s.sweeper,
1424
                Registry:                      s.invoices,
1425
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1426
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1427
                OnionProcessor:                s.sphinx,
1428
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1429
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1430
                Clock:                         clock.NewDefaultClock(),
1431
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1432
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1433
                HtlcNotifier:                  s.htlcNotifier,
1434
                Budget:                        *s.cfg.Sweeper.Budget,
1435

1436
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1437
                QueryIncomingCircuit: func(
1438
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1439

3✔
1440
                        // Get the circuit map.
3✔
1441
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1442

3✔
1443
                        // Lookup the outgoing circuit.
3✔
1444
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1445
                        if pc == nil {
5✔
1446
                                return nil
2✔
1447
                        }
2✔
1448

1449
                        return &pc.Incoming
3✔
1450
                },
1451
                AuxLeafStore: implCfg.AuxLeafStore,
1452
                AuxSigner:    implCfg.AuxSigner,
1453
                AuxResolver:  implCfg.AuxContractResolver,
1454
        }, dbs.ChanStateDB)
1455

1456
        // Select the configuration and funding parameters for Bitcoin.
1457
        chainCfg := cfg.Bitcoin
3✔
1458
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1459
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1460

3✔
1461
        var chanIDSeed [32]byte
3✔
1462
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1463
                return nil, err
×
1464
        }
×
1465

1466
        // Wrap the DeleteChannelEdges method so that the funding manager can
1467
        // use it without depending on several layers of indirection.
1468
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1469
                *models.ChannelEdgePolicy, error) {
6✔
1470

3✔
1471
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1472
                        scid.ToUint64(),
3✔
1473
                )
3✔
1474
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1475
                        // This is unlikely but there is a slim chance of this
×
1476
                        // being hit if lnd was killed via SIGKILL and the
×
1477
                        // funding manager was stepping through the delete
×
1478
                        // alias edge logic.
×
1479
                        return nil, nil
×
1480
                } else if err != nil {
3✔
1481
                        return nil, err
×
1482
                }
×
1483

1484
                // Grab our key to find our policy.
1485
                var ourKey [33]byte
3✔
1486
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1487

3✔
1488
                var ourPolicy *models.ChannelEdgePolicy
3✔
1489
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1490
                        ourPolicy = e1
3✔
1491
                } else {
6✔
1492
                        ourPolicy = e2
3✔
1493
                }
3✔
1494

1495
                if ourPolicy == nil {
3✔
1496
                        // Something is wrong, so return an error.
×
1497
                        return nil, fmt.Errorf("we don't have an edge")
×
1498
                }
×
1499

1500
                err = s.graphDB.DeleteChannelEdges(
3✔
1501
                        false, false, scid.ToUint64(),
3✔
1502
                )
3✔
1503
                return ourPolicy, err
3✔
1504
        }
1505

1506
        // For the reservationTimeout and the zombieSweeperInterval different
1507
        // values are set in case we are in a dev environment so enhance test
1508
        // capacilities.
1509
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1510
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1511

3✔
1512
        // Get the development config for funding manager. If we are not in
3✔
1513
        // development mode, this would be nil.
3✔
1514
        var devCfg *funding.DevConfig
3✔
1515
        if lncfg.IsDevBuild() {
6✔
1516
                devCfg = &funding.DevConfig{
3✔
1517
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1518
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1519
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1520
                }
3✔
1521

3✔
1522
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1523
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1524

3✔
1525
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1526
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1527
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1528
        }
3✔
1529

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

3✔
1548
                        return s.genNodeAnnouncement(nil)
3✔
1549
                },
3✔
1550
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1551
                NotifyWhenOnline:     s.NotifyWhenOnline,
1552
                TempChanIDSeed:       chanIDSeed,
1553
                FindChannel:          s.findChannel,
1554
                DefaultRoutingPolicy: cc.RoutingPolicy,
1555
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1556
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1557
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1558
                        // For large channels we increase the number
3✔
1559
                        // of confirmations we require for the
3✔
1560
                        // channel to be considered open. As it is
3✔
1561
                        // always the responder that gets to choose
3✔
1562
                        // value, the pushAmt is value being pushed
3✔
1563
                        // to us. This means we have more to lose
3✔
1564
                        // in the case this gets re-orged out, and
3✔
1565
                        // we will require more confirmations before
3✔
1566
                        // we consider it open.
3✔
1567

3✔
1568
                        // In case the user has explicitly specified
3✔
1569
                        // a default value for the number of
3✔
1570
                        // confirmations, we use it.
3✔
1571
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1572
                        if defaultConf != 0 {
6✔
1573
                                return defaultConf
3✔
1574
                        }
3✔
1575

1576
                        minConf := uint64(3)
×
1577
                        maxConf := uint64(6)
×
1578

×
1579
                        // If this is a wumbo channel, then we'll require the
×
1580
                        // max amount of confirmations.
×
1581
                        if chanAmt > MaxFundingAmount {
×
1582
                                return uint16(maxConf)
×
1583
                        }
×
1584

1585
                        // If not we return a value scaled linearly
1586
                        // between 3 and 6, depending on channel size.
1587
                        // TODO(halseth): Use 1 as minimum?
1588
                        maxChannelSize := uint64(
×
1589
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1590
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1591
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1592
                        if conf < minConf {
×
1593
                                conf = minConf
×
1594
                        }
×
1595
                        if conf > maxConf {
×
1596
                                conf = maxConf
×
1597
                        }
×
1598
                        return uint16(conf)
×
1599
                },
1600
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1601
                        // We scale the remote CSV delay (the time the
3✔
1602
                        // remote have to claim funds in case of a unilateral
3✔
1603
                        // close) linearly from minRemoteDelay blocks
3✔
1604
                        // for small channels, to maxRemoteDelay blocks
3✔
1605
                        // for channels of size MaxFundingAmount.
3✔
1606

3✔
1607
                        // In case the user has explicitly specified
3✔
1608
                        // a default value for the remote delay, we
3✔
1609
                        // use it.
3✔
1610
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1611
                        if defaultDelay > 0 {
6✔
1612
                                return defaultDelay
3✔
1613
                        }
3✔
1614

1615
                        // If this is a wumbo channel, then we'll require the
1616
                        // max value.
1617
                        if chanAmt > MaxFundingAmount {
×
1618
                                return maxRemoteDelay
×
1619
                        }
×
1620

1621
                        // If not we scale according to channel size.
1622
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1623
                                chanAmt / MaxFundingAmount)
×
1624
                        if delay < minRemoteDelay {
×
1625
                                delay = minRemoteDelay
×
1626
                        }
×
1627
                        if delay > maxRemoteDelay {
×
1628
                                delay = maxRemoteDelay
×
1629
                        }
×
1630
                        return delay
×
1631
                },
1632
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1633
                        peerKey *btcec.PublicKey) error {
3✔
1634

3✔
1635
                        // First, we'll mark this new peer as a persistent peer
3✔
1636
                        // for re-connection purposes. If the peer is not yet
3✔
1637
                        // tracked or the user hasn't requested it to be perm,
3✔
1638
                        // we'll set false to prevent the server from continuing
3✔
1639
                        // to connect to this peer even if the number of
3✔
1640
                        // channels with this peer is zero.
3✔
1641
                        s.mu.Lock()
3✔
1642
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1643
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1644
                                s.persistentPeers[pubStr] = false
3✔
1645
                        }
3✔
1646
                        s.mu.Unlock()
3✔
1647

3✔
1648
                        // With that taken care of, we'll send this channel to
3✔
1649
                        // the chain arb so it can react to on-chain events.
3✔
1650
                        return s.chainArb.WatchNewChannel(channel)
3✔
1651
                },
1652
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1653
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1654
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1655
                },
3✔
1656
                RequiredRemoteChanReserve: func(chanAmt,
1657
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1658

3✔
1659
                        // By default, we'll require the remote peer to maintain
3✔
1660
                        // at least 1% of the total channel capacity at all
3✔
1661
                        // times. If this value ends up dipping below the dust
3✔
1662
                        // limit, then we'll use the dust limit itself as the
3✔
1663
                        // reserve as required by BOLT #2.
3✔
1664
                        reserve := chanAmt / 100
3✔
1665
                        if reserve < dustLimit {
6✔
1666
                                reserve = dustLimit
3✔
1667
                        }
3✔
1668

1669
                        return reserve
3✔
1670
                },
1671
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1672
                        // By default, we'll allow the remote peer to fully
3✔
1673
                        // utilize the full bandwidth of the channel, minus our
3✔
1674
                        // required reserve.
3✔
1675
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1676
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1677
                },
3✔
1678
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1679
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1680
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1681
                        }
3✔
1682

1683
                        // By default, we'll permit them to utilize the full
1684
                        // channel bandwidth.
1685
                        return uint16(input.MaxHTLCNumber / 2)
×
1686
                },
1687
                ZombieSweeperInterval:         zombieSweeperInterval,
1688
                ReservationTimeout:            reservationTimeout,
1689
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1690
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1691
                MaxPendingChannels:            cfg.MaxPendingChannels,
1692
                RejectPush:                    cfg.RejectPush,
1693
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1694
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1695
                OpenChannelPredicate:          chanPredicate,
1696
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1697
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1698
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1699
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1700
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1701
                DeleteAliasEdge:      deleteAliasEdge,
1702
                AliasManager:         s.aliasMgr,
1703
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1704
                AuxFundingController: implCfg.AuxFundingController,
1705
                AuxSigner:            implCfg.AuxSigner,
1706
                AuxResolver:          implCfg.AuxContractResolver,
1707
        })
1708
        if err != nil {
3✔
1709
                return nil, err
×
1710
        }
×
1711

1712
        // Next, we'll assemble the sub-system that will maintain an on-disk
1713
        // static backup of the latest channel state.
1714
        chanNotifier := &channelNotifier{
3✔
1715
                chanNotifier: s.channelNotifier,
3✔
1716
                addrs:        s.addrSource,
3✔
1717
        }
3✔
1718
        backupFile := chanbackup.NewMultiFile(
3✔
1719
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1720
        )
3✔
1721
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1722
                s.chanStateDB, s.addrSource,
3✔
1723
        )
3✔
1724
        if err != nil {
3✔
1725
                return nil, err
×
1726
        }
×
1727
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1728
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1729
        )
3✔
1730
        if err != nil {
3✔
1731
                return nil, err
×
1732
        }
×
1733

1734
        // Assemble a peer notifier which will provide clients with subscriptions
1735
        // to peer online and offline events.
1736
        s.peerNotifier = peernotifier.New()
3✔
1737

3✔
1738
        // Create a channel event store which monitors all open channels.
3✔
1739
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1740
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1741
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1742
                },
3✔
1743
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1744
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1745
                },
3✔
1746
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1747
                Clock:           clock.NewDefaultClock(),
1748
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1749
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1750
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1751
        })
1752

1753
        if cfg.WtClient.Active {
6✔
1754
                policy := wtpolicy.DefaultPolicy()
3✔
1755
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1756

3✔
1757
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1758
                // protocol operations on sat/kw.
3✔
1759
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1760
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1761
                )
3✔
1762

3✔
1763
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1764

3✔
1765
                if err := policy.Validate(); err != nil {
3✔
1766
                        return nil, err
×
1767
                }
×
1768

1769
                // authDial is the wrapper around the btrontide.Dial for the
1770
                // watchtower.
1771
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1772
                        netAddr *lnwire.NetAddress,
3✔
1773
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1774

3✔
1775
                        return brontide.Dial(
3✔
1776
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1777
                        )
3✔
1778
                }
3✔
1779

1780
                // buildBreachRetribution is a call-back that can be used to
1781
                // query the BreachRetribution info and channel type given a
1782
                // channel ID and commitment height.
1783
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1784
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1785
                        channeldb.ChannelType, error) {
6✔
1786

3✔
1787
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1788
                                nil, chanID,
3✔
1789
                        )
3✔
1790
                        if err != nil {
3✔
1791
                                return nil, 0, err
×
1792
                        }
×
1793

1794
                        br, err := lnwallet.NewBreachRetribution(
3✔
1795
                                channel, commitHeight, 0, nil,
3✔
1796
                                implCfg.AuxLeafStore,
3✔
1797
                                implCfg.AuxContractResolver,
3✔
1798
                        )
3✔
1799
                        if err != nil {
3✔
1800
                                return nil, 0, err
×
1801
                        }
×
1802

1803
                        return br, channel.ChanType, nil
3✔
1804
                }
1805

1806
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1807

3✔
1808
                // Copy the policy for legacy channels and set the blob flag
3✔
1809
                // signalling support for anchor channels.
3✔
1810
                anchorPolicy := policy
3✔
1811
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1812

3✔
1813
                // Copy the policy for legacy channels and set the blob flag
3✔
1814
                // signalling support for taproot channels.
3✔
1815
                taprootPolicy := policy
3✔
1816
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1817
                        blob.FlagTaprootChannel,
3✔
1818
                )
3✔
1819

3✔
1820
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1821
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1822
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1823
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1824
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1825
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1826
                                error) {
6✔
1827

3✔
1828
                                return s.channelNotifier.
3✔
1829
                                        SubscribeChannelEvents()
3✔
1830
                        },
3✔
1831
                        Signer: cc.Wallet.Cfg.Signer,
1832
                        NewAddress: func() ([]byte, error) {
3✔
1833
                                addr, err := newSweepPkScriptGen(
3✔
1834
                                        cc.Wallet, netParams,
3✔
1835
                                )().Unpack()
3✔
1836
                                if err != nil {
3✔
1837
                                        return nil, err
×
1838
                                }
×
1839

1840
                                return addr.DeliveryAddress, nil
3✔
1841
                        },
1842
                        SecretKeyRing:      s.cc.KeyRing,
1843
                        Dial:               cfg.net.Dial,
1844
                        AuthDial:           authDial,
1845
                        DB:                 dbs.TowerClientDB,
1846
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1847
                        MinBackoff:         10 * time.Second,
1848
                        MaxBackoff:         5 * time.Minute,
1849
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1850
                }, policy, anchorPolicy, taprootPolicy)
1851
                if err != nil {
3✔
1852
                        return nil, err
×
1853
                }
×
1854
        }
1855

1856
        if len(cfg.ExternalHosts) != 0 {
3✔
1857
                advertisedIPs := make(map[string]struct{})
×
1858
                for _, addr := range s.currentNodeAnn.Addresses {
×
1859
                        advertisedIPs[addr.String()] = struct{}{}
×
1860
                }
×
1861

1862
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1863
                        Hosts:         cfg.ExternalHosts,
×
1864
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1865
                        LookupHost: func(host string) (net.Addr, error) {
×
1866
                                return lncfg.ParseAddressString(
×
1867
                                        host, strconv.Itoa(defaultPeerPort),
×
1868
                                        cfg.net.ResolveTCPAddr,
×
1869
                                )
×
1870
                        },
×
1871
                        AdvertisedIPs: advertisedIPs,
1872
                        AnnounceNewIPs: netann.IPAnnouncer(
1873
                                func(modifier ...netann.NodeAnnModifier) (
1874
                                        lnwire.NodeAnnouncement, error) {
×
1875

×
1876
                                        return s.genNodeAnnouncement(
×
1877
                                                nil, modifier...,
×
1878
                                        )
×
1879
                                }),
×
1880
                })
1881
        }
1882

1883
        // Create liveness monitor.
1884
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1885

3✔
1886
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1887
        for i, listenAddr := range listenAddrs {
6✔
1888
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1889
                // doesn't need to call the general lndResolveTCP function
3✔
1890
                // since we are resolving a local address.
3✔
1891

3✔
1892
                // RESOLVE: We are actually partially accepting inbound
3✔
1893
                // connection requests when we call NewListener.
3✔
1894
                listeners[i], err = brontide.NewListener(
3✔
1895
                        nodeKeyECDH, listenAddr.String(),
3✔
1896
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1897
                )
3✔
1898
                if err != nil {
3✔
1899
                        return nil, err
×
1900
                }
×
1901
        }
1902

1903
        // Create the connection manager which will be responsible for
1904
        // maintaining persistent outbound connections and also accepting new
1905
        // incoming connections
1906
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1907
                Listeners:      listeners,
3✔
1908
                OnAccept:       s.InboundPeerConnected,
3✔
1909
                RetryDuration:  time.Second * 5,
3✔
1910
                TargetOutbound: 100,
3✔
1911
                Dial: noiseDial(
3✔
1912
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1913
                ),
3✔
1914
                OnConnection: s.OutboundPeerConnected,
3✔
1915
        })
3✔
1916
        if err != nil {
3✔
1917
                return nil, err
×
1918
        }
×
1919
        s.connMgr = cmgr
3✔
1920

3✔
1921
        // Finally, register the subsystems in blockbeat.
3✔
1922
        s.registerBlockConsumers()
3✔
1923

3✔
1924
        return s, nil
3✔
1925
}
1926

1927
// UpdateRoutingConfig is a callback function to update the routing config
1928
// values in the main cfg.
1929
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1930
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1931

3✔
1932
        switch c := cfg.Estimator.Config().(type) {
3✔
1933
        case routing.AprioriConfig:
3✔
1934
                routerCfg.ProbabilityEstimatorType =
3✔
1935
                        routing.AprioriEstimatorName
3✔
1936

3✔
1937
                targetCfg := routerCfg.AprioriConfig
3✔
1938
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1939
                targetCfg.Weight = c.AprioriWeight
3✔
1940
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1941
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1942

1943
        case routing.BimodalConfig:
3✔
1944
                routerCfg.ProbabilityEstimatorType =
3✔
1945
                        routing.BimodalEstimatorName
3✔
1946

3✔
1947
                targetCfg := routerCfg.BimodalConfig
3✔
1948
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1949
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1950
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1951
        }
1952

1953
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1954
}
1955

1956
// registerBlockConsumers registers the subsystems that consume block events.
1957
// By calling `RegisterQueue`, a list of subsystems are registered in the
1958
// blockbeat for block notifications. When a new block arrives, the subsystems
1959
// in the same queue are notified sequentially, and different queues are
1960
// notified concurrently.
1961
//
1962
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1963
// a new `RegisterQueue` call.
1964
func (s *server) registerBlockConsumers() {
3✔
1965
        // In this queue, when a new block arrives, it will be received and
3✔
1966
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1967
        consumers := []chainio.Consumer{
3✔
1968
                s.chainArb,
3✔
1969
                s.sweeper,
3✔
1970
                s.txPublisher,
3✔
1971
        }
3✔
1972
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1973
}
3✔
1974

1975
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1976
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1977
// may differ from what is on disk.
1978
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1979
        error) {
3✔
1980

3✔
1981
        data, err := u.DataToSign()
3✔
1982
        if err != nil {
3✔
1983
                return nil, err
×
1984
        }
×
1985

1986
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1987
}
1988

1989
// createLivenessMonitor creates a set of health checks using our configured
1990
// values and uses these checks to create a liveness monitor. Available
1991
// health checks,
1992
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1993
//   - diskCheck
1994
//   - tlsHealthCheck
1995
//   - torController, only created when tor is enabled.
1996
//
1997
// If a health check has been disabled by setting attempts to 0, our monitor
1998
// will not run it.
1999
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2000
        leaderElector cluster.LeaderElector) {
3✔
2001

3✔
2002
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2003
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2004
                srvrLog.Info("Disabling chain backend checks for " +
×
2005
                        "nochainbackend mode")
×
2006

×
2007
                chainBackendAttempts = 0
×
2008
        }
×
2009

2010
        chainHealthCheck := healthcheck.NewObservation(
3✔
2011
                "chain backend",
3✔
2012
                cc.HealthCheck,
3✔
2013
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2014
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2015
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2016
                chainBackendAttempts,
3✔
2017
        )
3✔
2018

3✔
2019
        diskCheck := healthcheck.NewObservation(
3✔
2020
                "disk space",
3✔
2021
                func() error {
3✔
2022
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2023
                                cfg.LndDir,
×
2024
                        )
×
2025
                        if err != nil {
×
2026
                                return err
×
2027
                        }
×
2028

2029
                        // If we have more free space than we require,
2030
                        // we return a nil error.
2031
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2032
                                return nil
×
2033
                        }
×
2034

2035
                        return fmt.Errorf("require: %v free space, got: %v",
×
2036
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2037
                                free)
×
2038
                },
2039
                cfg.HealthChecks.DiskCheck.Interval,
2040
                cfg.HealthChecks.DiskCheck.Timeout,
2041
                cfg.HealthChecks.DiskCheck.Backoff,
2042
                cfg.HealthChecks.DiskCheck.Attempts,
2043
        )
2044

2045
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2046
                "tls",
3✔
2047
                func() error {
3✔
2048
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2049
                                s.cc.KeyRing,
×
2050
                        )
×
2051
                        if err != nil {
×
2052
                                return err
×
2053
                        }
×
2054
                        if expired {
×
2055
                                return fmt.Errorf("TLS certificate is "+
×
2056
                                        "expired as of %v", expTime)
×
2057
                        }
×
2058

2059
                        // If the certificate is not outdated, no error needs
2060
                        // to be returned
2061
                        return nil
×
2062
                },
2063
                cfg.HealthChecks.TLSCheck.Interval,
2064
                cfg.HealthChecks.TLSCheck.Timeout,
2065
                cfg.HealthChecks.TLSCheck.Backoff,
2066
                cfg.HealthChecks.TLSCheck.Attempts,
2067
        )
2068

2069
        checks := []*healthcheck.Observation{
3✔
2070
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2071
        }
3✔
2072

3✔
2073
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2074
        if s.torController != nil {
3✔
2075
                torConnectionCheck := healthcheck.NewObservation(
×
2076
                        "tor connection",
×
2077
                        func() error {
×
2078
                                return healthcheck.CheckTorServiceStatus(
×
2079
                                        s.torController,
×
2080
                                        s.createNewHiddenService,
×
2081
                                )
×
2082
                        },
×
2083
                        cfg.HealthChecks.TorConnection.Interval,
2084
                        cfg.HealthChecks.TorConnection.Timeout,
2085
                        cfg.HealthChecks.TorConnection.Backoff,
2086
                        cfg.HealthChecks.TorConnection.Attempts,
2087
                )
2088
                checks = append(checks, torConnectionCheck)
×
2089
        }
2090

2091
        // If remote signing is enabled, add the healthcheck for the remote
2092
        // signing RPC interface.
2093
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2094
                // Because we have two cascading timeouts here, we need to add
3✔
2095
                // some slack to the "outer" one of them in case the "inner"
3✔
2096
                // returns exactly on time.
3✔
2097
                overhead := time.Millisecond * 10
3✔
2098

3✔
2099
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2100
                        "remote signer connection",
3✔
2101
                        rpcwallet.HealthCheck(
3✔
2102
                                s.cfg.RemoteSigner,
3✔
2103

3✔
2104
                                // For the health check we might to be even
3✔
2105
                                // stricter than the initial/normal connect, so
3✔
2106
                                // we use the health check timeout here.
3✔
2107
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2108
                        ),
3✔
2109
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2110
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2111
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2112
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2113
                )
3✔
2114
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2115
        }
3✔
2116

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

×
2135
                                leader, err := leaderElector.IsLeader(
×
2136
                                        timeoutCtx,
×
2137
                                )
×
2138
                                if err != nil {
×
2139
                                        return fmt.Errorf("unable to check if "+
×
2140
                                                "still leader: %v", err)
×
2141
                                }
×
2142

2143
                                if !leader {
×
2144
                                        srvrLog.Debug("Not the current leader")
×
2145
                                        return fmt.Errorf("not the current " +
×
2146
                                                "leader")
×
2147
                                }
×
2148

2149
                                return nil
×
2150
                        },
2151
                        cfg.HealthChecks.LeaderCheck.Interval,
2152
                        cfg.HealthChecks.LeaderCheck.Timeout,
2153
                        cfg.HealthChecks.LeaderCheck.Backoff,
2154
                        cfg.HealthChecks.LeaderCheck.Attempts,
2155
                )
2156

2157
                checks = append(checks, leaderCheck)
×
2158
        }
2159

2160
        // If we have not disabled all of our health checks, we create a
2161
        // liveness monitor with our configured checks.
2162
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2163
                &healthcheck.Config{
3✔
2164
                        Checks:   checks,
3✔
2165
                        Shutdown: srvrLog.Criticalf,
3✔
2166
                },
3✔
2167
        )
3✔
2168
}
2169

2170
// Started returns true if the server has been started, and false otherwise.
2171
// NOTE: This function is safe for concurrent access.
2172
func (s *server) Started() bool {
3✔
2173
        return atomic.LoadInt32(&s.active) != 0
3✔
2174
}
3✔
2175

2176
// cleaner is used to aggregate "cleanup" functions during an operation that
2177
// starts several subsystems. In case one of the subsystem fails to start
2178
// and a proper resource cleanup is required, the "run" method achieves this
2179
// by running all these added "cleanup" functions.
2180
type cleaner []func() error
2181

2182
// add is used to add a cleanup function to be called when
2183
// the run function is executed.
2184
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2185
        return append(c, cleanup)
3✔
2186
}
3✔
2187

2188
// run is used to run all the previousely added cleanup functions.
2189
func (c cleaner) run() {
×
2190
        for i := len(c) - 1; i >= 0; i-- {
×
2191
                if err := c[i](); err != nil {
×
2192
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2193
                }
×
2194
        }
2195
}
2196

2197
// startLowLevelServices starts the low-level services of the server. These
2198
// services must be started successfully before running the main server. The
2199
// services are,
2200
// 1. the chain notifier.
2201
//
2202
// TODO(yy): identify and add more low-level services here.
2203
func (s *server) startLowLevelServices() error {
3✔
2204
        var startErr error
3✔
2205

3✔
2206
        cleanup := cleaner{}
3✔
2207

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

2213
        if startErr != nil {
3✔
2214
                cleanup.run()
×
2215
        }
×
2216

2217
        return startErr
3✔
2218
}
2219

2220
// Start starts the main daemon server, all requested listeners, and any helper
2221
// goroutines.
2222
// NOTE: This function is safe for concurrent access.
2223
//
2224
//nolint:funlen
2225
func (s *server) Start(ctx context.Context) error {
3✔
2226
        // Get the current blockbeat.
3✔
2227
        beat, err := s.getStartingBeat()
3✔
2228
        if err != nil {
3✔
2229
                return err
×
2230
        }
×
2231

2232
        var startErr error
3✔
2233

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

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

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

2252
                if s.hostAnn != nil {
3✔
2253
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2254
                        if err := s.hostAnn.Start(); err != nil {
×
2255
                                startErr = err
×
2256
                                return
×
2257
                        }
×
2258
                }
2259

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

2268
                // Start the notification server. This is used so channel
2269
                // management goroutines can be notified when a funding
2270
                // transaction reaches a sufficient number of confirmations, or
2271
                // when the input for the funding transaction is spent in an
2272
                // attempt at an uncooperative close by the counterparty.
2273
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2274
                if err := s.sigPool.Start(); err != nil {
3✔
2275
                        startErr = err
×
2276
                        return
×
2277
                }
×
2278

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

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

2291
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2292
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2293
                        startErr = err
×
2294
                        return
×
2295
                }
×
2296

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

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

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

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

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

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

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

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

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

2355
                // htlcSwitch must be started before chainArb since the latter
2356
                // relies on htlcSwitch to deliver resolution message upon
2357
                // start.
2358
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2359
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2360
                        startErr = err
×
2361
                        return
×
2362
                }
×
2363

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

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

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

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

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

2394
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2395
                if err := s.chanRouter.Start(); err != nil {
3✔
2396
                        startErr = err
×
2397
                        return
×
2398
                }
×
2399
                // The authGossiper depends on the chanRouter and therefore
2400
                // should be started after it.
2401
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2402
                if err := s.authGossiper.Start(); err != nil {
3✔
2403
                        startErr = err
×
2404
                        return
×
2405
                }
×
2406

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

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

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

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

2431
                cleanup.add(func() error {
3✔
2432
                        s.missionController.StopStoreTickers()
×
2433
                        return nil
×
2434
                })
×
2435
                s.missionController.RunStoreTickers()
3✔
2436

3✔
2437
                // Before we start the connMgr, we'll check to see if we have
3✔
2438
                // any backups to recover. We do this now as we want to ensure
3✔
2439
                // that have all the information we need to handle channel
3✔
2440
                // recovery _before_ we even accept connections from any peers.
3✔
2441
                chanRestorer := &chanDBRestorer{
3✔
2442
                        db:         s.chanStateDB,
3✔
2443
                        secretKeys: s.cc.KeyRing,
3✔
2444
                        chainArb:   s.chainArb,
3✔
2445
                }
3✔
2446
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2447
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2448
                                s.chansToRestore.PackedSingleChanBackups,
×
2449
                                s.cc.KeyRing, chanRestorer, s,
×
2450
                        )
×
2451
                        if err != nil {
×
2452
                                startErr = fmt.Errorf("unable to unpack single "+
×
2453
                                        "backups: %v", err)
×
2454
                                return
×
2455
                        }
×
2456
                }
2457
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2458
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2459
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2460
                                s.cc.KeyRing, chanRestorer, s,
3✔
2461
                        )
3✔
2462
                        if err != nil {
3✔
2463
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2464
                                        "backup: %v", err)
×
2465
                                return
×
2466
                        }
×
2467
                }
2468

2469
                // chanSubSwapper must be started after the `channelNotifier`
2470
                // because it depends on channel events as a synchronization
2471
                // point.
2472
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2473
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2474
                        startErr = err
×
2475
                        return
×
2476
                }
×
2477

2478
                if s.torController != nil {
3✔
2479
                        cleanup = cleanup.add(s.torController.Stop)
×
2480
                        if err := s.createNewHiddenService(); err != nil {
×
2481
                                startErr = err
×
2482
                                return
×
2483
                        }
×
2484
                }
2485

2486
                if s.natTraversal != nil {
3✔
2487
                        s.wg.Add(1)
×
2488
                        go s.watchExternalIP()
×
2489
                }
×
2490

2491
                // Start connmgr last to prevent connections before init.
2492
                cleanup = cleanup.add(func() error {
3✔
2493
                        s.connMgr.Stop()
×
2494
                        return nil
×
2495
                })
×
2496

2497
                // RESOLVE: s.connMgr.Start() is called here, but
2498
                // brontide.NewListener() is called in newServer. This means
2499
                // that we are actually listening and partially accepting
2500
                // inbound connections even before the connMgr starts.
2501
                //
2502
                // TODO(yy): move the log into the connMgr's `Start` method.
2503
                srvrLog.Info("connMgr starting...")
3✔
2504
                s.connMgr.Start()
3✔
2505
                srvrLog.Debug("connMgr started")
3✔
2506

3✔
2507
                // If peers are specified as a config option, we'll add those
3✔
2508
                // peers first.
3✔
2509
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2510
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2511
                                peerAddrCfg,
3✔
2512
                        )
3✔
2513
                        if err != nil {
3✔
2514
                                startErr = fmt.Errorf("unable to parse peer "+
×
2515
                                        "pubkey from config: %v", err)
×
2516
                                return
×
2517
                        }
×
2518
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2519
                        if err != nil {
3✔
2520
                                startErr = fmt.Errorf("unable to parse peer "+
×
2521
                                        "address provided as a config option: "+
×
2522
                                        "%v", err)
×
2523
                                return
×
2524
                        }
×
2525

2526
                        peerAddr := &lnwire.NetAddress{
3✔
2527
                                IdentityKey: parsedPubkey,
3✔
2528
                                Address:     addr,
3✔
2529
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2530
                        }
3✔
2531

3✔
2532
                        err = s.ConnectToPeer(
3✔
2533
                                peerAddr, true,
3✔
2534
                                s.cfg.ConnectionTimeout,
3✔
2535
                        )
3✔
2536
                        if err != nil {
3✔
2537
                                startErr = fmt.Errorf("unable to connect to "+
×
2538
                                        "peer address provided as a config "+
×
2539
                                        "option: %v", err)
×
2540
                                return
×
2541
                        }
×
2542
                }
2543

2544
                // Subscribe to NodeAnnouncements that advertise new addresses
2545
                // our persistent peers.
2546
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2547
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2548
                                "addr: %v", err)
×
2549

×
2550
                        startErr = err
×
2551
                        return
×
2552
                }
×
2553

2554
                // With all the relevant sub-systems started, we'll now attempt
2555
                // to establish persistent connections to our direct channel
2556
                // collaborators within the network. Before doing so however,
2557
                // we'll prune our set of link nodes found within the database
2558
                // to ensure we don't reconnect to any nodes we no longer have
2559
                // open channels with.
2560
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2561
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2562

×
2563
                        startErr = err
×
2564
                        return
×
2565
                }
×
2566

2567
                if err := s.establishPersistentConnections(); err != nil {
3✔
2568
                        srvrLog.Errorf("Failed to establish persistent "+
×
2569
                                "connections: %v", err)
×
2570
                }
×
2571

2572
                // setSeedList is a helper function that turns multiple DNS seed
2573
                // server tuples from the command line or config file into the
2574
                // data structure we need and does a basic formal sanity check
2575
                // in the process.
2576
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2577
                        if len(tuples) == 0 {
×
2578
                                return
×
2579
                        }
×
2580

2581
                        result := make([][2]string, len(tuples))
×
2582
                        for idx, tuple := range tuples {
×
2583
                                tuple = strings.TrimSpace(tuple)
×
2584
                                if len(tuple) == 0 {
×
2585
                                        return
×
2586
                                }
×
2587

2588
                                servers := strings.Split(tuple, ",")
×
2589
                                if len(servers) > 2 || len(servers) == 0 {
×
2590
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2591
                                                "seed tuple: %v", servers)
×
2592
                                        return
×
2593
                                }
×
2594

2595
                                copy(result[idx][:], servers)
×
2596
                        }
2597

2598
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2599
                }
2600

2601
                // Let users overwrite the DNS seed nodes. We only allow them
2602
                // for bitcoin mainnet/testnet/signet.
2603
                if s.cfg.Bitcoin.MainNet {
3✔
2604
                        setSeedList(
×
2605
                                s.cfg.Bitcoin.DNSSeeds,
×
2606
                                chainreg.BitcoinMainnetGenesis,
×
2607
                        )
×
2608
                }
×
2609
                if s.cfg.Bitcoin.TestNet3 {
3✔
2610
                        setSeedList(
×
2611
                                s.cfg.Bitcoin.DNSSeeds,
×
2612
                                chainreg.BitcoinTestnetGenesis,
×
2613
                        )
×
2614
                }
×
2615
                if s.cfg.Bitcoin.TestNet4 {
3✔
2616
                        setSeedList(
×
2617
                                s.cfg.Bitcoin.DNSSeeds,
×
2618
                                chainreg.BitcoinTestnet4Genesis,
×
2619
                        )
×
2620
                }
×
2621
                if s.cfg.Bitcoin.SigNet {
3✔
2622
                        setSeedList(
×
2623
                                s.cfg.Bitcoin.DNSSeeds,
×
2624
                                chainreg.BitcoinSignetGenesis,
×
2625
                        )
×
2626
                }
×
2627

2628
                // If network bootstrapping hasn't been disabled, then we'll
2629
                // configure the set of active bootstrappers, and launch a
2630
                // dedicated goroutine to maintain a set of persistent
2631
                // connections.
2632
                if shouldPeerBootstrap(s.cfg) {
3✔
2633
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2634
                        if err != nil {
×
2635
                                startErr = err
×
2636
                                return
×
2637
                        }
×
2638

2639
                        s.wg.Add(1)
×
2640
                        go s.peerBootstrapper(
×
2641
                                ctx, defaultMinPeers, bootstrappers,
×
2642
                        )
×
2643
                } else {
3✔
2644
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2645
                }
3✔
2646

2647
                // Start the blockbeat after all other subsystems have been
2648
                // started so they are ready to receive new blocks.
2649
                cleanup = cleanup.add(func() error {
3✔
2650
                        s.blockbeatDispatcher.Stop()
×
2651
                        return nil
×
2652
                })
×
2653
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2654
                        startErr = err
×
2655
                        return
×
2656
                }
×
2657

2658
                // Set the active flag now that we've completed the full
2659
                // startup.
2660
                atomic.StoreInt32(&s.active, 1)
3✔
2661
        })
2662

2663
        if startErr != nil {
3✔
2664
                cleanup.run()
×
2665
        }
×
2666
        return startErr
3✔
2667
}
2668

2669
// Stop gracefully shutsdown the main daemon server. This function will signal
2670
// any active goroutines, or helper objects to exit, then blocks until they've
2671
// all successfully exited. Additionally, any/all listeners are closed.
2672
// NOTE: This function is safe for concurrent access.
2673
func (s *server) Stop() error {
3✔
2674
        s.stop.Do(func() {
6✔
2675
                atomic.StoreInt32(&s.stopping, 1)
3✔
2676

3✔
2677
                close(s.quit)
3✔
2678

3✔
2679
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2680
                s.connMgr.Stop()
3✔
2681

3✔
2682
                // Stop dispatching blocks to other systems immediately.
3✔
2683
                s.blockbeatDispatcher.Stop()
3✔
2684

3✔
2685
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2686
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2688
                }
×
2689
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2691
                }
×
2692
                if err := s.sphinx.Stop(); err != nil {
3✔
2693
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2694
                }
×
2695
                if err := s.invoices.Stop(); err != nil {
3✔
2696
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2697
                }
×
2698
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2699
                        srvrLog.Warnf("failed to stop interceptable "+
×
2700
                                "switch: %v", err)
×
2701
                }
×
2702
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2703
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2704
                                "modifier: %v", err)
×
2705
                }
×
2706
                if err := s.chanRouter.Stop(); err != nil {
3✔
2707
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2708
                }
×
2709
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2710
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2711
                }
×
2712
                if err := s.graphDB.Stop(); err != nil {
3✔
2713
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2714
                }
×
2715
                if err := s.chainArb.Stop(); err != nil {
3✔
2716
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2717
                }
×
2718
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2719
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2720
                }
×
2721
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2722
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2723
                                err)
×
2724
                }
×
2725
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2726
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2727
                }
×
2728
                if err := s.authGossiper.Stop(); err != nil {
3✔
2729
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2730
                }
×
2731
                if err := s.sweeper.Stop(); err != nil {
3✔
2732
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2733
                }
×
2734
                if err := s.txPublisher.Stop(); err != nil {
3✔
2735
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2736
                }
×
2737
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2738
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2739
                }
×
2740
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2741
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2742
                }
×
2743
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2744
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2745
                }
×
2746

2747
                // Update channel.backup file. Make sure to do it before
2748
                // stopping chanSubSwapper.
2749
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2750
                        s.chanStateDB, s.addrSource,
3✔
2751
                )
3✔
2752
                if err != nil {
3✔
2753
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2754
                                err)
×
2755
                } else {
3✔
2756
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2757
                        if err != nil {
6✔
2758
                                srvrLog.Warnf("Manual update of channel "+
3✔
2759
                                        "backup failed: %v", err)
3✔
2760
                        }
3✔
2761
                }
2762

2763
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2764
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2765
                }
×
2766
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2767
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2768
                }
×
2769
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2770
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2771
                                err)
×
2772
                }
×
2773
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2774
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2775
                                err)
×
2776
                }
×
2777
                s.missionController.StopStoreTickers()
3✔
2778

3✔
2779
                // Disconnect from each active peers to ensure that
3✔
2780
                // peerTerminationWatchers signal completion to each peer.
3✔
2781
                for _, peer := range s.Peers() {
6✔
2782
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2783
                        if err != nil {
3✔
2784
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2785
                                        "received error: %v", peer.IdentityKey(),
×
2786
                                        err,
×
2787
                                )
×
2788
                        }
×
2789
                }
2790

2791
                // Now that all connections have been torn down, stop the tower
2792
                // client which will reliably flush all queued states to the
2793
                // tower. If this is halted for any reason, the force quit timer
2794
                // will kick in and abort to allow this method to return.
2795
                if s.towerClientMgr != nil {
6✔
2796
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2797
                                srvrLog.Warnf("Unable to shut down tower "+
×
2798
                                        "client manager: %v", err)
×
2799
                        }
×
2800
                }
2801

2802
                if s.hostAnn != nil {
3✔
2803
                        if err := s.hostAnn.Stop(); err != nil {
×
2804
                                srvrLog.Warnf("unable to shut down host "+
×
2805
                                        "annoucner: %v", err)
×
2806
                        }
×
2807
                }
2808

2809
                if s.livenessMonitor != nil {
6✔
2810
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2811
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2812
                                        "monitor: %v", err)
×
2813
                        }
×
2814
                }
2815

2816
                // Wait for all lingering goroutines to quit.
2817
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2818
                s.wg.Wait()
3✔
2819

3✔
2820
                srvrLog.Debug("Stopping buffer pools...")
3✔
2821
                s.sigPool.Stop()
3✔
2822
                s.writePool.Stop()
3✔
2823
                s.readPool.Stop()
3✔
2824
        })
2825

2826
        return nil
3✔
2827
}
2828

2829
// Stopped returns true if the server has been instructed to shutdown.
2830
// NOTE: This function is safe for concurrent access.
2831
func (s *server) Stopped() bool {
3✔
2832
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2833
}
3✔
2834

2835
// configurePortForwarding attempts to set up port forwarding for the different
2836
// ports that the server will be listening on.
2837
//
2838
// NOTE: This should only be used when using some kind of NAT traversal to
2839
// automatically set up forwarding rules.
2840
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2841
        ip, err := s.natTraversal.ExternalIP()
×
2842
        if err != nil {
×
2843
                return nil, err
×
2844
        }
×
2845
        s.lastDetectedIP = ip
×
2846

×
2847
        externalIPs := make([]string, 0, len(ports))
×
2848
        for _, port := range ports {
×
2849
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2850
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2851
                        continue
×
2852
                }
2853

2854
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2855
                externalIPs = append(externalIPs, hostIP)
×
2856
        }
2857

2858
        return externalIPs, nil
×
2859
}
2860

2861
// removePortForwarding attempts to clear the forwarding rules for the different
2862
// ports the server is currently listening on.
2863
//
2864
// NOTE: This should only be used when using some kind of NAT traversal to
2865
// automatically set up forwarding rules.
2866
func (s *server) removePortForwarding() {
×
2867
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2868
        for _, port := range forwardedPorts {
×
2869
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2870
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2871
                                "port %d: %v", port, err)
×
2872
                }
×
2873
        }
2874
}
2875

2876
// watchExternalIP continuously checks for an updated external IP address every
2877
// 15 minutes. Once a new IP address has been detected, it will automatically
2878
// handle port forwarding rules and send updated node announcements to the
2879
// currently connected peers.
2880
//
2881
// NOTE: This MUST be run as a goroutine.
2882
func (s *server) watchExternalIP() {
×
2883
        defer s.wg.Done()
×
2884

×
2885
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2886
        // up by the server.
×
2887
        defer s.removePortForwarding()
×
2888

×
2889
        // Keep track of the external IPs set by the user to avoid replacing
×
2890
        // them when detecting a new IP.
×
2891
        ipsSetByUser := make(map[string]struct{})
×
2892
        for _, ip := range s.cfg.ExternalIPs {
×
2893
                ipsSetByUser[ip.String()] = struct{}{}
×
2894
        }
×
2895

2896
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2897

×
2898
        ticker := time.NewTicker(15 * time.Minute)
×
2899
        defer ticker.Stop()
×
2900
out:
×
2901
        for {
×
2902
                select {
×
2903
                case <-ticker.C:
×
2904
                        // We'll start off by making sure a new IP address has
×
2905
                        // been detected.
×
2906
                        ip, err := s.natTraversal.ExternalIP()
×
2907
                        if err != nil {
×
2908
                                srvrLog.Debugf("Unable to retrieve the "+
×
2909
                                        "external IP address: %v", err)
×
2910
                                continue
×
2911
                        }
2912

2913
                        // Periodically renew the NAT port forwarding.
2914
                        for _, port := range forwardedPorts {
×
2915
                                err := s.natTraversal.AddPortMapping(port)
×
2916
                                if err != nil {
×
2917
                                        srvrLog.Warnf("Unable to automatically "+
×
2918
                                                "re-create port forwarding using %s: %v",
×
2919
                                                s.natTraversal.Name(), err)
×
2920
                                } else {
×
2921
                                        srvrLog.Debugf("Automatically re-created "+
×
2922
                                                "forwarding for port %d using %s to "+
×
2923
                                                "advertise external IP",
×
2924
                                                port, s.natTraversal.Name())
×
2925
                                }
×
2926
                        }
2927

2928
                        if ip.Equal(s.lastDetectedIP) {
×
2929
                                continue
×
2930
                        }
2931

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

×
2934
                        // Next, we'll craft the new addresses that will be
×
2935
                        // included in the new node announcement and advertised
×
2936
                        // to the network. Each address will consist of the new
×
2937
                        // IP detected and one of the currently advertised
×
2938
                        // ports.
×
2939
                        var newAddrs []net.Addr
×
2940
                        for _, port := range forwardedPorts {
×
2941
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2942
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2943
                                if err != nil {
×
2944
                                        srvrLog.Debugf("Unable to resolve "+
×
2945
                                                "host %v: %v", addr, err)
×
2946
                                        continue
×
2947
                                }
2948

2949
                                newAddrs = append(newAddrs, addr)
×
2950
                        }
2951

2952
                        // Skip the update if we weren't able to resolve any of
2953
                        // the new addresses.
2954
                        if len(newAddrs) == 0 {
×
2955
                                srvrLog.Debug("Skipping node announcement " +
×
2956
                                        "update due to not being able to " +
×
2957
                                        "resolve any new addresses")
×
2958
                                continue
×
2959
                        }
2960

2961
                        // Now, we'll need to update the addresses in our node's
2962
                        // announcement in order to propagate the update
2963
                        // throughout the network. We'll only include addresses
2964
                        // that have a different IP from the previous one, as
2965
                        // the previous IP is no longer valid.
2966
                        currentNodeAnn := s.getNodeAnnouncement()
×
2967

×
2968
                        for _, addr := range currentNodeAnn.Addresses {
×
2969
                                host, _, err := net.SplitHostPort(addr.String())
×
2970
                                if err != nil {
×
2971
                                        srvrLog.Debugf("Unable to determine "+
×
2972
                                                "host from address %v: %v",
×
2973
                                                addr, err)
×
2974
                                        continue
×
2975
                                }
2976

2977
                                // We'll also make sure to include external IPs
2978
                                // set manually by the user.
2979
                                _, setByUser := ipsSetByUser[addr.String()]
×
2980
                                if setByUser || host != s.lastDetectedIP.String() {
×
2981
                                        newAddrs = append(newAddrs, addr)
×
2982
                                }
×
2983
                        }
2984

2985
                        // Then, we'll generate a new timestamped node
2986
                        // announcement with the updated addresses and broadcast
2987
                        // it to our peers.
2988
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2989
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2990
                        )
×
2991
                        if err != nil {
×
2992
                                srvrLog.Debugf("Unable to generate new node "+
×
2993
                                        "announcement: %v", err)
×
2994
                                continue
×
2995
                        }
2996

2997
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2998
                        if err != nil {
×
2999
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3000
                                        "announcement to peers: %v", err)
×
3001
                                continue
×
3002
                        }
3003

3004
                        // Finally, update the last IP seen to the current one.
3005
                        s.lastDetectedIP = ip
×
3006
                case <-s.quit:
×
3007
                        break out
×
3008
                }
3009
        }
3010
}
3011

3012
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3013
// based on the server, and currently active bootstrap mechanisms as defined
3014
// within the current configuration.
3015
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3016
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3017

×
3018
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3019

×
3020
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3021
        // this can be used by default if we've already partially seeded the
×
3022
        // network.
×
3023
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3024
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3025
        if err != nil {
×
3026
                return nil, err
×
3027
        }
×
3028
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3029

×
3030
        // If this isn't simnet mode, then one of our additional bootstrapping
×
3031
        // sources will be the set of running DNS seeds.
×
3032
        if !s.cfg.Bitcoin.SimNet {
×
3033
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3034

×
3035
                // If we have a set of DNS seeds for this chain, then we'll add
×
3036
                // it as an additional bootstrapping source.
×
3037
                if ok {
×
3038
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3039
                                "seeds: %v", dnsSeeds)
×
3040

×
3041
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3042
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3043
                        )
×
3044
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3045
                }
×
3046
        }
3047

3048
        return bootStrappers, nil
×
3049
}
3050

3051
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3052
// needs to ignore, which is made of three parts,
3053
//   - the node itself needs to be skipped as it doesn't make sense to connect
3054
//     to itself.
3055
//   - the peers that already have connections with, as in s.peersByPub.
3056
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3057
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3058
        s.mu.RLock()
×
3059
        defer s.mu.RUnlock()
×
3060

×
3061
        ignore := make(map[autopilot.NodeID]struct{})
×
3062

×
3063
        // We should ignore ourselves from bootstrapping.
×
3064
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3065
        ignore[selfKey] = struct{}{}
×
3066

×
3067
        // Ignore all connected peers.
×
3068
        for _, peer := range s.peersByPub {
×
3069
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3070
                ignore[nID] = struct{}{}
×
3071
        }
×
3072

3073
        // Ignore all persistent peers as they have a dedicated reconnecting
3074
        // process.
3075
        for pubKeyStr := range s.persistentPeers {
×
3076
                var nID autopilot.NodeID
×
3077
                copy(nID[:], []byte(pubKeyStr))
×
3078
                ignore[nID] = struct{}{}
×
3079
        }
×
3080

3081
        return ignore
×
3082
}
3083

3084
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3085
// and maintain a target minimum number of outbound connections. With this
3086
// invariant, we ensure that our node is connected to a diverse set of peers
3087
// and that nodes newly joining the network receive an up to date network view
3088
// as soon as possible.
3089
func (s *server) peerBootstrapper(ctx context.Context, numTargetPeers uint32,
3090
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3091

×
3092
        defer s.wg.Done()
×
3093

×
3094
        // Before we continue, init the ignore peers map.
×
3095
        ignoreList := s.createBootstrapIgnorePeers()
×
3096

×
3097
        // We'll start off by aggressively attempting connections to peers in
×
3098
        // order to be a part of the network as soon as possible.
×
3099
        s.initialPeerBootstrap(ctx, ignoreList, numTargetPeers, bootstrappers)
×
3100

×
3101
        // Once done, we'll attempt to maintain our target minimum number of
×
3102
        // peers.
×
3103
        //
×
3104
        // We'll use a 15 second backoff, and double the time every time an
×
3105
        // epoch fails up to a ceiling.
×
3106
        backOff := time.Second * 15
×
3107

×
3108
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3109
        // see if we've reached our minimum number of peers.
×
3110
        sampleTicker := time.NewTicker(backOff)
×
3111
        defer sampleTicker.Stop()
×
3112

×
3113
        // We'll use the number of attempts and errors to determine if we need
×
3114
        // to increase the time between discovery epochs.
×
3115
        var epochErrors uint32 // To be used atomically.
×
3116
        var epochAttempts uint32
×
3117

×
3118
        for {
×
3119
                select {
×
3120
                // The ticker has just woken us up, so we'll need to check if
3121
                // we need to attempt to connect our to any more peers.
3122
                case <-sampleTicker.C:
×
3123
                        // Obtain the current number of peers, so we can gauge
×
3124
                        // if we need to sample more peers or not.
×
3125
                        s.mu.RLock()
×
3126
                        numActivePeers := uint32(len(s.peersByPub))
×
3127
                        s.mu.RUnlock()
×
3128

×
3129
                        // If we have enough peers, then we can loop back
×
3130
                        // around to the next round as we're done here.
×
3131
                        if numActivePeers >= numTargetPeers {
×
3132
                                continue
×
3133
                        }
3134

3135
                        // If all of our attempts failed during this last back
3136
                        // off period, then will increase our backoff to 5
3137
                        // minute ceiling to avoid an excessive number of
3138
                        // queries
3139
                        //
3140
                        // TODO(roasbeef): add reverse policy too?
3141

3142
                        if epochAttempts > 0 &&
×
3143
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3144

×
3145
                                sampleTicker.Stop()
×
3146

×
3147
                                backOff *= 2
×
3148
                                if backOff > bootstrapBackOffCeiling {
×
3149
                                        backOff = bootstrapBackOffCeiling
×
3150
                                }
×
3151

3152
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3153
                                        "%v", backOff)
×
3154
                                sampleTicker = time.NewTicker(backOff)
×
3155
                                continue
×
3156
                        }
3157

3158
                        atomic.StoreUint32(&epochErrors, 0)
×
3159
                        epochAttempts = 0
×
3160

×
3161
                        // Since we know need more peers, we'll compute the
×
3162
                        // exact number we need to reach our threshold.
×
3163
                        numNeeded := numTargetPeers - numActivePeers
×
3164

×
3165
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3166
                                "peers", numNeeded)
×
3167

×
3168
                        // With the number of peers we need calculated, we'll
×
3169
                        // query the network bootstrappers to sample a set of
×
3170
                        // random addrs for us.
×
3171
                        //
×
3172
                        // Before we continue, get a copy of the ignore peers
×
3173
                        // map.
×
3174
                        ignoreList = s.createBootstrapIgnorePeers()
×
3175

×
3176
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3177
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3178
                        )
×
3179
                        if err != nil {
×
3180
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3181
                                        "peers: %v", err)
×
3182
                                continue
×
3183
                        }
3184

3185
                        // Finally, we'll launch a new goroutine for each
3186
                        // prospective peer candidates.
3187
                        for _, addr := range peerAddrs {
×
3188
                                epochAttempts++
×
3189

×
3190
                                go func(a *lnwire.NetAddress) {
×
3191
                                        // TODO(roasbeef): can do AS, subnet,
×
3192
                                        // country diversity, etc
×
3193
                                        errChan := make(chan error, 1)
×
3194
                                        s.connectToPeer(
×
3195
                                                a, errChan,
×
3196
                                                s.cfg.ConnectionTimeout,
×
3197
                                        )
×
3198
                                        select {
×
3199
                                        case err := <-errChan:
×
3200
                                                if err == nil {
×
3201
                                                        return
×
3202
                                                }
×
3203

3204
                                                srvrLog.Errorf("Unable to "+
×
3205
                                                        "connect to %v: %v",
×
3206
                                                        a, err)
×
3207
                                                atomic.AddUint32(&epochErrors, 1)
×
3208
                                        case <-s.quit:
×
3209
                                        }
3210
                                }(addr)
3211
                        }
3212
                case <-s.quit:
×
3213
                        return
×
3214
                }
3215
        }
3216
}
3217

3218
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3219
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3220
// query back off each time we encounter a failure.
3221
const bootstrapBackOffCeiling = time.Minute * 5
3222

3223
// initialPeerBootstrap attempts to continuously connect to peers on startup
3224
// until the target number of peers has been reached. This ensures that nodes
3225
// receive an up to date network view as soon as possible.
3226
func (s *server) initialPeerBootstrap(ctx context.Context,
3227
        ignore map[autopilot.NodeID]struct{}, numTargetPeers uint32,
3228
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3229

×
3230
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3231
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3232

×
3233
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3234
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3235
        var delaySignal <-chan time.Time
×
3236
        delayTime := time.Second * 2
×
3237

×
3238
        // As want to be more aggressive, we'll use a lower back off celling
×
3239
        // then the main peer bootstrap logic.
×
3240
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3241

×
3242
        for attempts := 0; ; attempts++ {
×
3243
                // Check if the server has been requested to shut down in order
×
3244
                // to prevent blocking.
×
3245
                if s.Stopped() {
×
3246
                        return
×
3247
                }
×
3248

3249
                // We can exit our aggressive initial peer bootstrapping stage
3250
                // if we've reached out target number of peers.
3251
                s.mu.RLock()
×
3252
                numActivePeers := uint32(len(s.peersByPub))
×
3253
                s.mu.RUnlock()
×
3254

×
3255
                if numActivePeers >= numTargetPeers {
×
3256
                        return
×
3257
                }
×
3258

3259
                if attempts > 0 {
×
3260
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3261
                                "bootstrap peers (attempt #%v)", delayTime,
×
3262
                                attempts)
×
3263

×
3264
                        // We've completed at least one iterating and haven't
×
3265
                        // finished, so we'll start to insert a delay period
×
3266
                        // between each attempt.
×
3267
                        delaySignal = time.After(delayTime)
×
3268
                        select {
×
3269
                        case <-delaySignal:
×
3270
                        case <-s.quit:
×
3271
                                return
×
3272
                        }
3273

3274
                        // After our delay, we'll double the time we wait up to
3275
                        // the max back off period.
3276
                        delayTime *= 2
×
3277
                        if delayTime > backOffCeiling {
×
3278
                                delayTime = backOffCeiling
×
3279
                        }
×
3280
                }
3281

3282
                // Otherwise, we'll request for the remaining number of peers
3283
                // in order to reach our target.
3284
                peersNeeded := numTargetPeers - numActivePeers
×
3285
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3286
                        ctx, ignore, peersNeeded, bootstrappers...,
×
3287
                )
×
3288
                if err != nil {
×
3289
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3290
                                "peers: %v", err)
×
3291
                        continue
×
3292
                }
3293

3294
                // Then, we'll attempt to establish a connection to the
3295
                // different peer addresses retrieved by our bootstrappers.
3296
                var wg sync.WaitGroup
×
3297
                for _, bootstrapAddr := range bootstrapAddrs {
×
3298
                        wg.Add(1)
×
3299
                        go func(addr *lnwire.NetAddress) {
×
3300
                                defer wg.Done()
×
3301

×
3302
                                errChan := make(chan error, 1)
×
3303
                                go s.connectToPeer(
×
3304
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3305
                                )
×
3306

×
3307
                                // We'll only allow this connection attempt to
×
3308
                                // take up to 3 seconds. This allows us to move
×
3309
                                // quickly by discarding peers that are slowing
×
3310
                                // us down.
×
3311
                                select {
×
3312
                                case err := <-errChan:
×
3313
                                        if err == nil {
×
3314
                                                return
×
3315
                                        }
×
3316
                                        srvrLog.Errorf("Unable to connect to "+
×
3317
                                                "%v: %v", addr, err)
×
3318
                                // TODO: tune timeout? 3 seconds might be *too*
3319
                                // aggressive but works well.
3320
                                case <-time.After(3 * time.Second):
×
3321
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3322
                                                "to not establishing a "+
×
3323
                                                "connection within 3 seconds",
×
3324
                                                addr)
×
3325
                                case <-s.quit:
×
3326
                                }
3327
                        }(bootstrapAddr)
3328
                }
3329

3330
                wg.Wait()
×
3331
        }
3332
}
3333

3334
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3335
// order to listen for inbound connections over Tor.
3336
func (s *server) createNewHiddenService() error {
×
3337
        // Determine the different ports the server is listening on. The onion
×
3338
        // service's virtual port will map to these ports and one will be picked
×
3339
        // at random when the onion service is being accessed.
×
3340
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3341
        for _, listenAddr := range s.listenAddrs {
×
3342
                port := listenAddr.(*net.TCPAddr).Port
×
3343
                listenPorts = append(listenPorts, port)
×
3344
        }
×
3345

3346
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3347
        if err != nil {
×
3348
                return err
×
3349
        }
×
3350

3351
        // Once the port mapping has been set, we can go ahead and automatically
3352
        // create our onion service. The service's private key will be saved to
3353
        // disk in order to regain access to this service when restarting `lnd`.
3354
        onionCfg := tor.AddOnionConfig{
×
3355
                VirtualPort: defaultPeerPort,
×
3356
                TargetPorts: listenPorts,
×
3357
                Store: tor.NewOnionFile(
×
3358
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3359
                        encrypter,
×
3360
                ),
×
3361
        }
×
3362

×
3363
        switch {
×
3364
        case s.cfg.Tor.V2:
×
3365
                onionCfg.Type = tor.V2
×
3366
        case s.cfg.Tor.V3:
×
3367
                onionCfg.Type = tor.V3
×
3368
        }
3369

3370
        addr, err := s.torController.AddOnion(onionCfg)
×
3371
        if err != nil {
×
3372
                return err
×
3373
        }
×
3374

3375
        // Now that the onion service has been created, we'll add the onion
3376
        // address it can be reached at to our list of advertised addresses.
3377
        newNodeAnn, err := s.genNodeAnnouncement(
×
3378
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3379
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3380
                },
×
3381
        )
3382
        if err != nil {
×
3383
                return fmt.Errorf("unable to generate new node "+
×
3384
                        "announcement: %v", err)
×
3385
        }
×
3386

3387
        // Finally, we'll update the on-disk version of our announcement so it
3388
        // will eventually propagate to nodes in the network.
3389
        selfNode := &models.LightningNode{
×
3390
                HaveNodeAnnouncement: true,
×
3391
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3392
                Addresses:            newNodeAnn.Addresses,
×
3393
                Alias:                newNodeAnn.Alias.String(),
×
3394
                Features: lnwire.NewFeatureVector(
×
3395
                        newNodeAnn.Features, lnwire.Features,
×
3396
                ),
×
3397
                Color:        newNodeAnn.RGBColor,
×
3398
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3399
        }
×
3400
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3401
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3402
                return fmt.Errorf("can't set self node: %w", err)
×
3403
        }
×
3404

3405
        return nil
×
3406
}
3407

3408
// findChannel finds a channel given a public key and ChannelID. It is an
3409
// optimization that is quicker than seeking for a channel given only the
3410
// ChannelID.
3411
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3412
        *channeldb.OpenChannel, error) {
3✔
3413

3✔
3414
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3415
        if err != nil {
3✔
3416
                return nil, err
×
3417
        }
×
3418

3419
        for _, channel := range nodeChans {
6✔
3420
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3421
                        return channel, nil
3✔
3422
                }
3✔
3423
        }
3424

3425
        return nil, fmt.Errorf("unable to find channel")
3✔
3426
}
3427

3428
// getNodeAnnouncement fetches the current, fully signed node announcement.
3429
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3430
        s.mu.Lock()
3✔
3431
        defer s.mu.Unlock()
3✔
3432

3✔
3433
        return *s.currentNodeAnn
3✔
3434
}
3✔
3435

3436
// genNodeAnnouncement generates and returns the current fully signed node
3437
// announcement. The time stamp of the announcement will be updated in order
3438
// to ensure it propagates through the network.
3439
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3440
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3441

3✔
3442
        s.mu.Lock()
3✔
3443
        defer s.mu.Unlock()
3✔
3444

3✔
3445
        // First, try to update our feature manager with the updated set of
3✔
3446
        // features.
3✔
3447
        if features != nil {
6✔
3448
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3449
                        feature.SetNodeAnn: features,
3✔
3450
                }
3✔
3451
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3452
                if err != nil {
6✔
3453
                        return lnwire.NodeAnnouncement{}, err
3✔
3454
                }
3✔
3455

3456
                // If we could successfully update our feature manager, add
3457
                // an update modifier to include these new features to our
3458
                // set.
3459
                modifiers = append(
3✔
3460
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3461
                )
3✔
3462
        }
3463

3464
        // Always update the timestamp when refreshing to ensure the update
3465
        // propagates.
3466
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3467

3✔
3468
        // Apply the requested changes to the node announcement.
3✔
3469
        for _, modifier := range modifiers {
6✔
3470
                modifier(s.currentNodeAnn)
3✔
3471
        }
3✔
3472

3473
        // Sign a new update after applying all of the passed modifiers.
3474
        err := netann.SignNodeAnnouncement(
3✔
3475
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3476
        )
3✔
3477
        if err != nil {
3✔
3478
                return lnwire.NodeAnnouncement{}, err
×
3479
        }
×
3480

3481
        return *s.currentNodeAnn, nil
3✔
3482
}
3483

3484
// updateAndBroadcastSelfNode generates a new node announcement
3485
// applying the giving modifiers and updating the time stamp
3486
// to ensure it propagates through the network. Then it broadcasts
3487
// it to the network.
3488
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3489
        modifiers ...netann.NodeAnnModifier) error {
3✔
3490

3✔
3491
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3492
        if err != nil {
6✔
3493
                return fmt.Errorf("unable to generate new node "+
3✔
3494
                        "announcement: %v", err)
3✔
3495
        }
3✔
3496

3497
        // Update the on-disk version of our announcement.
3498
        // Load and modify self node istead of creating anew instance so we
3499
        // don't risk overwriting any existing values.
3500
        selfNode, err := s.graphDB.SourceNode()
3✔
3501
        if err != nil {
3✔
3502
                return fmt.Errorf("unable to get current source node: %w", err)
×
3503
        }
×
3504

3505
        selfNode.HaveNodeAnnouncement = true
3✔
3506
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3507
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3508
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3509
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3510
        selfNode.Color = newNodeAnn.RGBColor
3✔
3511
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3512

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

3✔
3515
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3✔
3516
                return fmt.Errorf("can't set self node: %w", err)
×
3517
        }
×
3518

3519
        // Finally, propagate it to the nodes in the network.
3520
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3521
        if err != nil {
3✔
3522
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3523
                        "announcement to peers: %v", err)
×
3524
                return err
×
3525
        }
×
3526

3527
        return nil
3✔
3528
}
3529

3530
type nodeAddresses struct {
3531
        pubKey    *btcec.PublicKey
3532
        addresses []net.Addr
3533
}
3534

3535
// establishPersistentConnections attempts to establish persistent connections
3536
// to all our direct channel collaborators. In order to promote liveness of our
3537
// active channels, we instruct the connection manager to attempt to establish
3538
// and maintain persistent connections to all our direct channel counterparties.
3539
func (s *server) establishPersistentConnections() error {
3✔
3540
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3541
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3542
        // since other PubKey forms can't be compared.
3✔
3543
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3544

3✔
3545
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3546
        // attempt to connect to based on our set of previous connections. Set
3✔
3547
        // the reconnection port to the default peer port.
3✔
3548
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3549
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3550
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3551
        }
×
3552

3553
        for _, node := range linkNodes {
6✔
3554
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3555
                nodeAddrs := &nodeAddresses{
3✔
3556
                        pubKey:    node.IdentityPub,
3✔
3557
                        addresses: node.Addresses,
3✔
3558
                }
3✔
3559
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3560
        }
3✔
3561

3562
        // After checking our previous connections for addresses to connect to,
3563
        // iterate through the nodes in our channel graph to find addresses
3564
        // that have been added via NodeAnnouncement messages.
3565
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3566
        // each of the nodes.
3567
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3568
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3569

3✔
3570
                // If the remote party has announced the channel to us, but we
3✔
3571
                // haven't yet, then we won't have a policy. However, we don't
3✔
3572
                // need this to connect to the peer, so we'll log it and move on.
3✔
3573
                if !havePolicy {
3✔
3574
                        srvrLog.Warnf("No channel policy found for "+
×
3575
                                "ChannelPoint(%v): ", chanPoint)
×
3576
                }
×
3577

3578
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3579

3✔
3580
                // Add all unique addresses from channel
3✔
3581
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3582
                // connect to for this peer.
3✔
3583
                addrSet := make(map[string]net.Addr)
3✔
3584
                for _, addr := range channelPeer.Addresses {
6✔
3585
                        switch addr.(type) {
3✔
3586
                        case *net.TCPAddr:
3✔
3587
                                addrSet[addr.String()] = addr
3✔
3588

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

3598
                // If this peer is also recorded as a link node, we'll add any
3599
                // additional addresses that have not already been selected.
3600
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3601
                if ok {
6✔
3602
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3603
                                switch lnAddress.(type) {
3✔
3604
                                case *net.TCPAddr:
3✔
3605
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3606

3607
                                // We'll only attempt to connect to Tor
3608
                                // addresses if Tor outbound support is enabled.
3609
                                case *tor.OnionAddr:
×
3610
                                        if s.cfg.Tor.Active {
×
3611
                                                addrSet[lnAddress.String()] = lnAddress
×
3612
                                        }
×
3613
                                }
3614
                        }
3615
                }
3616

3617
                // Construct a slice of the deduped addresses.
3618
                var addrs []net.Addr
3✔
3619
                for _, addr := range addrSet {
6✔
3620
                        addrs = append(addrs, addr)
3✔
3621
                }
3✔
3622

3623
                n := &nodeAddresses{
3✔
3624
                        addresses: addrs,
3✔
3625
                }
3✔
3626
                n.pubKey, err = channelPeer.PubKey()
3✔
3627
                if err != nil {
3✔
3628
                        return err
×
3629
                }
×
3630

3631
                nodeAddrsMap[pubStr] = n
3✔
3632
                return nil
3✔
3633
        })
3634
        if err != nil {
3✔
3635
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3636
                        "%v", err)
×
3637

×
3638
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3639
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3640

×
3641
                        return err
×
3642
                }
×
3643
        }
3644

3645
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3646
                len(nodeAddrsMap))
3✔
3647

3✔
3648
        // Acquire and hold server lock until all persistent connection requests
3✔
3649
        // have been recorded and sent to the connection manager.
3✔
3650
        s.mu.Lock()
3✔
3651
        defer s.mu.Unlock()
3✔
3652

3✔
3653
        // Iterate through the combined list of addresses from prior links and
3✔
3654
        // node announcements and attempt to reconnect to each node.
3✔
3655
        var numOutboundConns int
3✔
3656
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3657
                // Add this peer to the set of peers we should maintain a
3✔
3658
                // persistent connection with. We set the value to false to
3✔
3659
                // indicate that we should not continue to reconnect if the
3✔
3660
                // number of channels returns to zero, since this peer has not
3✔
3661
                // been requested as perm by the user.
3✔
3662
                s.persistentPeers[pubStr] = false
3✔
3663
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3664
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3665
                }
3✔
3666

3667
                for _, address := range nodeAddr.addresses {
6✔
3668
                        // Create a wrapper address which couples the IP and
3✔
3669
                        // the pubkey so the brontide authenticated connection
3✔
3670
                        // can be established.
3✔
3671
                        lnAddr := &lnwire.NetAddress{
3✔
3672
                                IdentityKey: nodeAddr.pubKey,
3✔
3673
                                Address:     address,
3✔
3674
                        }
3✔
3675

3✔
3676
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3677
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3678
                }
3✔
3679

3680
                // We'll connect to the first 10 peers immediately, then
3681
                // randomly stagger any remaining connections if the
3682
                // stagger initial reconnect flag is set. This ensures
3683
                // that mobile nodes or nodes with a small number of
3684
                // channels obtain connectivity quickly, but larger
3685
                // nodes are able to disperse the costs of connecting to
3686
                // all peers at once.
3687
                if numOutboundConns < numInstantInitReconnect ||
3✔
3688
                        !s.cfg.StaggerInitialReconnect {
6✔
3689

3✔
3690
                        go s.connectToPersistentPeer(pubStr)
3✔
3691
                } else {
3✔
3692
                        go s.delayInitialReconnect(pubStr)
×
3693
                }
×
3694

3695
                numOutboundConns++
3✔
3696
        }
3697

3698
        return nil
3✔
3699
}
3700

3701
// delayInitialReconnect will attempt a reconnection to the given peer after
3702
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3703
//
3704
// NOTE: This method MUST be run as a goroutine.
3705
func (s *server) delayInitialReconnect(pubStr string) {
×
3706
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3707
        select {
×
3708
        case <-time.After(delay):
×
3709
                s.connectToPersistentPeer(pubStr)
×
3710
        case <-s.quit:
×
3711
        }
3712
}
3713

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

3✔
3720
        s.mu.Lock()
3✔
3721
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3722
                delete(s.persistentPeers, pubKeyStr)
3✔
3723
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3724
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3725
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3726
                s.mu.Unlock()
3✔
3727

3✔
3728
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3729
                        "peer has no open channels", compressedPubKey)
3✔
3730

3✔
3731
                return
3✔
3732
        }
3✔
3733
        s.mu.Unlock()
3✔
3734
}
3735

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

3753
// BroadcastMessage sends a request to the server to broadcast a set of
3754
// messages to all peers other than the one specified by the `skips` parameter.
3755
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3756
// the target peers.
3757
//
3758
// NOTE: This function is safe for concurrent access.
3759
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3760
        msgs ...lnwire.Message) error {
3✔
3761

3✔
3762
        // Filter out peers found in the skips map. We synchronize access to
3✔
3763
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3764
        // exact set of peers present at the time of invocation.
3✔
3765
        s.mu.RLock()
3✔
3766
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3767
        for pubStr, sPeer := range s.peersByPub {
6✔
3768
                if skips != nil {
6✔
3769
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3770
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3771
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3772
                                continue
3✔
3773
                        }
3774
                }
3775

3776
                peers = append(peers, sPeer)
3✔
3777
        }
3778
        s.mu.RUnlock()
3✔
3779

3✔
3780
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3781
        // all messages to each of peers.
3✔
3782
        var wg sync.WaitGroup
3✔
3783
        for _, sPeer := range peers {
6✔
3784
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3785
                        sPeer.PubKey())
3✔
3786

3✔
3787
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3788
                wg.Add(1)
3✔
3789
                s.wg.Add(1)
3✔
3790
                go func(p lnpeer.Peer) {
6✔
3791
                        defer s.wg.Done()
3✔
3792
                        defer wg.Done()
3✔
3793

3✔
3794
                        p.SendMessageLazy(false, msgs...)
3✔
3795
                }(sPeer)
3✔
3796
        }
3797

3798
        // Wait for all messages to have been dispatched before returning to
3799
        // caller.
3800
        wg.Wait()
3✔
3801

3✔
3802
        return nil
3✔
3803
}
3804

3805
// NotifyWhenOnline can be called by other subsystems to get notified when a
3806
// particular peer comes online. The peer itself is sent across the peerChan.
3807
//
3808
// NOTE: This function is safe for concurrent access.
3809
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3810
        peerChan chan<- lnpeer.Peer) {
3✔
3811

3✔
3812
        s.mu.Lock()
3✔
3813

3✔
3814
        // Compute the target peer's identifier.
3✔
3815
        pubStr := string(peerKey[:])
3✔
3816

3✔
3817
        // Check if peer is connected.
3✔
3818
        peer, ok := s.peersByPub[pubStr]
3✔
3819
        if ok {
6✔
3820
                // Unlock here so that the mutex isn't held while we are
3✔
3821
                // waiting for the peer to become active.
3✔
3822
                s.mu.Unlock()
3✔
3823

3✔
3824
                // Wait until the peer signals that it is actually active
3✔
3825
                // rather than only in the server's maps.
3✔
3826
                select {
3✔
3827
                case <-peer.ActiveSignal():
3✔
3828
                case <-peer.QuitSignal():
1✔
3829
                        // The peer quit, so we'll add the channel to the slice
1✔
3830
                        // and return.
1✔
3831
                        s.mu.Lock()
1✔
3832
                        s.peerConnectedListeners[pubStr] = append(
1✔
3833
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3834
                        )
1✔
3835
                        s.mu.Unlock()
1✔
3836
                        return
1✔
3837
                }
3838

3839
                // Connected, can return early.
3840
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3841

3✔
3842
                select {
3✔
3843
                case peerChan <- peer:
3✔
3844
                case <-s.quit:
×
3845
                }
3846

3847
                return
3✔
3848
        }
3849

3850
        // Not connected, store this listener such that it can be notified when
3851
        // the peer comes online.
3852
        s.peerConnectedListeners[pubStr] = append(
3✔
3853
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3854
        )
3✔
3855
        s.mu.Unlock()
3✔
3856
}
3857

3858
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3859
// the given public key has been disconnected. The notification is signaled by
3860
// closing the channel returned.
3861
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3862
        s.mu.Lock()
3✔
3863
        defer s.mu.Unlock()
3✔
3864

3✔
3865
        c := make(chan struct{})
3✔
3866

3✔
3867
        // If the peer is already offline, we can immediately trigger the
3✔
3868
        // notification.
3✔
3869
        peerPubKeyStr := string(peerPubKey[:])
3✔
3870
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3871
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3872
                close(c)
×
3873
                return c
×
3874
        }
×
3875

3876
        // Otherwise, the peer is online, so we'll keep track of the channel to
3877
        // trigger the notification once the server detects the peer
3878
        // disconnects.
3879
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3880
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3881
        )
3✔
3882

3✔
3883
        return c
3✔
3884
}
3885

3886
// FindPeer will return the peer that corresponds to the passed in public key.
3887
// This function is used by the funding manager, allowing it to update the
3888
// daemon's local representation of the remote peer.
3889
//
3890
// NOTE: This function is safe for concurrent access.
3891
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3892
        s.mu.RLock()
3✔
3893
        defer s.mu.RUnlock()
3✔
3894

3✔
3895
        pubStr := string(peerKey.SerializeCompressed())
3✔
3896

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

3900
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3901
// which should be a string representation of the peer's serialized, compressed
3902
// public key.
3903
//
3904
// NOTE: This function is safe for concurrent access.
3905
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3906
        s.mu.RLock()
3✔
3907
        defer s.mu.RUnlock()
3✔
3908

3✔
3909
        return s.findPeerByPubStr(pubStr)
3✔
3910
}
3✔
3911

3912
// findPeerByPubStr is an internal method that retrieves the specified peer from
3913
// the server's internal state using.
3914
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3915
        peer, ok := s.peersByPub[pubStr]
3✔
3916
        if !ok {
6✔
3917
                return nil, ErrPeerNotConnected
3✔
3918
        }
3✔
3919

3920
        return peer, nil
3✔
3921
}
3922

3923
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3924
// exponential backoff. If no previous backoff was known, the default is
3925
// returned.
3926
func (s *server) nextPeerBackoff(pubStr string,
3927
        startTime time.Time) time.Duration {
3✔
3928

3✔
3929
        // Now, determine the appropriate backoff to use for the retry.
3✔
3930
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3931
        if !ok {
6✔
3932
                // If an existing backoff was unknown, use the default.
3✔
3933
                return s.cfg.MinBackoff
3✔
3934
        }
3✔
3935

3936
        // If the peer failed to start properly, we'll just use the previous
3937
        // backoff to compute the subsequent randomized exponential backoff
3938
        // duration. This will roughly double on average.
3939
        if startTime.IsZero() {
3✔
3940
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3941
        }
×
3942

3943
        // The peer succeeded in starting. If the connection didn't last long
3944
        // enough to be considered stable, we'll continue to back off retries
3945
        // with this peer.
3946
        connDuration := time.Since(startTime)
3✔
3947
        if connDuration < defaultStableConnDuration {
6✔
3948
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3949
        }
3✔
3950

3951
        // The peer succeed in starting and this was stable peer, so we'll
3952
        // reduce the timeout duration by the length of the connection after
3953
        // applying randomized exponential backoff. We'll only apply this in the
3954
        // case that:
3955
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3956
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3957
        if relaxedBackoff > s.cfg.MinBackoff {
×
3958
                return relaxedBackoff
×
3959
        }
×
3960

3961
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3962
        // the stable connection lasted much longer than our previous backoff.
3963
        // To reward such good behavior, we'll reconnect after the default
3964
        // timeout.
3965
        return s.cfg.MinBackoff
×
3966
}
3967

3968
// shouldDropLocalConnection determines if our local connection to a remote peer
3969
// should be dropped in the case of concurrent connection establishment. In
3970
// order to deterministically decide which connection should be dropped, we'll
3971
// utilize the ordering of the local and remote public key. If we didn't use
3972
// such a tie breaker, then we risk _both_ connections erroneously being
3973
// dropped.
3974
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3975
        localPubBytes := local.SerializeCompressed()
×
3976
        remotePubPbytes := remote.SerializeCompressed()
×
3977

×
3978
        // The connection that comes from the node with a "smaller" pubkey
×
3979
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3980
        // should drop our established connection.
×
3981
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3982
}
×
3983

3984
// InboundPeerConnected initializes a new peer in response to a new inbound
3985
// connection.
3986
//
3987
// NOTE: This function is safe for concurrent access.
3988
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3989
        // Exit early if we have already been instructed to shutdown, this
3✔
3990
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3991
        if s.Stopped() {
3✔
3992
                return
×
3993
        }
×
3994

3995
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3996
        pubSer := nodePub.SerializeCompressed()
3✔
3997
        pubStr := string(pubSer)
3✔
3998

3✔
3999
        var pubBytes [33]byte
3✔
4000
        copy(pubBytes[:], pubSer)
3✔
4001

3✔
4002
        s.mu.Lock()
3✔
4003
        defer s.mu.Unlock()
3✔
4004

3✔
4005
        // If the remote node's public key is banned, drop the connection.
3✔
4006
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4007
        if err != nil {
3✔
4008
                // Clean up the persistent peer maps if we're dropping this
×
4009
                // connection.
×
4010
                s.bannedPersistentPeerConnection(pubStr)
×
4011

×
4012
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4013
                        "of restricted-access connection slots: %v.", pubSer,
×
4014
                        err)
×
4015

×
4016
                conn.Close()
×
4017

×
4018
                return
×
4019
        }
×
4020

4021
        // If we already have an outbound connection to this peer, then ignore
4022
        // this new connection.
4023
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4024
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4025
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4026
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4027

3✔
4028
                conn.Close()
3✔
4029
                return
3✔
4030
        }
3✔
4031

4032
        // If we already have a valid connection that is scheduled to take
4033
        // precedence once the prior peer has finished disconnecting, we'll
4034
        // ignore this connection.
4035
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4036
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4037
                        "scheduled", conn.RemoteAddr(), p)
×
4038
                conn.Close()
×
4039
                return
×
4040
        }
×
4041

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

3✔
4044
        // Check to see if we already have a connection with this peer. If so,
3✔
4045
        // we may need to drop our existing connection. This prevents us from
3✔
4046
        // having duplicate connections to the same peer. We forgo adding a
3✔
4047
        // default case as we expect these to be the only error values returned
3✔
4048
        // from findPeerByPubStr.
3✔
4049
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4050
        switch err {
3✔
4051
        case ErrPeerNotConnected:
3✔
4052
                // We were unable to locate an existing connection with the
3✔
4053
                // target peer, proceed to connect.
3✔
4054
                s.cancelConnReqs(pubStr, nil)
3✔
4055
                s.peerConnected(conn, nil, true, access)
3✔
4056

4057
        case nil:
×
4058
                // We already have a connection with the incoming peer. If the
×
4059
                // connection we've already established should be kept and is
×
4060
                // not of the same type of the new connection (inbound), then
×
4061
                // we'll close out the new connection s.t there's only a single
×
4062
                // connection between us.
×
4063
                localPub := s.identityECDH.PubKey()
×
4064
                if !connectedPeer.Inbound() &&
×
4065
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4066

×
4067
                        srvrLog.Warnf("Received inbound connection from "+
×
4068
                                "peer %v, but already have outbound "+
×
4069
                                "connection, dropping conn", connectedPeer)
×
4070
                        conn.Close()
×
4071
                        return
×
4072
                }
×
4073

4074
                // Otherwise, if we should drop the connection, then we'll
4075
                // disconnect our already connected peer.
4076
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4077
                        connectedPeer)
×
4078

×
4079
                s.cancelConnReqs(pubStr, nil)
×
4080

×
4081
                // Remove the current peer from the server's internal state and
×
4082
                // signal that the peer termination watcher does not need to
×
4083
                // execute for this peer.
×
4084
                s.removePeer(connectedPeer)
×
4085
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4086
                s.scheduledPeerConnection[pubStr] = func() {
×
4087
                        s.peerConnected(conn, nil, true, access)
×
4088
                }
×
4089
        }
4090
}
4091

4092
// OutboundPeerConnected initializes a new peer in response to a new outbound
4093
// connection.
4094
// NOTE: This function is safe for concurrent access.
4095
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4096
        // Exit early if we have already been instructed to shutdown, this
3✔
4097
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4098
        if s.Stopped() {
3✔
4099
                return
×
4100
        }
×
4101

4102
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4103
        pubSer := nodePub.SerializeCompressed()
3✔
4104
        pubStr := string(pubSer)
3✔
4105

3✔
4106
        var pubBytes [33]byte
3✔
4107
        copy(pubBytes[:], pubSer)
3✔
4108

3✔
4109
        s.mu.Lock()
3✔
4110
        defer s.mu.Unlock()
3✔
4111

3✔
4112
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4113
        if err != nil {
3✔
4114
                // Clean up the persistent peer maps if we're dropping this
×
4115
                // connection.
×
4116
                s.bannedPersistentPeerConnection(pubStr)
×
4117

×
4118
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4119
                        "of restricted-access connection slots: %v.", pubSer,
×
4120
                        err)
×
4121

×
4122
                if connReq != nil {
×
4123
                        s.connMgr.Remove(connReq.ID())
×
4124
                }
×
4125

4126
                conn.Close()
×
4127

×
4128
                return
×
4129
        }
4130

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

3✔
4138
                if connReq != nil {
6✔
4139
                        s.connMgr.Remove(connReq.ID())
3✔
4140
                }
3✔
4141
                conn.Close()
3✔
4142
                return
3✔
4143
        }
4144
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4145
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4146
                s.connMgr.Remove(connReq.ID())
×
4147
                conn.Close()
×
4148
                return
×
4149
        }
×
4150

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

×
4157
                if connReq != nil {
×
4158
                        s.connMgr.Remove(connReq.ID())
×
4159
                }
×
4160

4161
                conn.Close()
×
4162
                return
×
4163
        }
4164

4165
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4166
                conn.RemoteAddr())
3✔
4167

3✔
4168
        if connReq != nil {
6✔
4169
                // A successful connection was returned by the connmgr.
3✔
4170
                // Immediately cancel all pending requests, excluding the
3✔
4171
                // outbound connection we just established.
3✔
4172
                ignore := connReq.ID()
3✔
4173
                s.cancelConnReqs(pubStr, &ignore)
3✔
4174
        } else {
6✔
4175
                // This was a successful connection made by some other
3✔
4176
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4177
                s.cancelConnReqs(pubStr, nil)
3✔
4178
        }
3✔
4179

4180
        // If we already have a connection with this peer, decide whether or not
4181
        // we need to drop the stale connection. We forgo adding a default case
4182
        // as we expect these to be the only error values returned from
4183
        // findPeerByPubStr.
4184
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4185
        switch err {
3✔
4186
        case ErrPeerNotConnected:
3✔
4187
                // We were unable to locate an existing connection with the
3✔
4188
                // target peer, proceed to connect.
3✔
4189
                s.peerConnected(conn, connReq, false, access)
3✔
4190

4191
        case nil:
×
4192
                // We already have a connection with the incoming peer. If the
×
4193
                // connection we've already established should be kept and is
×
4194
                // not of the same type of the new connection (outbound), then
×
4195
                // we'll close out the new connection s.t there's only a single
×
4196
                // connection between us.
×
4197
                localPub := s.identityECDH.PubKey()
×
4198
                if connectedPeer.Inbound() &&
×
4199
                        shouldDropLocalConnection(localPub, nodePub) {
×
4200

×
4201
                        srvrLog.Warnf("Established outbound connection to "+
×
4202
                                "peer %v, but already have inbound "+
×
4203
                                "connection, dropping conn", connectedPeer)
×
4204
                        if connReq != nil {
×
4205
                                s.connMgr.Remove(connReq.ID())
×
4206
                        }
×
4207
                        conn.Close()
×
4208
                        return
×
4209
                }
4210

4211
                // Otherwise, _their_ connection should be dropped. So we'll
4212
                // disconnect the peer and send the now obsolete peer to the
4213
                // server for garbage collection.
4214
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4215
                        connectedPeer)
×
4216

×
4217
                // Remove the current peer from the server's internal state and
×
4218
                // signal that the peer termination watcher does not need to
×
4219
                // execute for this peer.
×
4220
                s.removePeer(connectedPeer)
×
4221
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4222
                s.scheduledPeerConnection[pubStr] = func() {
×
4223
                        s.peerConnected(conn, connReq, false, access)
×
4224
                }
×
4225
        }
4226
}
4227

4228
// UnassignedConnID is the default connection ID that a request can have before
4229
// it actually is submitted to the connmgr.
4230
// TODO(conner): move into connmgr package, or better, add connmgr method for
4231
// generating atomic IDs
4232
const UnassignedConnID uint64 = 0
4233

4234
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4235
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4236
// Afterwards, each connection request removed from the connmgr. The caller can
4237
// optionally specify a connection ID to ignore, which prevents us from
4238
// canceling a successful request. All persistent connreqs for the provided
4239
// pubkey are discarded after the operationjw.
4240
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4241
        // First, cancel any lingering persistent retry attempts, which will
3✔
4242
        // prevent retries for any with backoffs that are still maturing.
3✔
4243
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4244
                close(cancelChan)
3✔
4245
                delete(s.persistentRetryCancels, pubStr)
3✔
4246
        }
3✔
4247

4248
        // Next, check to see if we have any outstanding persistent connection
4249
        // requests to this peer. If so, then we'll remove all of these
4250
        // connection requests, and also delete the entry from the map.
4251
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4252
        if !ok {
6✔
4253
                return
3✔
4254
        }
3✔
4255

4256
        for _, connReq := range connReqs {
6✔
4257
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4258

3✔
4259
                // Atomically capture the current request identifier.
3✔
4260
                connID := connReq.ID()
3✔
4261

3✔
4262
                // Skip any zero IDs, this indicates the request has not
3✔
4263
                // yet been schedule.
3✔
4264
                if connID == UnassignedConnID {
3✔
4265
                        continue
×
4266
                }
4267

4268
                // Skip a particular connection ID if instructed.
4269
                if skip != nil && connID == *skip {
6✔
4270
                        continue
3✔
4271
                }
4272

4273
                s.connMgr.Remove(connID)
3✔
4274
        }
4275

4276
        delete(s.persistentConnReqs, pubStr)
3✔
4277
}
4278

4279
// handleCustomMessage dispatches an incoming custom peers message to
4280
// subscribers.
4281
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4282
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4283
                peer, msg.Type)
3✔
4284

3✔
4285
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4286
                Peer: peer,
3✔
4287
                Msg:  msg,
3✔
4288
        })
3✔
4289
}
3✔
4290

4291
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4292
// messages.
4293
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4294
        return s.customMessageServer.Subscribe()
3✔
4295
}
3✔
4296

4297
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4298
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
3✔
4299
        return s.onionMessageServer.Subscribe()
3✔
4300
}
3✔
4301

4302
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4303
// the channelNotifier's NotifyOpenChannelEvent.
4304
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4305
        remotePub *btcec.PublicKey) error {
3✔
4306

3✔
4307
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4308
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4309
                return err
3✔
4310
        }
3✔
4311

4312
        // Notify subscribers about this open channel event.
4313
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4314

3✔
4315
        return nil
3✔
4316
}
4317

4318
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4319
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4320
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4321
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4322

3✔
4323
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4324
        // peer.
3✔
4325
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4326
                return err
×
4327
        }
×
4328

4329
        // Notify subscribers about this event.
4330
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4331

3✔
4332
        return nil
3✔
4333
}
4334

4335
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4336
// calls the channelNotifier's NotifyFundingTimeout.
4337
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4338
        remotePub *btcec.PublicKey) error {
3✔
4339

3✔
4340
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4341
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4342
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4343
                // If we encounter an error while attempting to disconnect the
×
4344
                // peer, log the error.
×
4345
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4346
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4347
                }
×
4348
        }
4349

4350
        // Notify subscribers about this event.
4351
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4352

3✔
4353
        return nil
3✔
4354
}
4355

4356
// peerConnected is a function that handles initialization a newly connected
4357
// peer by adding it to the server's global list of all active peers, and
4358
// starting all the goroutines the peer needs to function properly. The inbound
4359
// boolean should be true if the peer initiated the connection to us.
4360
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4361
        inbound bool, access peerAccessStatus) {
3✔
4362

3✔
4363
        brontideConn := conn.(*brontide.Conn)
3✔
4364
        addr := conn.RemoteAddr()
3✔
4365
        pubKey := brontideConn.RemotePub()
3✔
4366

3✔
4367
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4368
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4369

3✔
4370
        peerAddr := &lnwire.NetAddress{
3✔
4371
                IdentityKey: pubKey,
3✔
4372
                Address:     addr,
3✔
4373
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4374
        }
3✔
4375

3✔
4376
        // With the brontide connection established, we'll now craft the feature
3✔
4377
        // vectors to advertise to the remote node.
3✔
4378
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4379
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4380

3✔
4381
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4382
        // found, create a fresh buffer.
3✔
4383
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4384
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4385
        if !ok {
6✔
4386
                var err error
3✔
4387
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4388
                if err != nil {
3✔
4389
                        srvrLog.Errorf("unable to create peer %v", err)
×
4390
                        return
×
4391
                }
×
4392
        }
4393

4394
        // If we directly set the peer.Config TowerClient member to the
4395
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4396
        // the peer.Config's TowerClient member will not evaluate to nil even
4397
        // though the underlying value is nil. To avoid this gotcha which can
4398
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4399
        // TowerClient if needed.
4400
        var towerClient wtclient.ClientManager
3✔
4401
        if s.towerClientMgr != nil {
6✔
4402
                towerClient = s.towerClientMgr
3✔
4403
        }
3✔
4404

4405
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4406
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4407

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

3✔
4452
                        return s.genNodeAnnouncement(nil)
3✔
4453
                },
3✔
4454

4455
                PongBuf: s.pongBuf,
4456

4457
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4458

4459
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4460

4461
                FundingManager: s.fundingMgr,
4462

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

4492
                        return clock.NewDefaultClock().Now().Before(
3✔
4493
                                EndorsementExperimentEnd,
3✔
4494
                        )
3✔
4495
                },
4496
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4497
        }
4498

4499
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4500
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4501

3✔
4502
        p := peer.NewBrontide(pCfg)
3✔
4503

3✔
4504
        // Update the access manager with the access permission for this peer.
3✔
4505
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4506

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

3✔
4510
        s.addPeer(p)
3✔
4511

3✔
4512
        // Once we have successfully added the peer to the server, we can
3✔
4513
        // delete the previous error buffer from the server's map of error
3✔
4514
        // buffers.
3✔
4515
        delete(s.peerErrors, pkStr)
3✔
4516

3✔
4517
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4518
        // includes sending and receiving Init messages, which would be a DOS
3✔
4519
        // vector if we held the server's mutex throughout the procedure.
3✔
4520
        s.wg.Add(1)
3✔
4521
        go s.peerInitializer(p)
3✔
4522
}
4523

4524
// addPeer adds the passed peer to the server's global state of all active
4525
// peers.
4526
func (s *server) addPeer(p *peer.Brontide) {
3✔
4527
        if p == nil {
3✔
4528
                return
×
4529
        }
×
4530

4531
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4532

3✔
4533
        // Ignore new peers if we're shutting down.
3✔
4534
        if s.Stopped() {
3✔
4535
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4536
                        pubBytes)
×
4537
                p.Disconnect(ErrServerShuttingDown)
×
4538

×
4539
                return
×
4540
        }
×
4541

4542
        // Track the new peer in our indexes so we can quickly look it up either
4543
        // according to its public key, or its peer ID.
4544
        // TODO(roasbeef): pipe all requests through to the
4545
        // queryHandler/peerManager
4546

4547
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4548
        // be human-readable.
4549
        pubStr := string(pubBytes)
3✔
4550

3✔
4551
        s.peersByPub[pubStr] = p
3✔
4552

3✔
4553
        if p.Inbound() {
6✔
4554
                s.inboundPeers[pubStr] = p
3✔
4555
        } else {
6✔
4556
                s.outboundPeers[pubStr] = p
3✔
4557
        }
3✔
4558

4559
        // Inform the peer notifier of a peer online event so that it can be reported
4560
        // to clients listening for peer events.
4561
        var pubKey [33]byte
3✔
4562
        copy(pubKey[:], pubBytes)
3✔
4563

3✔
4564
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4565
}
4566

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

3✔
4579
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4580

3✔
4581
        // Avoid initializing peers while the server is exiting.
3✔
4582
        if s.Stopped() {
3✔
4583
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4584
                        pubBytes)
×
4585
                return
×
4586
        }
×
4587

4588
        // Create a channel that will be used to signal a successful start of
4589
        // the link. This prevents the peer termination watcher from beginning
4590
        // its duty too early.
4591
        ready := make(chan struct{})
3✔
4592

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

3✔
4602
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4603
        // will unblock the peerTerminationWatcher.
3✔
4604
        if err := p.Start(); err != nil {
6✔
4605
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4606

3✔
4607
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4608
                return
3✔
4609
        }
3✔
4610

4611
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4612
        // was successful, and to begin watching the peer's wait group.
4613
        close(ready)
3✔
4614

3✔
4615
        s.mu.Lock()
3✔
4616
        defer s.mu.Unlock()
3✔
4617

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

3✔
4621
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4622
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4623
        pubStr := string(pubBytes)
3✔
4624
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4625
                select {
3✔
4626
                case peerChan <- p:
3✔
4627
                case <-s.quit:
×
4628
                        return
×
4629
                }
4630
        }
4631
        delete(s.peerConnectedListeners, pubStr)
3✔
4632
}
4633

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

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

3✔
4650
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4651

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4764
        // We came across an error retrieving an advertised
4765
        // address, log it, and fall back to the existing peer
4766
        // address.
4767
        default:
3✔
4768
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4769
                        "address for node %x: %v", p.PubKey(),
3✔
4770
                        err)
3✔
4771
        }
4772

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

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

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

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

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

4808
        // We choose not to wait group this go routine since the Connect
4809
        // call can stall for arbitrarily long if we shutdown while an
4810
        // outbound connection attempt is being made.
4811
        go func() {
6✔
4812
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4813
                        "persistent peer %x in %s",
3✔
4814
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4815

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

4824
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4825
                        "connection to peer %x",
3✔
4826
                        p.IdentityKey().SerializeCompressed())
3✔
4827

3✔
4828
                s.connectToPersistentPeer(pubStr)
3✔
4829
        }()
4830
}
4831

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

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

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

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

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

4882
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4883

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

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

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

3✔
4907
                        s.mu.Lock()
3✔
4908
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4909
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4910
                        )
3✔
4911
                        s.mu.Unlock()
3✔
4912

3✔
4913
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4914
                                "channel peer %v", addr)
3✔
4915

3✔
4916
                        go s.connMgr.Connect(connReq)
3✔
4917

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

4929
// removePeer removes the passed peer from the server's state of all active
4930
// peers.
4931
func (s *server) removePeer(p *peer.Brontide) {
3✔
4932
        if p == nil {
3✔
4933
                return
×
4934
        }
×
4935

4936
        srvrLog.Debugf("removing peer %v", p)
3✔
4937

3✔
4938
        // As the peer is now finished, ensure that the TCP connection is
3✔
4939
        // closed and all of its related goroutines have exited.
3✔
4940
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
3✔
4941

3✔
4942
        // If this peer had an active persistent connection request, remove it.
3✔
4943
        if p.ConnReq() != nil {
6✔
4944
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4945
        }
3✔
4946

4947
        // Ignore deleting peers if we're shutting down.
4948
        if s.Stopped() {
3✔
4949
                return
×
4950
        }
×
4951

4952
        pKey := p.PubKey()
3✔
4953
        pubSer := pKey[:]
3✔
4954
        pubStr := string(pubSer)
3✔
4955

3✔
4956
        delete(s.peersByPub, pubStr)
3✔
4957

3✔
4958
        if p.Inbound() {
6✔
4959
                delete(s.inboundPeers, pubStr)
3✔
4960
        } else {
6✔
4961
                delete(s.outboundPeers, pubStr)
3✔
4962
        }
3✔
4963

4964
        // Remove the peer's access permission from the access manager.
4965
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4966

3✔
4967
        // Copy the peer's error buffer across to the server if it has any items
3✔
4968
        // in it so that we can restore peer errors across connections.
3✔
4969
        if p.ErrorBuffer().Total() > 0 {
6✔
4970
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4971
        }
3✔
4972

4973
        // Inform the peer notifier of a peer offline event so that it can be
4974
        // reported to clients listening for peer events.
4975
        var pubKey [33]byte
3✔
4976
        copy(pubKey[:], pubSer)
3✔
4977

3✔
4978
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4979
}
4980

4981
// ConnectToPeer requests that the server connect to a Lightning Network peer
4982
// at the specified address. This function will *block* until either a
4983
// connection is established, or the initial handshake process fails.
4984
//
4985
// NOTE: This function is safe for concurrent access.
4986
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4987
        perm bool, timeout time.Duration) error {
3✔
4988

3✔
4989
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4990

3✔
4991
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4992
        // better granularity.  In certain conditions, this method requires
3✔
4993
        // making an outbound connection to a remote peer, which requires the
3✔
4994
        // lock to be released, and subsequently reacquired.
3✔
4995
        s.mu.Lock()
3✔
4996

3✔
4997
        // Ensure we're not already connected to this peer.
3✔
4998
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4999
        if err == nil {
6✔
5000
                s.mu.Unlock()
3✔
5001
                return &errPeerAlreadyConnected{peer: peer}
3✔
5002
        }
3✔
5003

5004
        // Peer was not found, continue to pursue connection with peer.
5005

5006
        // If there's already a pending connection request for this pubkey,
5007
        // then we ignore this request to ensure we don't create a redundant
5008
        // connection.
5009
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5010
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5011
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5012
        }
3✔
5013

5014
        // If there's not already a pending or active connection to this node,
5015
        // then instruct the connection manager to attempt to establish a
5016
        // persistent connection to the peer.
5017
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5018
        if perm {
6✔
5019
                connReq := &connmgr.ConnReq{
3✔
5020
                        Addr:      addr,
3✔
5021
                        Permanent: true,
3✔
5022
                }
3✔
5023

3✔
5024
                // Since the user requested a permanent connection, we'll set
3✔
5025
                // the entry to true which will tell the server to continue
3✔
5026
                // reconnecting even if the number of channels with this peer is
3✔
5027
                // zero.
3✔
5028
                s.persistentPeers[targetPub] = true
3✔
5029
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5030
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5031
                }
3✔
5032
                s.persistentConnReqs[targetPub] = append(
3✔
5033
                        s.persistentConnReqs[targetPub], connReq,
3✔
5034
                )
3✔
5035
                s.mu.Unlock()
3✔
5036

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

3✔
5039
                return nil
3✔
5040
        }
5041
        s.mu.Unlock()
3✔
5042

3✔
5043
        // If we're not making a persistent connection, then we'll attempt to
3✔
5044
        // connect to the target peer. If the we can't make the connection, or
3✔
5045
        // the crypto negotiation breaks down, then return an error to the
3✔
5046
        // caller.
3✔
5047
        errChan := make(chan error, 1)
3✔
5048
        s.connectToPeer(addr, errChan, timeout)
3✔
5049

3✔
5050
        select {
3✔
5051
        case err := <-errChan:
3✔
5052
                return err
3✔
5053
        case <-s.quit:
×
5054
                return ErrServerShuttingDown
×
5055
        }
5056
}
5057

5058
// connectToPeer establishes a connection to a remote peer. errChan is used to
5059
// notify the caller if the connection attempt has failed. Otherwise, it will be
5060
// closed.
5061
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5062
        errChan chan<- error, timeout time.Duration) {
3✔
5063

3✔
5064
        conn, err := brontide.Dial(
3✔
5065
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5066
        )
3✔
5067
        if err != nil {
6✔
5068
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5069
                select {
3✔
5070
                case errChan <- err:
3✔
5071
                case <-s.quit:
×
5072
                }
5073
                return
3✔
5074
        }
5075

5076
        close(errChan)
3✔
5077

3✔
5078
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5079
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5080

3✔
5081
        s.OutboundPeerConnected(nil, conn)
3✔
5082
}
5083

5084
// DisconnectPeer sends the request to server to close the connection with peer
5085
// identified by public key.
5086
//
5087
// NOTE: This function is safe for concurrent access.
5088
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5089
        pubBytes := pubKey.SerializeCompressed()
3✔
5090
        pubStr := string(pubBytes)
3✔
5091

3✔
5092
        s.mu.Lock()
3✔
5093
        defer s.mu.Unlock()
3✔
5094

3✔
5095
        // Check that were actually connected to this peer. If not, then we'll
3✔
5096
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5097
        // currently connected to.
3✔
5098
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5099
        if err == ErrPeerNotConnected {
6✔
5100
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5101
        }
3✔
5102

5103
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5104

3✔
5105
        s.cancelConnReqs(pubStr, nil)
3✔
5106

3✔
5107
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5108
        // them from this map so we don't attempt to re-connect after we
3✔
5109
        // disconnect.
3✔
5110
        delete(s.persistentPeers, pubStr)
3✔
5111
        delete(s.persistentPeersBackoff, pubStr)
3✔
5112

3✔
5113
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5114
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5115
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5116

3✔
5117
        return nil
3✔
5118
}
5119

5120
// OpenChannel sends a request to the server to open a channel to the specified
5121
// peer identified by nodeKey with the passed channel funding parameters.
5122
//
5123
// NOTE: This function is safe for concurrent access.
5124
func (s *server) OpenChannel(
5125
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5126

3✔
5127
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5128
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5129
        // not blocked if the caller is not reading the updates.
3✔
5130
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5131
        req.Err = make(chan error, 1)
3✔
5132

3✔
5133
        // First attempt to locate the target peer to open a channel with, if
3✔
5134
        // we're unable to locate the peer then this request will fail.
3✔
5135
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5136
        s.mu.RLock()
3✔
5137
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5138
        if !ok {
3✔
5139
                s.mu.RUnlock()
×
5140

×
5141
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5142
                return req.Updates, req.Err
×
5143
        }
×
5144
        req.Peer = peer
3✔
5145
        s.mu.RUnlock()
3✔
5146

3✔
5147
        // We'll wait until the peer is active before beginning the channel
3✔
5148
        // opening process.
3✔
5149
        select {
3✔
5150
        case <-peer.ActiveSignal():
3✔
5151
        case <-peer.QuitSignal():
×
5152
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5153
                return req.Updates, req.Err
×
5154
        case <-s.quit:
×
5155
                req.Err <- ErrServerShuttingDown
×
5156
                return req.Updates, req.Err
×
5157
        }
5158

5159
        // If the fee rate wasn't specified at this point we fail the funding
5160
        // because of the missing fee rate information. The caller of the
5161
        // `OpenChannel` method needs to make sure that default values for the
5162
        // fee rate are set beforehand.
5163
        if req.FundingFeePerKw == 0 {
3✔
5164
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5165
                        "the channel opening transaction")
×
5166

×
5167
                return req.Updates, req.Err
×
5168
        }
×
5169

5170
        // Spawn a goroutine to send the funding workflow request to the funding
5171
        // manager. This allows the server to continue handling queries instead
5172
        // of blocking on this request which is exported as a synchronous
5173
        // request to the outside world.
5174
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5175

3✔
5176
        return req.Updates, req.Err
3✔
5177
}
5178

5179
// Peers returns a slice of all active peers.
5180
//
5181
// NOTE: This function is safe for concurrent access.
5182
func (s *server) Peers() []*peer.Brontide {
3✔
5183
        s.mu.RLock()
3✔
5184
        defer s.mu.RUnlock()
3✔
5185

3✔
5186
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5187
        for _, peer := range s.peersByPub {
6✔
5188
                peers = append(peers, peer)
3✔
5189
        }
3✔
5190

5191
        return peers
3✔
5192
}
5193

5194
// computeNextBackoff uses a truncated exponential backoff to compute the next
5195
// backoff using the value of the exiting backoff. The returned duration is
5196
// randomized in either direction by 1/20 to prevent tight loops from
5197
// stabilizing.
5198
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5199
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5200
        nextBackoff := 2 * currBackoff
3✔
5201
        if nextBackoff > maxBackoff {
6✔
5202
                nextBackoff = maxBackoff
3✔
5203
        }
3✔
5204

5205
        // Using 1/10 of our duration as a margin, compute a random offset to
5206
        // avoid the nodes entering connection cycles.
5207
        margin := nextBackoff / 10
3✔
5208

3✔
5209
        var wiggle big.Int
3✔
5210
        wiggle.SetUint64(uint64(margin))
3✔
5211
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5212
                // Randomizing is not mission critical, so we'll just return the
×
5213
                // current backoff.
×
5214
                return nextBackoff
×
5215
        }
×
5216

5217
        // Otherwise add in our wiggle, but subtract out half of the margin so
5218
        // that the backoff can tweaked by 1/20 in either direction.
5219
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5220
}
5221

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

5226
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5227
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5228
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5229
        if err != nil {
3✔
5230
                return nil, err
×
5231
        }
×
5232

5233
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5234
        if err != nil {
6✔
5235
                return nil, err
3✔
5236
        }
3✔
5237

5238
        if len(node.Addresses) == 0 {
6✔
5239
                return nil, errNoAdvertisedAddr
3✔
5240
        }
3✔
5241

5242
        return node.Addresses, nil
3✔
5243
}
5244

5245
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5246
// channel update for a target channel.
5247
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5248
        *lnwire.ChannelUpdate1, error) {
3✔
5249

3✔
5250
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5251
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5252
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5253
                if err != nil {
6✔
5254
                        return nil, err
3✔
5255
                }
3✔
5256

5257
                return netann.ExtractChannelUpdate(
3✔
5258
                        ourPubKey[:], info, edge1, edge2,
3✔
5259
                )
3✔
5260
        }
5261
}
5262

5263
// applyChannelUpdate applies the channel update to the different sub-systems of
5264
// the server. The useAlias boolean denotes whether or not to send an alias in
5265
// place of the real SCID.
5266
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5267
        op *wire.OutPoint, useAlias bool) error {
3✔
5268

3✔
5269
        var (
3✔
5270
                peerAlias    *lnwire.ShortChannelID
3✔
5271
                defaultAlias lnwire.ShortChannelID
3✔
5272
        )
3✔
5273

3✔
5274
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5275

3✔
5276
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5277
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5278
        if useAlias {
6✔
5279
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5280
                if foundAlias != defaultAlias {
6✔
5281
                        peerAlias = &foundAlias
3✔
5282
                }
3✔
5283
        }
5284

5285
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5286
                update, discovery.RemoteAlias(peerAlias),
3✔
5287
        )
3✔
5288
        select {
3✔
5289
        case err := <-errChan:
3✔
5290
                return err
3✔
5291
        case <-s.quit:
×
5292
                return ErrServerShuttingDown
×
5293
        }
5294
}
5295

5296
// SendCustomMessage sends a custom message to the peer with the specified
5297
// pubkey.
5298
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5299
        data []byte) error {
3✔
5300

3✔
5301
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5302
        if err != nil {
3✔
5303
                return err
×
5304
        }
×
5305

5306
        // We'll wait until the peer is active.
5307
        select {
3✔
5308
        case <-peer.ActiveSignal():
3✔
5309
        case <-peer.QuitSignal():
×
5310
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5311
        case <-s.quit:
×
5312
                return ErrServerShuttingDown
×
5313
        }
5314

5315
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5316
        if err != nil {
6✔
5317
                return err
3✔
5318
        }
3✔
5319

5320
        // Send the message as low-priority. For now we assume that all
5321
        // application-defined message are low priority.
5322
        return peer.SendMessageLazy(true, msg)
3✔
5323
}
5324

5325
// SendOnionMessage sends a custom message to the peer with the specified
5326
// pubkey.
5327
// TODO(gijs): change this message to include path finding.
5328
func (s *server) SendOnionMessage(peerPub [33]byte,
5329
        blindingPoint *btcec.PublicKey, onion []byte) error {
3✔
5330

3✔
5331
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5332
        if err != nil {
3✔
UNCOV
5333
                return err
×
UNCOV
5334
        }
×
5335

5336
        // We'll wait until the peer is active.
5337
        select {
3✔
5338
        case <-peer.ActiveSignal():
3✔
5339
        case <-peer.QuitSignal():
×
5340
                return fmt.Errorf("peer %x disconnected", peerPub)
×
NEW
5341
        case <-s.quit:
×
NEW
5342
                return ErrServerShuttingDown
×
5343
        }
5344

5345
        msg := lnwire.NewOnionMessage(blindingPoint, onion)
3✔
5346

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

5352
// newSweepPkScriptGen creates closure that generates a new public key script
5353
// which should be used to sweep any funds into the on-chain wallet.
5354
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5355
// (p2wkh) output.
5356
func newSweepPkScriptGen(
5357
        wallet lnwallet.WalletController,
5358
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5359

3✔
5360
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5361
                sweepAddr, err := wallet.NewAddress(
3✔
5362
                        lnwallet.TaprootPubkey, false,
3✔
5363
                        lnwallet.DefaultAccountName,
3✔
5364
                )
3✔
5365
                if err != nil {
3✔
NEW
5366
                        return fn.Err[lnwallet.AddrWithKey](err)
×
NEW
5367
                }
×
5368

5369
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5370
                if err != nil {
3✔
5371
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5372
                }
×
5373

5374
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5375
                        wallet, netParams, addr,
3✔
5376
                )
3✔
5377
                if err != nil {
3✔
5378
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5379
                }
×
5380

5381
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5382
                        DeliveryAddress: addr,
3✔
5383
                        InternalKey:     internalKeyDesc,
3✔
5384
                })
3✔
5385
        }
5386
}
5387

5388
// shouldPeerBootstrap returns true if we should attempt to perform peer
5389
// bootstrapping to actively seek our peers using the set of active network
5390
// bootstrappers.
5391
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5392
        isSimnet := cfg.Bitcoin.SimNet
3✔
5393
        isSignet := cfg.Bitcoin.SigNet
3✔
5394
        isRegtest := cfg.Bitcoin.RegTest
3✔
5395
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5396

3✔
5397
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5398
        // covering the bootstrapping process.
3✔
5399
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5400
}
3✔
5401

5402
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5403
// finished.
5404
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5405
        // Get a list of closed channels.
3✔
5406
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5407
        if err != nil {
3✔
5408
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5409
                return nil
×
5410
        }
×
5411

5412
        // Save the SCIDs in a map.
5413
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5414
        for _, c := range channels {
6✔
5415
                // If the channel is not pending, its FC has been finalized.
3✔
5416
                if !c.IsPending {
6✔
5417
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5418
                }
3✔
5419
        }
5420

5421
        // Double check whether the reported closed channel has indeed finished
5422
        // closing.
5423
        //
5424
        // NOTE: There are misalignments regarding when a channel's FC is
5425
        // marked as finalized. We double check the pending channels to make
5426
        // sure the returned SCIDs are indeed terminated.
5427
        //
5428
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5429
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5430
        if err != nil {
3✔
5431
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5432
                return nil
×
5433
        }
×
5434

5435
        for _, c := range pendings {
6✔
5436
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5437
                        continue
3✔
5438
                }
5439

5440
                // If the channel is still reported as pending, remove it from
5441
                // the map.
5442
                delete(closedSCIDs, c.ShortChannelID)
×
5443

×
5444
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5445
                        c.ShortChannelID)
×
5446
        }
5447

5448
        return closedSCIDs
3✔
5449
}
5450

5451
// getStartingBeat returns the current beat. This is used during the startup to
5452
// initialize blockbeat consumers.
5453
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5454
        // beat is the current blockbeat.
3✔
5455
        var beat *chainio.Beat
3✔
5456

3✔
5457
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5458
        // we will skip fetching the best block.
3✔
5459
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5460
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5461
                        "mode")
×
5462

×
5463
                return &chainio.Beat{}, nil
×
5464
        }
×
5465

5466
        // We should get a notification with the current best block immediately
5467
        // by passing a nil block.
5468
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5469
        if err != nil {
3✔
5470
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5471
        }
×
5472
        defer blockEpochs.Cancel()
3✔
5473

3✔
5474
        // We registered for the block epochs with a nil request. The notifier
3✔
5475
        // should send us the current best block immediately. So we need to
3✔
5476
        // wait for it here because we need to know the current best height.
3✔
5477
        select {
3✔
5478
        case bestBlock := <-blockEpochs.Epochs:
3✔
5479
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5480
                        bestBlock.Hash, bestBlock.Height)
3✔
5481

3✔
5482
                // Update the current blockbeat.
3✔
5483
                beat = chainio.NewBeat(*bestBlock)
3✔
5484

5485
        case <-s.quit:
×
5486
                srvrLog.Debug("LND shutting down")
×
5487
        }
5488

5489
        return beat, nil
3✔
5490
}
5491

5492
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5493
// point has an active RBF chan closer.
5494
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5495
        chanPoint wire.OutPoint) bool {
3✔
5496

3✔
5497
        pubBytes := peerPub.SerializeCompressed()
3✔
5498

3✔
5499
        s.mu.RLock()
3✔
5500
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5501
        s.mu.RUnlock()
3✔
5502
        if !ok {
3✔
5503
                return false
×
5504
        }
×
5505

5506
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5507
}
5508

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

3✔
5517
        // First, we'll attempt to look up the channel based on it's
3✔
5518
        // ChannelPoint.
3✔
5519
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5520
        if err != nil {
3✔
5521
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5522
        }
×
5523

5524
        // From the channel, we can now get the pubkey of the peer, then use
5525
        // that to eventually get the chan closer.
5526
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5527

3✔
5528
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5529
        s.mu.RLock()
3✔
5530
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5531
        s.mu.RUnlock()
3✔
5532
        if !ok {
3✔
5533
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5534
                        "not online", chanPoint)
×
5535
        }
×
5536

5537
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5538
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5539
        )
3✔
5540
        if err != nil {
3✔
5541
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5542
                        "%w", err)
×
5543
        }
×
5544

5545
        return closeUpdates, nil
3✔
5546
}
5547

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

3✔
5556
        // If the channel is present in the switch, then the request should flow
3✔
5557
        // through the switch instead.
3✔
5558
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5559
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5560
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5561
                        "invalid request", chanPoint)
×
5562
        }
×
5563

5564
        // At this point, we know that the channel isn't present in the link, so
5565
        // we'll check to see if we have an entry in the active chan closer map.
5566
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5567
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5568
        )
3✔
5569
        if err != nil {
3✔
5570
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5571
                        "ChannelPoint(%v)", chanPoint)
×
5572
        }
×
5573

5574
        return updates, nil
3✔
5575
}
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