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

lightningnetwork / lnd / 15973895448

30 Jun 2025 01:12PM UTC coverage: 67.627% (+0.05%) from 67.577%
15973895448

Pull #10007

github

web-flow
Merge a10fe7711 into 01dfee6f8
Pull Request #10007: graph/db: explicitly store bitfields for channel_update message & channel flags

0 of 65 new or added lines in 3 files covered. (0.0%)

40 existing lines in 12 files now uncovered.

135274 of 200031 relevant lines covered (67.63%)

21833.89 hits per line

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

69.95
/server.go
1
package lnd
2

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

19
        "github.com/btcsuite/btcd/btcec/v2"
20
        "github.com/btcsuite/btcd/btcec/v2/ecdsa"
21
        "github.com/btcsuite/btcd/btcutil"
22
        "github.com/btcsuite/btcd/chaincfg"
23
        "github.com/btcsuite/btcd/chaincfg/chainhash"
24
        "github.com/btcsuite/btcd/connmgr"
25
        "github.com/btcsuite/btcd/txscript"
26
        "github.com/btcsuite/btcd/wire"
27
        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
// String returns a human-readable representation of the status code.
197
func (p peerAccessStatus) String() string {
3✔
198
        switch p {
3✔
199
        case peerStatusRestricted:
3✔
200
                return "restricted"
3✔
201

202
        case peerStatusTemporary:
3✔
203
                return "temporary"
3✔
204

205
        case peerStatusProtected:
3✔
206
                return "protected"
3✔
207

208
        default:
×
209
                return "unknown"
×
210
        }
211
}
212

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

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

228
        start sync.Once
229
        stop  sync.Once
230

231
        cfg *Config
232

233
        implCfg *ImplementationCfg
234

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

239
        // identityKeyLoc is the key locator for the above wrapped identity key.
240
        identityKeyLoc keychain.KeyLocator
241

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

246
        chanStatusMgr *netann.ChanStatusManager
247

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

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

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

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

268
        mu sync.RWMutex
269

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

279
        inboundPeers  map[string]*peer.Brontide
280
        outboundPeers map[string]*peer.Brontide
281

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

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

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

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

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

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

320
        cc *chainreg.ChainControl
321

322
        fundingMgr *funding.Manager
323

324
        graphDB *graphdb.ChannelGraph
325

326
        chanStateDB *channeldb.ChannelStateDB
327

328
        addrSource channeldb.AddrSource
329

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

334
        invoicesDB invoices.InvoiceDB
335

336
        aliasMgr *aliasmgr.Manager
337

338
        htlcSwitch *htlcswitch.Switch
339

340
        interceptableSwitch *htlcswitch.InterceptableSwitch
341

342
        invoices *invoices.InvoiceRegistry
343

344
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
345

346
        channelNotifier *channelnotifier.ChannelNotifier
347

348
        peerNotifier *peernotifier.PeerNotifier
349

350
        htlcNotifier *htlcswitch.HtlcNotifier
351

352
        witnessBeacon contractcourt.WitnessBeacon
353

354
        breachArbitrator *contractcourt.BreachArbitrator
355

356
        missionController *routing.MissionController
357
        defaultMC         *routing.MissionControl
358

359
        graphBuilder *graph.Builder
360

361
        chanRouter *routing.ChannelRouter
362

363
        controlTower routing.ControlTower
364

365
        authGossiper *discovery.AuthenticatedGossiper
366

367
        localChanMgr *localchans.Manager
368

369
        utxoNursery *contractcourt.UtxoNursery
370

371
        sweeper *sweep.UtxoSweeper
372

373
        chainArb *contractcourt.ChainArbitrator
374

375
        sphinx *hop.OnionProcessor
376

377
        towerClientMgr *wtclient.Manager
378

379
        connMgr *connmgr.ConnManager
380

381
        sigPool *lnwallet.SigPool
382

383
        writePool *pool.Write
384

385
        readPool *pool.Read
386

387
        tlsManager *TLSManager
388

389
        // featureMgr dispatches feature vectors for various contexts within the
390
        // daemon.
391
        featureMgr *feature.Manager
392

393
        // currentNodeAnn is the node announcement that has been broadcast to
394
        // the network upon startup, if the attributes of the node (us) has
395
        // changed since last start.
396
        currentNodeAnn *lnwire.NodeAnnouncement
397

398
        // chansToRestore is the set of channels that upon starting, the server
399
        // should attempt to restore/recover.
400
        chansToRestore walletunlocker.ChannelsToRecover
401

402
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
403
        // backups are consistent at all times. It interacts with the
404
        // channelNotifier to be notified of newly opened and closed channels.
405
        chanSubSwapper *chanbackup.SubSwapper
406

407
        // chanEventStore tracks the behaviour of channels and their remote peers to
408
        // provide insights into their health and performance.
409
        chanEventStore *chanfitness.ChannelEventStore
410

411
        hostAnn *netann.HostAnnouncer
412

413
        // livenessMonitor monitors that lnd has access to critical resources.
414
        livenessMonitor *healthcheck.Monitor
415

416
        customMessageServer *subscribe.Server
417

418
        // txPublisher is a publisher with fee-bumping capability.
419
        txPublisher *sweep.TxPublisher
420

421
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
422
        // of new blocks.
423
        blockbeatDispatcher *chainio.BlockbeatDispatcher
424

425
        // peerAccessMan implements peer access controls.
426
        peerAccessMan *accessMan
427

428
        quit chan struct{}
429

430
        wg sync.WaitGroup
431
}
432

433
// updatePersistentPeerAddrs subscribes to topology changes and stores
434
// advertised addresses for any NodeAnnouncements from our persisted peers.
435
func (s *server) updatePersistentPeerAddrs() error {
3✔
436
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
437
        if err != nil {
3✔
438
                return err
×
439
        }
×
440

441
        s.wg.Add(1)
3✔
442
        go func() {
6✔
443
                defer func() {
6✔
444
                        graphSub.Cancel()
3✔
445
                        s.wg.Done()
3✔
446
                }()
3✔
447

448
                for {
6✔
449
                        select {
3✔
450
                        case <-s.quit:
3✔
451
                                return
3✔
452

453
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
454
                                // If the router is shutting down, then we will
3✔
455
                                // as well.
3✔
456
                                if !ok {
3✔
457
                                        return
×
458
                                }
×
459

460
                                for _, update := range topChange.NodeUpdates {
6✔
461
                                        pubKeyStr := string(
3✔
462
                                                update.IdentityKey.
3✔
463
                                                        SerializeCompressed(),
3✔
464
                                        )
3✔
465

3✔
466
                                        // We only care about updates from
3✔
467
                                        // our persistentPeers.
3✔
468
                                        s.mu.RLock()
3✔
469
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
470
                                        s.mu.RUnlock()
3✔
471
                                        if !ok {
6✔
472
                                                continue
3✔
473
                                        }
474

475
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
476
                                                len(update.Addresses))
3✔
477

3✔
478
                                        for _, addr := range update.Addresses {
6✔
479
                                                addrs = append(addrs,
3✔
480
                                                        &lnwire.NetAddress{
3✔
481
                                                                IdentityKey: update.IdentityKey,
3✔
482
                                                                Address:     addr,
3✔
483
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
484
                                                        },
3✔
485
                                                )
3✔
486
                                        }
3✔
487

488
                                        s.mu.Lock()
3✔
489

3✔
490
                                        // Update the stored addresses for this
3✔
491
                                        // to peer to reflect the new set.
3✔
492
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
493

3✔
494
                                        // If there are no outstanding
3✔
495
                                        // connection requests for this peer
3✔
496
                                        // then our work is done since we are
3✔
497
                                        // not currently trying to connect to
3✔
498
                                        // them.
3✔
499
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
500
                                                s.mu.Unlock()
3✔
501
                                                continue
3✔
502
                                        }
503

504
                                        s.mu.Unlock()
3✔
505

3✔
506
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
507
                                }
508
                        }
509
                }
510
        }()
511

512
        return nil
3✔
513
}
514

515
// CustomMessage is a custom message that is received from a peer.
516
type CustomMessage struct {
517
        // Peer is the peer pubkey
518
        Peer [33]byte
519

520
        // Msg is the custom wire message.
521
        Msg *lnwire.Custom
522
}
523

524
// parseAddr parses an address from its string format to a net.Addr.
525
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
526
        var (
3✔
527
                host string
3✔
528
                port int
3✔
529
        )
3✔
530

3✔
531
        // Split the address into its host and port components.
3✔
532
        h, p, err := net.SplitHostPort(address)
3✔
533
        if err != nil {
3✔
534
                // If a port wasn't specified, we'll assume the address only
×
535
                // contains the host so we'll use the default port.
×
536
                host = address
×
537
                port = defaultPeerPort
×
538
        } else {
3✔
539
                // Otherwise, we'll note both the host and ports.
3✔
540
                host = h
3✔
541
                portNum, err := strconv.Atoi(p)
3✔
542
                if err != nil {
3✔
543
                        return nil, err
×
544
                }
×
545
                port = portNum
3✔
546
        }
547

548
        if tor.IsOnionHost(host) {
3✔
549
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
550
        }
×
551

552
        // If the host is part of a TCP address, we'll use the network
553
        // specific ResolveTCPAddr function in order to resolve these
554
        // addresses over Tor in order to prevent leaking your real IP
555
        // address.
556
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
557
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
558
}
559

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

3✔
565
        return func(a net.Addr) (net.Conn, error) {
6✔
566
                lnAddr := a.(*lnwire.NetAddress)
3✔
567
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
568
        }
3✔
569
}
570

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

3✔
584
        var (
3✔
585
                err         error
3✔
586
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
587

3✔
588
                // We just derived the full descriptor, so we know the public
3✔
589
                // key is set on it.
3✔
590
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
591
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
592
                )
3✔
593
        )
3✔
594

3✔
595
        var serializedPubKey [33]byte
3✔
596
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
597

3✔
598
        netParams := cfg.ActiveNetParams.Params
3✔
599

3✔
600
        // Initialize the sphinx router.
3✔
601
        replayLog := htlcswitch.NewDecayedLog(
3✔
602
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
603
        )
3✔
604
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
605

3✔
606
        writeBufferPool := pool.NewWriteBuffer(
3✔
607
                pool.DefaultWriteBufferGCInterval,
3✔
608
                pool.DefaultWriteBufferExpiryInterval,
3✔
609
        )
3✔
610

3✔
611
        writePool := pool.NewWrite(
3✔
612
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
613
        )
3✔
614

3✔
615
        readBufferPool := pool.NewReadBuffer(
3✔
616
                pool.DefaultReadBufferGCInterval,
3✔
617
                pool.DefaultReadBufferExpiryInterval,
3✔
618
        )
3✔
619

3✔
620
        readPool := pool.NewRead(
3✔
621
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
622
        )
3✔
623

3✔
624
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
625
        // controller, then we'll exit as this is incompatible.
3✔
626
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
627
                implCfg.AuxFundingController.IsNone() {
3✔
628

×
629
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
630
                        "aux controllers")
×
631
        }
×
632

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

656
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
657
        registryConfig := invoices.RegistryConfig{
3✔
658
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
659
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
660
                Clock:                       clock.NewDefaultClock(),
3✔
661
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
662
                AcceptAMP:                   cfg.AcceptAMP,
3✔
663
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
664
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
665
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
666
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
667
        }
3✔
668

3✔
669
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
670

3✔
671
        s := &server{
3✔
672
                cfg:            cfg,
3✔
673
                implCfg:        implCfg,
3✔
674
                graphDB:        dbs.GraphDB,
3✔
675
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
676
                addrSource:     addrSource,
3✔
677
                miscDB:         dbs.ChanStateDB,
3✔
678
                invoicesDB:     dbs.InvoiceDB,
3✔
679
                cc:             cc,
3✔
680
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
681
                writePool:      writePool,
3✔
682
                readPool:       readPool,
3✔
683
                chansToRestore: chansToRestore,
3✔
684

3✔
685
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
686
                        cc.ChainNotifier,
3✔
687
                ),
3✔
688
                channelNotifier: channelnotifier.New(
3✔
689
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
690
                ),
3✔
691

3✔
692
                identityECDH:   nodeKeyECDH,
3✔
693
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
694
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
695

3✔
696
                listenAddrs: listenAddrs,
3✔
697

3✔
698
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
699
                // schedule
3✔
700
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
701

3✔
702
                torController: torController,
3✔
703

3✔
704
                persistentPeers:         make(map[string]bool),
3✔
705
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
706
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
707
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
708
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
709
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
710
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
711
                scheduledPeerConnection: make(map[string]func()),
3✔
712
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
713

3✔
714
                peersByPub:                make(map[string]*peer.Brontide),
3✔
715
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
716
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
717
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
718
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
719

3✔
720
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
721

3✔
722
                customMessageServer: subscribe.NewServer(),
3✔
723

3✔
724
                tlsManager: tlsManager,
3✔
725

3✔
726
                featureMgr: featureMgr,
3✔
727
                quit:       make(chan struct{}),
3✔
728
        }
3✔
729

3✔
730
        // Start the low-level services once they are initialized.
3✔
731
        //
3✔
732
        // TODO(yy): break the server startup into four steps,
3✔
733
        // 1. init the low-level services.
3✔
734
        // 2. start the low-level services.
3✔
735
        // 3. init the high-level services.
3✔
736
        // 4. start the high-level services.
3✔
737
        if err := s.startLowLevelServices(); err != nil {
3✔
738
                return nil, err
×
739
        }
×
740

741
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
742
        if err != nil {
3✔
743
                return nil, err
×
744
        }
×
745

746
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
747
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
748
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
749
        )
3✔
750
        s.invoices = invoices.NewRegistry(
3✔
751
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
752
        )
3✔
753

3✔
754
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
755

3✔
756
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
757
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
758

3✔
759
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
760
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
761
                if err != nil {
3✔
762
                        return err
×
763
                }
×
764

765
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
766

3✔
767
                return nil
3✔
768
        }
769

770
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
771
        if err != nil {
3✔
772
                return nil, err
×
773
        }
×
774

775
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
776
                DB:                   dbs.ChanStateDB,
3✔
777
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
778
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
779
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
780
                LocalChannelClose: func(pubKey []byte,
3✔
781
                        request *htlcswitch.ChanClose) {
6✔
782

3✔
783
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
784
                        if err != nil {
3✔
785
                                srvrLog.Errorf("unable to close channel, peer"+
×
786
                                        " with %v id can't be found: %v",
×
787
                                        pubKey, err,
×
788
                                )
×
789
                                return
×
790
                        }
×
791

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

827
        s.witnessBeacon = newPreimageBeacon(
3✔
828
                dbs.ChanStateDB.NewWitnessCache(),
3✔
829
                s.interceptableSwitch.ForwardPacket,
3✔
830
        )
3✔
831

3✔
832
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
833
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
834
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
835
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
836
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
837
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
838
                MessageSigner:            s.nodeSigner,
3✔
839
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
840
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
841
                DB:                       s.chanStateDB,
3✔
842
                Graph:                    dbs.GraphDB,
3✔
843
        }
3✔
844

3✔
845
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
846
        if err != nil {
3✔
847
                return nil, err
×
848
        }
×
849
        s.chanStatusMgr = chanStatusMgr
3✔
850

3✔
851
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
852
        // port forwarding for users behind a NAT.
3✔
853
        if cfg.NAT {
3✔
854
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
855

×
856
                discoveryTimeout := time.Duration(10 * time.Second)
×
857

×
858
                ctx, cancel := context.WithTimeout(
×
859
                        context.Background(), discoveryTimeout,
×
860
                )
×
861
                defer cancel()
×
862
                upnp, err := nat.DiscoverUPnP(ctx)
×
863
                if err == nil {
×
864
                        s.natTraversal = upnp
×
865
                } else {
×
866
                        // If we were not able to discover a UPnP enabled device
×
867
                        // on the local network, we'll fall back to attempting
×
868
                        // to discover a NAT-PMP enabled device.
×
869
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
870
                                "device on the local network: %v", err)
×
871

×
872
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
873
                                "enabled device")
×
874

×
875
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
876
                        if err != nil {
×
877
                                err := fmt.Errorf("unable to discover a "+
×
878
                                        "NAT-PMP enabled device on the local "+
×
879
                                        "network: %v", err)
×
880
                                srvrLog.Error(err)
×
881
                                return nil, err
×
882
                        }
×
883

884
                        s.natTraversal = pmp
×
885
                }
886
        }
887

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

×
903
                        listenPorts = append(listenPorts, uint16(port))
×
904
                }
×
905

906
                ips, err := s.configurePortForwarding(listenPorts...)
×
907
                if err != nil {
×
908
                        srvrLog.Errorf("Unable to automatically set up port "+
×
909
                                "forwarding using %s: %v",
×
910
                                s.natTraversal.Name(), err)
×
911
                } else {
×
912
                        srvrLog.Infof("Automatically set up port forwarding "+
×
913
                                "using %s to advertise external IP",
×
914
                                s.natTraversal.Name())
×
915
                        externalIPStrings = append(externalIPStrings, ips...)
×
916
                }
×
917
        }
918

919
        // If external IP addresses have been specified, add those to the list
920
        // of this server's addresses.
921
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
922
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
923
                cfg.net.ResolveTCPAddr,
3✔
924
        )
3✔
925
        if err != nil {
3✔
926
                return nil, err
×
927
        }
×
928

929
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
930
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
931

3✔
932
        // We'll now reconstruct a node announcement based on our current
3✔
933
        // configuration so we can send it out as a sort of heart beat within
3✔
934
        // the network.
3✔
935
        //
3✔
936
        // We'll start by parsing the node color from configuration.
3✔
937
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
938
        if err != nil {
3✔
939
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
940
                return nil, err
×
941
        }
×
942

943
        // If no alias is provided, default to first 10 characters of public
944
        // key.
945
        alias := cfg.Alias
3✔
946
        if alias == "" {
6✔
947
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
948
        }
3✔
949
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
950
        if err != nil {
3✔
951
                return nil, err
×
952
        }
×
953

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

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

973
        // If the above cases are not matched, then we have an unhandled non
974
        // nil error.
975
        default:
×
976
                return nil, fmt.Errorf("unable to fetch source node: %w", err)
×
977
        }
978

979
        selfNode := &models.LightningNode{
3✔
980
                HaveNodeAnnouncement: true,
3✔
981
                LastUpdate:           nodeLastUpdate,
3✔
982
                Addresses:            selfAddrs,
3✔
983
                Alias:                nodeAlias.String(),
3✔
984
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
985
                Color:                color,
3✔
986
        }
3✔
987
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
988

3✔
989
        // Based on the disk representation of the node announcement generated
3✔
990
        // above, we'll generate a node announcement that can go out on the
3✔
991
        // network so we can properly sign it.
3✔
992
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
993
        if err != nil {
3✔
994
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
995
        }
×
996

997
        // With the announcement generated, we'll sign it to properly
998
        // authenticate the message on the network.
999
        authSig, err := netann.SignAnnouncement(
3✔
1000
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
1001
        )
3✔
1002
        if err != nil {
3✔
1003
                return nil, fmt.Errorf("unable to generate signature for "+
×
1004
                        "self node announcement: %v", err)
×
1005
        }
×
1006
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
1007
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
1008
                selfNode.AuthSigBytes,
3✔
1009
        )
3✔
1010
        if err != nil {
3✔
1011
                return nil, err
×
1012
        }
×
1013

1014
        // Finally, we'll update the representation on disk, and update our
1015
        // cached in-memory version as well.
1016
        if err := dbs.GraphDB.SetSourceNode(ctx, selfNode); err != nil {
3✔
1017
                return nil, fmt.Errorf("can't set self node: %w", err)
×
1018
        }
×
1019
        s.currentNodeAnn = nodeAnn
3✔
1020

3✔
1021
        // The router will get access to the payment ID sequencer, such that it
3✔
1022
        // can generate unique payment IDs.
3✔
1023
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
1024
        if err != nil {
3✔
1025
                return nil, err
×
1026
        }
×
1027

1028
        // Instantiate mission control with config from the sub server.
1029
        //
1030
        // TODO(joostjager): When we are further in the process of moving to sub
1031
        // servers, the mission control instance itself can be moved there too.
1032
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1033

3✔
1034
        // We only initialize a probability estimator if there's no custom one.
3✔
1035
        var estimator routing.Estimator
3✔
1036
        if cfg.Estimator != nil {
3✔
1037
                estimator = cfg.Estimator
×
1038
        } else {
3✔
1039
                switch routingConfig.ProbabilityEstimatorType {
3✔
1040
                case routing.AprioriEstimatorName:
3✔
1041
                        aCfg := routingConfig.AprioriConfig
3✔
1042
                        aprioriConfig := routing.AprioriConfig{
3✔
1043
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1044
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1045
                                AprioriWeight:         aCfg.Weight,
3✔
1046
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1047
                        }
3✔
1048

3✔
1049
                        estimator, err = routing.NewAprioriEstimator(
3✔
1050
                                aprioriConfig,
3✔
1051
                        )
3✔
1052
                        if err != nil {
3✔
1053
                                return nil, err
×
1054
                        }
×
1055

1056
                case routing.BimodalEstimatorName:
×
1057
                        bCfg := routingConfig.BimodalConfig
×
1058
                        bimodalConfig := routing.BimodalConfig{
×
1059
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1060
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1061
                                        bCfg.Scale,
×
1062
                                ),
×
1063
                                BimodalDecayTime: bCfg.DecayTime,
×
1064
                        }
×
1065

×
1066
                        estimator, err = routing.NewBimodalEstimator(
×
1067
                                bimodalConfig,
×
1068
                        )
×
1069
                        if err != nil {
×
1070
                                return nil, err
×
1071
                        }
×
1072

1073
                default:
×
1074
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1075
                                routingConfig.ProbabilityEstimatorType)
×
1076
                }
1077
        }
1078

1079
        mcCfg := &routing.MissionControlConfig{
3✔
1080
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1081
                Estimator:               estimator,
3✔
1082
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1083
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1084
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1085
        }
3✔
1086

3✔
1087
        s.missionController, err = routing.NewMissionController(
3✔
1088
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1089
        )
3✔
1090
        if err != nil {
3✔
1091
                return nil, fmt.Errorf("can't create mission control "+
×
1092
                        "manager: %w", err)
×
1093
        }
×
1094
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1095
                routing.DefaultMissionControlNamespace,
3✔
1096
        )
3✔
1097
        if err != nil {
3✔
1098
                return nil, fmt.Errorf("can't create mission control in the "+
×
1099
                        "default namespace: %w", err)
×
1100
        }
×
1101

1102
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1103
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1104
                int64(routingConfig.AttemptCost),
3✔
1105
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1106
                routingConfig.MinRouteProbability)
3✔
1107

3✔
1108
        pathFindingConfig := routing.PathFindingConfig{
3✔
1109
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1110
                        routingConfig.AttemptCost,
3✔
1111
                ),
3✔
1112
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1113
                MinProbability: routingConfig.MinRouteProbability,
3✔
1114
        }
3✔
1115

3✔
1116
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
3✔
1117
        if err != nil {
3✔
1118
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1119
        }
×
1120
        paymentSessionSource := &routing.SessionSource{
3✔
1121
                GraphSessionFactory: dbs.GraphDB,
3✔
1122
                SourceNode:          sourceNode,
3✔
1123
                MissionControl:      s.defaultMC,
3✔
1124
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1125
                PathFindingConfig:   pathFindingConfig,
3✔
1126
        }
3✔
1127

3✔
1128
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1129

3✔
1130
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1131

3✔
1132
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1133
                cfg.Routing.StrictZombiePruning
3✔
1134

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

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

1172
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1173
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1174
        if err != nil {
3✔
1175
                return nil, err
×
1176
        }
×
1177
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1178
        if err != nil {
3✔
1179
                return nil, err
×
1180
        }
×
1181

1182
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1183

3✔
1184
        s.authGossiper = discovery.New(discovery.Config{
3✔
1185
                Graph:                 s.graphBuilder,
3✔
1186
                ChainIO:               s.cc.ChainIO,
3✔
1187
                Notifier:              s.cc.ChainNotifier,
3✔
1188
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1189
                Broadcast:             s.BroadcastMessage,
3✔
1190
                ChanSeries:            chanSeries,
3✔
1191
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1192
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1193
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1194
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1195
                        error) {
3✔
1196

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

1228
        accessCfg := &accessManConfig{
3✔
1229
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1230
                        error) {
6✔
1231

3✔
1232
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1233
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1234
                                genesisHash[:],
3✔
1235
                        )
3✔
1236
                },
3✔
1237
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1238
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1239
        }
1240

1241
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1242
        if err != nil {
3✔
1243
                return nil, err
×
1244
        }
×
1245

1246
        s.peerAccessMan = peerAccessMan
3✔
1247

3✔
1248
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1249
        //nolint:ll
3✔
1250
        s.localChanMgr = &localchans.Manager{
3✔
1251
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1252
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1253
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1254
                        *models.ChannelEdgePolicy) error) error {
6✔
1255

3✔
1256
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1257
                                func(c *models.ChannelEdgeInfo,
3✔
1258
                                        e *models.ChannelEdgePolicy,
3✔
1259
                                        _ *models.ChannelEdgePolicy) error {
6✔
1260

3✔
1261
                                        // NOTE: The invoked callback here may
3✔
1262
                                        // receive a nil channel policy.
3✔
1263
                                        return cb(c, e)
3✔
1264
                                },
3✔
1265
                        )
1266
                },
1267
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1268
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1269
                FetchChannel:              s.chanStateDB.FetchChannel,
1270
                AddEdge: func(ctx context.Context,
1271
                        edge *models.ChannelEdgeInfo) error {
×
1272

×
1273
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1274
                },
×
1275
        }
1276

1277
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1278
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1279
        )
3✔
1280
        if err != nil {
3✔
1281
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1282
                return nil, err
×
1283
        }
×
1284

1285
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1286
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1287
        )
3✔
1288
        if err != nil {
3✔
1289
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1290
                return nil, err
×
1291
        }
×
1292

1293
        aggregator := sweep.NewBudgetAggregator(
3✔
1294
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1295
                s.implCfg.AuxSweeper,
3✔
1296
        )
3✔
1297

3✔
1298
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1299
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1300
                Wallet:     cc.Wallet,
3✔
1301
                Estimator:  cc.FeeEstimator,
3✔
1302
                Notifier:   cc.ChainNotifier,
3✔
1303
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1304
        })
3✔
1305

3✔
1306
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1307
                FeeEstimator: cc.FeeEstimator,
3✔
1308
                GenSweepScript: newSweepPkScriptGen(
3✔
1309
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1310
                ),
3✔
1311
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1312
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1313
                Mempool:              cc.MempoolNotifier,
3✔
1314
                Notifier:             cc.ChainNotifier,
3✔
1315
                Store:                sweeperStore,
3✔
1316
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1317
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1318
                Aggregator:           aggregator,
3✔
1319
                Publisher:            s.txPublisher,
3✔
1320
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1321
        })
3✔
1322

3✔
1323
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1324
                ChainIO:             cc.ChainIO,
3✔
1325
                ConfDepth:           1,
3✔
1326
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1327
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1328
                Notifier:            cc.ChainNotifier,
3✔
1329
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1330
                Store:               utxnStore,
3✔
1331
                SweepInput:          s.sweeper.SweepInput,
3✔
1332
                Budget:              s.cfg.Sweeper.Budget,
3✔
1333
        })
3✔
1334

3✔
1335
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1336
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1337
                closureType contractcourt.ChannelCloseType) {
6✔
1338
                // TODO(conner): Properly respect the update and error channels
3✔
1339
                // returned by CloseLink.
3✔
1340

3✔
1341
                // Instruct the switch to close the channel.  Provide no close out
3✔
1342
                // delivery script or target fee per kw because user input is not
3✔
1343
                // available when the remote peer closes the channel.
3✔
1344
                s.htlcSwitch.CloseLink(
3✔
1345
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1346
                )
3✔
1347
        }
3✔
1348

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

3✔
1353
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1354
                &contractcourt.BreachConfig{
3✔
1355
                        CloseLink: closeLink,
3✔
1356
                        DB:        s.chanStateDB,
3✔
1357
                        Estimator: s.cc.FeeEstimator,
3✔
1358
                        GenSweepScript: newSweepPkScriptGen(
3✔
1359
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1360
                        ),
3✔
1361
                        Notifier:           cc.ChainNotifier,
3✔
1362
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1363
                        ContractBreaches:   contractBreaches,
3✔
1364
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1365
                        Store: contractcourt.NewRetributionStore(
3✔
1366
                                dbs.ChanStateDB,
3✔
1367
                        ),
3✔
1368
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1369
                },
3✔
1370
        )
3✔
1371

3✔
1372
        //nolint:ll
3✔
1373
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1374
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1375
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1376
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1377
                NewSweepAddr: func() ([]byte, error) {
3✔
1378
                        addr, err := newSweepPkScriptGen(
×
1379
                                cc.Wallet, netParams,
×
1380
                        )().Unpack()
×
1381
                        if err != nil {
×
1382
                                return nil, err
×
1383
                        }
×
1384

1385
                        return addr.DeliveryAddress, nil
×
1386
                },
1387
                PublishTx: cc.Wallet.PublishTransaction,
1388
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1389
                        for _, msg := range msgs {
6✔
1390
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1391
                                if err != nil {
3✔
1392
                                        return err
×
1393
                                }
×
1394
                        }
1395
                        return nil
3✔
1396
                },
1397
                IncubateOutputs: func(chanPoint wire.OutPoint,
1398
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1399
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1400
                        broadcastHeight uint32,
1401
                        deadlineHeight fn.Option[int32]) error {
3✔
1402

3✔
1403
                        return s.utxoNursery.IncubateOutputs(
3✔
1404
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1405
                                broadcastHeight, deadlineHeight,
3✔
1406
                        )
3✔
1407
                },
3✔
1408
                PreimageDB:   s.witnessBeacon,
1409
                Notifier:     cc.ChainNotifier,
1410
                Mempool:      cc.MempoolNotifier,
1411
                Signer:       cc.Wallet.Cfg.Signer,
1412
                FeeEstimator: cc.FeeEstimator,
1413
                ChainIO:      cc.ChainIO,
1414
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1415
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1416
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1417
                        return nil
3✔
1418
                },
3✔
1419
                IsOurAddress: cc.Wallet.IsOurAddress,
1420
                ContractBreach: func(chanPoint wire.OutPoint,
1421
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1422

3✔
1423
                        // processACK will handle the BreachArbitrator ACKing
3✔
1424
                        // the event.
3✔
1425
                        finalErr := make(chan error, 1)
3✔
1426
                        processACK := func(brarErr error) {
6✔
1427
                                if brarErr != nil {
3✔
1428
                                        finalErr <- brarErr
×
1429
                                        return
×
1430
                                }
×
1431

1432
                                // If the BreachArbitrator successfully handled
1433
                                // the event, we can signal that the handoff
1434
                                // was successful.
1435
                                finalErr <- nil
3✔
1436
                        }
1437

1438
                        event := &contractcourt.ContractBreachEvent{
3✔
1439
                                ChanPoint:         chanPoint,
3✔
1440
                                ProcessACK:        processACK,
3✔
1441
                                BreachRetribution: breachRet,
3✔
1442
                        }
3✔
1443

3✔
1444
                        // Send the contract breach event to the
3✔
1445
                        // BreachArbitrator.
3✔
1446
                        select {
3✔
1447
                        case contractBreaches <- event:
3✔
1448
                        case <-s.quit:
×
1449
                                return ErrServerShuttingDown
×
1450
                        }
1451

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

1477
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1478
                QueryIncomingCircuit: func(
1479
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1480

3✔
1481
                        // Get the circuit map.
3✔
1482
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1483

3✔
1484
                        // Lookup the outgoing circuit.
3✔
1485
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1486
                        if pc == nil {
5✔
1487
                                return nil
2✔
1488
                        }
2✔
1489

1490
                        return &pc.Incoming
3✔
1491
                },
1492
                AuxLeafStore: implCfg.AuxLeafStore,
1493
                AuxSigner:    implCfg.AuxSigner,
1494
                AuxResolver:  implCfg.AuxContractResolver,
1495
        }, dbs.ChanStateDB)
1496

1497
        // Select the configuration and funding parameters for Bitcoin.
1498
        chainCfg := cfg.Bitcoin
3✔
1499
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1500
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1501

3✔
1502
        var chanIDSeed [32]byte
3✔
1503
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1504
                return nil, err
×
1505
        }
×
1506

1507
        // Wrap the DeleteChannelEdges method so that the funding manager can
1508
        // use it without depending on several layers of indirection.
1509
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1510
                *models.ChannelEdgePolicy, error) {
6✔
1511

3✔
1512
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1513
                        scid.ToUint64(),
3✔
1514
                )
3✔
1515
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1516
                        // This is unlikely but there is a slim chance of this
×
1517
                        // being hit if lnd was killed via SIGKILL and the
×
1518
                        // funding manager was stepping through the delete
×
1519
                        // alias edge logic.
×
1520
                        return nil, nil
×
1521
                } else if err != nil {
3✔
1522
                        return nil, err
×
1523
                }
×
1524

1525
                // Grab our key to find our policy.
1526
                var ourKey [33]byte
3✔
1527
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1528

3✔
1529
                var ourPolicy *models.ChannelEdgePolicy
3✔
1530
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1531
                        ourPolicy = e1
3✔
1532
                } else {
6✔
1533
                        ourPolicy = e2
3✔
1534
                }
3✔
1535

1536
                if ourPolicy == nil {
3✔
1537
                        // Something is wrong, so return an error.
×
1538
                        return nil, fmt.Errorf("we don't have an edge")
×
1539
                }
×
1540

1541
                err = s.graphDB.DeleteChannelEdges(
3✔
1542
                        false, false, scid.ToUint64(),
3✔
1543
                )
3✔
1544
                return ourPolicy, err
3✔
1545
        }
1546

1547
        // For the reservationTimeout and the zombieSweeperInterval different
1548
        // values are set in case we are in a dev environment so enhance test
1549
        // capacilities.
1550
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1551
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1552

3✔
1553
        // Get the development config for funding manager. If we are not in
3✔
1554
        // development mode, this would be nil.
3✔
1555
        var devCfg *funding.DevConfig
3✔
1556
        if lncfg.IsDevBuild() {
6✔
1557
                devCfg = &funding.DevConfig{
3✔
1558
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1559
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1560
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1561
                }
3✔
1562

3✔
1563
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1564
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1565

3✔
1566
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1567
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1568
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1569
        }
3✔
1570

1571
        //nolint:ll
1572
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1573
                Dev:                devCfg,
3✔
1574
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1575
                IDKey:              nodeKeyDesc.PubKey,
3✔
1576
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1577
                Wallet:             cc.Wallet,
3✔
1578
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1579
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1580
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1581
                },
3✔
1582
                Notifier:     cc.ChainNotifier,
1583
                ChannelDB:    s.chanStateDB,
1584
                FeeEstimator: cc.FeeEstimator,
1585
                SignMessage:  cc.MsgSigner.SignMessage,
1586
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1587
                        error) {
3✔
1588

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

3✔
1609
                        // In case the user has explicitly specified
3✔
1610
                        // a default value for the number of
3✔
1611
                        // confirmations, we use it.
3✔
1612
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1613
                        if defaultConf != 0 {
6✔
1614
                                return defaultConf
3✔
1615
                        }
3✔
1616

1617
                        minConf := uint64(3)
×
1618
                        maxConf := uint64(6)
×
1619

×
1620
                        // If this is a wumbo channel, then we'll require the
×
1621
                        // max amount of confirmations.
×
1622
                        if chanAmt > MaxFundingAmount {
×
1623
                                return uint16(maxConf)
×
1624
                        }
×
1625

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

3✔
1648
                        // In case the user has explicitly specified
3✔
1649
                        // a default value for the remote delay, we
3✔
1650
                        // use it.
3✔
1651
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1652
                        if defaultDelay > 0 {
6✔
1653
                                return defaultDelay
3✔
1654
                        }
3✔
1655

1656
                        // If this is a wumbo channel, then we'll require the
1657
                        // max value.
1658
                        if chanAmt > MaxFundingAmount {
×
1659
                                return maxRemoteDelay
×
1660
                        }
×
1661

1662
                        // If not we scale according to channel size.
1663
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1664
                                chanAmt / MaxFundingAmount)
×
1665
                        if delay < minRemoteDelay {
×
1666
                                delay = minRemoteDelay
×
1667
                        }
×
1668
                        if delay > maxRemoteDelay {
×
1669
                                delay = maxRemoteDelay
×
1670
                        }
×
1671
                        return delay
×
1672
                },
1673
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1674
                        peerKey *btcec.PublicKey) error {
3✔
1675

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

3✔
1689
                        // With that taken care of, we'll send this channel to
3✔
1690
                        // the chain arb so it can react to on-chain events.
3✔
1691
                        return s.chainArb.WatchNewChannel(channel)
3✔
1692
                },
1693
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1694
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1695
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1696
                },
3✔
1697
                RequiredRemoteChanReserve: func(chanAmt,
1698
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1699

3✔
1700
                        // By default, we'll require the remote peer to maintain
3✔
1701
                        // at least 1% of the total channel capacity at all
3✔
1702
                        // times. If this value ends up dipping below the dust
3✔
1703
                        // limit, then we'll use the dust limit itself as the
3✔
1704
                        // reserve as required by BOLT #2.
3✔
1705
                        reserve := chanAmt / 100
3✔
1706
                        if reserve < dustLimit {
6✔
1707
                                reserve = dustLimit
3✔
1708
                        }
3✔
1709

1710
                        return reserve
3✔
1711
                },
1712
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1713
                        // By default, we'll allow the remote peer to fully
3✔
1714
                        // utilize the full bandwidth of the channel, minus our
3✔
1715
                        // required reserve.
3✔
1716
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1717
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1718
                },
3✔
1719
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1720
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1721
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1722
                        }
3✔
1723

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

1753
        // Next, we'll assemble the sub-system that will maintain an on-disk
1754
        // static backup of the latest channel state.
1755
        chanNotifier := &channelNotifier{
3✔
1756
                chanNotifier: s.channelNotifier,
3✔
1757
                addrs:        s.addrSource,
3✔
1758
        }
3✔
1759
        backupFile := chanbackup.NewMultiFile(
3✔
1760
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1761
        )
3✔
1762
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1763
                ctx, s.chanStateDB, s.addrSource,
3✔
1764
        )
3✔
1765
        if err != nil {
3✔
1766
                return nil, err
×
1767
        }
×
1768
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1769
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1770
        )
3✔
1771
        if err != nil {
3✔
1772
                return nil, err
×
1773
        }
×
1774

1775
        // Assemble a peer notifier which will provide clients with subscriptions
1776
        // to peer online and offline events.
1777
        s.peerNotifier = peernotifier.New()
3✔
1778

3✔
1779
        // Create a channel event store which monitors all open channels.
3✔
1780
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1781
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1782
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1783
                },
3✔
1784
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1785
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1786
                },
3✔
1787
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1788
                Clock:           clock.NewDefaultClock(),
1789
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1790
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1791
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1792
        })
1793

1794
        if cfg.WtClient.Active {
6✔
1795
                policy := wtpolicy.DefaultPolicy()
3✔
1796
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1797

3✔
1798
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1799
                // protocol operations on sat/kw.
3✔
1800
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1801
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1802
                )
3✔
1803

3✔
1804
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1805

3✔
1806
                if err := policy.Validate(); err != nil {
3✔
1807
                        return nil, err
×
1808
                }
×
1809

1810
                // authDial is the wrapper around the btrontide.Dial for the
1811
                // watchtower.
1812
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1813
                        netAddr *lnwire.NetAddress,
3✔
1814
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1815

3✔
1816
                        return brontide.Dial(
3✔
1817
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1818
                        )
3✔
1819
                }
3✔
1820

1821
                // buildBreachRetribution is a call-back that can be used to
1822
                // query the BreachRetribution info and channel type given a
1823
                // channel ID and commitment height.
1824
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1825
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1826
                        channeldb.ChannelType, error) {
6✔
1827

3✔
1828
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1829
                                nil, chanID,
3✔
1830
                        )
3✔
1831
                        if err != nil {
3✔
1832
                                return nil, 0, err
×
1833
                        }
×
1834

1835
                        br, err := lnwallet.NewBreachRetribution(
3✔
1836
                                channel, commitHeight, 0, nil,
3✔
1837
                                implCfg.AuxLeafStore,
3✔
1838
                                implCfg.AuxContractResolver,
3✔
1839
                        )
3✔
1840
                        if err != nil {
3✔
1841
                                return nil, 0, err
×
1842
                        }
×
1843

1844
                        return br, channel.ChanType, nil
3✔
1845
                }
1846

1847
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1848

3✔
1849
                // Copy the policy for legacy channels and set the blob flag
3✔
1850
                // signalling support for anchor channels.
3✔
1851
                anchorPolicy := policy
3✔
1852
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1853

3✔
1854
                // Copy the policy for legacy channels and set the blob flag
3✔
1855
                // signalling support for taproot channels.
3✔
1856
                taprootPolicy := policy
3✔
1857
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1858
                        blob.FlagTaprootChannel,
3✔
1859
                )
3✔
1860

3✔
1861
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1862
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1863
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1864
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1865
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1866
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1867
                                error) {
6✔
1868

3✔
1869
                                return s.channelNotifier.
3✔
1870
                                        SubscribeChannelEvents()
3✔
1871
                        },
3✔
1872
                        Signer: cc.Wallet.Cfg.Signer,
1873
                        NewAddress: func() ([]byte, error) {
3✔
1874
                                addr, err := newSweepPkScriptGen(
3✔
1875
                                        cc.Wallet, netParams,
3✔
1876
                                )().Unpack()
3✔
1877
                                if err != nil {
3✔
1878
                                        return nil, err
×
1879
                                }
×
1880

1881
                                return addr.DeliveryAddress, nil
3✔
1882
                        },
1883
                        SecretKeyRing:      s.cc.KeyRing,
1884
                        Dial:               cfg.net.Dial,
1885
                        AuthDial:           authDial,
1886
                        DB:                 dbs.TowerClientDB,
1887
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1888
                        MinBackoff:         10 * time.Second,
1889
                        MaxBackoff:         5 * time.Minute,
1890
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1891
                }, policy, anchorPolicy, taprootPolicy)
1892
                if err != nil {
3✔
1893
                        return nil, err
×
1894
                }
×
1895
        }
1896

1897
        if len(cfg.ExternalHosts) != 0 {
3✔
1898
                advertisedIPs := make(map[string]struct{})
×
1899
                for _, addr := range s.currentNodeAnn.Addresses {
×
1900
                        advertisedIPs[addr.String()] = struct{}{}
×
1901
                }
×
1902

1903
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1904
                        Hosts:         cfg.ExternalHosts,
×
1905
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1906
                        LookupHost: func(host string) (net.Addr, error) {
×
1907
                                return lncfg.ParseAddressString(
×
1908
                                        host, strconv.Itoa(defaultPeerPort),
×
1909
                                        cfg.net.ResolveTCPAddr,
×
1910
                                )
×
1911
                        },
×
1912
                        AdvertisedIPs: advertisedIPs,
1913
                        AnnounceNewIPs: netann.IPAnnouncer(
1914
                                func(modifier ...netann.NodeAnnModifier) (
1915
                                        lnwire.NodeAnnouncement, error) {
×
1916

×
1917
                                        return s.genNodeAnnouncement(
×
1918
                                                nil, modifier...,
×
1919
                                        )
×
1920
                                }),
×
1921
                })
1922
        }
1923

1924
        // Create liveness monitor.
1925
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1926

3✔
1927
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1928
        for i, listenAddr := range listenAddrs {
6✔
1929
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1930
                // doesn't need to call the general lndResolveTCP function
3✔
1931
                // since we are resolving a local address.
3✔
1932

3✔
1933
                // RESOLVE: We are actually partially accepting inbound
3✔
1934
                // connection requests when we call NewListener.
3✔
1935
                listeners[i], err = brontide.NewListener(
3✔
1936
                        nodeKeyECDH, listenAddr.String(),
3✔
1937
                        // TODO(yy): remove this check and unify the inbound
3✔
1938
                        // connection check inside `InboundPeerConnected`.
3✔
1939
                        s.peerAccessMan.checkAcceptIncomingConn,
3✔
1940
                )
3✔
1941
                if err != nil {
3✔
1942
                        return nil, err
×
1943
                }
×
1944
        }
1945

1946
        // Create the connection manager which will be responsible for
1947
        // maintaining persistent outbound connections and also accepting new
1948
        // incoming connections
1949
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1950
                Listeners:      listeners,
3✔
1951
                OnAccept:       s.InboundPeerConnected,
3✔
1952
                RetryDuration:  time.Second * 5,
3✔
1953
                TargetOutbound: 100,
3✔
1954
                Dial: noiseDial(
3✔
1955
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1956
                ),
3✔
1957
                OnConnection: s.OutboundPeerConnected,
3✔
1958
        })
3✔
1959
        if err != nil {
3✔
1960
                return nil, err
×
1961
        }
×
1962
        s.connMgr = cmgr
3✔
1963

3✔
1964
        // Finally, register the subsystems in blockbeat.
3✔
1965
        s.registerBlockConsumers()
3✔
1966

3✔
1967
        return s, nil
3✔
1968
}
1969

1970
// UpdateRoutingConfig is a callback function to update the routing config
1971
// values in the main cfg.
1972
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1973
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1974

3✔
1975
        switch c := cfg.Estimator.Config().(type) {
3✔
1976
        case routing.AprioriConfig:
3✔
1977
                routerCfg.ProbabilityEstimatorType =
3✔
1978
                        routing.AprioriEstimatorName
3✔
1979

3✔
1980
                targetCfg := routerCfg.AprioriConfig
3✔
1981
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1982
                targetCfg.Weight = c.AprioriWeight
3✔
1983
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1984
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1985

1986
        case routing.BimodalConfig:
3✔
1987
                routerCfg.ProbabilityEstimatorType =
3✔
1988
                        routing.BimodalEstimatorName
3✔
1989

3✔
1990
                targetCfg := routerCfg.BimodalConfig
3✔
1991
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1992
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1993
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1994
        }
1995

1996
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1997
}
1998

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

2018
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2019
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2020
// may differ from what is on disk.
2021
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2022
        error) {
3✔
2023

3✔
2024
        data, err := u.DataToSign()
3✔
2025
        if err != nil {
3✔
2026
                return nil, err
×
2027
        }
×
2028

2029
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2030
}
2031

2032
// createLivenessMonitor creates a set of health checks using our configured
2033
// values and uses these checks to create a liveness monitor. Available
2034
// health checks,
2035
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2036
//   - diskCheck
2037
//   - tlsHealthCheck
2038
//   - torController, only created when tor is enabled.
2039
//
2040
// If a health check has been disabled by setting attempts to 0, our monitor
2041
// will not run it.
2042
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2043
        leaderElector cluster.LeaderElector) {
3✔
2044

3✔
2045
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2046
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2047
                srvrLog.Info("Disabling chain backend checks for " +
×
2048
                        "nochainbackend mode")
×
2049

×
2050
                chainBackendAttempts = 0
×
2051
        }
×
2052

2053
        chainHealthCheck := healthcheck.NewObservation(
3✔
2054
                "chain backend",
3✔
2055
                cc.HealthCheck,
3✔
2056
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2057
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2058
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2059
                chainBackendAttempts,
3✔
2060
        )
3✔
2061

3✔
2062
        diskCheck := healthcheck.NewObservation(
3✔
2063
                "disk space",
3✔
2064
                func() error {
3✔
2065
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2066
                                cfg.LndDir,
×
2067
                        )
×
2068
                        if err != nil {
×
2069
                                return err
×
2070
                        }
×
2071

2072
                        // If we have more free space than we require,
2073
                        // we return a nil error.
2074
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2075
                                return nil
×
2076
                        }
×
2077

2078
                        return fmt.Errorf("require: %v free space, got: %v",
×
2079
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2080
                                free)
×
2081
                },
2082
                cfg.HealthChecks.DiskCheck.Interval,
2083
                cfg.HealthChecks.DiskCheck.Timeout,
2084
                cfg.HealthChecks.DiskCheck.Backoff,
2085
                cfg.HealthChecks.DiskCheck.Attempts,
2086
        )
2087

2088
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2089
                "tls",
3✔
2090
                func() error {
3✔
2091
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2092
                                s.cc.KeyRing,
×
2093
                        )
×
2094
                        if err != nil {
×
2095
                                return err
×
2096
                        }
×
2097
                        if expired {
×
2098
                                return fmt.Errorf("TLS certificate is "+
×
2099
                                        "expired as of %v", expTime)
×
2100
                        }
×
2101

2102
                        // If the certificate is not outdated, no error needs
2103
                        // to be returned
2104
                        return nil
×
2105
                },
2106
                cfg.HealthChecks.TLSCheck.Interval,
2107
                cfg.HealthChecks.TLSCheck.Timeout,
2108
                cfg.HealthChecks.TLSCheck.Backoff,
2109
                cfg.HealthChecks.TLSCheck.Attempts,
2110
        )
2111

2112
        checks := []*healthcheck.Observation{
3✔
2113
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2114
        }
3✔
2115

3✔
2116
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2117
        if s.torController != nil {
3✔
2118
                torConnectionCheck := healthcheck.NewObservation(
×
2119
                        "tor connection",
×
2120
                        func() error {
×
2121
                                return healthcheck.CheckTorServiceStatus(
×
2122
                                        s.torController,
×
2123
                                        func() error {
×
2124
                                                return s.createNewHiddenService(
×
2125
                                                        context.TODO(),
×
2126
                                                )
×
2127
                                        },
×
2128
                                )
2129
                        },
2130
                        cfg.HealthChecks.TorConnection.Interval,
2131
                        cfg.HealthChecks.TorConnection.Timeout,
2132
                        cfg.HealthChecks.TorConnection.Backoff,
2133
                        cfg.HealthChecks.TorConnection.Attempts,
2134
                )
2135
                checks = append(checks, torConnectionCheck)
×
2136
        }
2137

2138
        // If remote signing is enabled, add the healthcheck for the remote
2139
        // signing RPC interface.
2140
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2141
                // Because we have two cascading timeouts here, we need to add
3✔
2142
                // some slack to the "outer" one of them in case the "inner"
3✔
2143
                // returns exactly on time.
3✔
2144
                overhead := time.Millisecond * 10
3✔
2145

3✔
2146
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2147
                        "remote signer connection",
3✔
2148
                        rpcwallet.HealthCheck(
3✔
2149
                                s.cfg.RemoteSigner,
3✔
2150

3✔
2151
                                // For the health check we might to be even
3✔
2152
                                // stricter than the initial/normal connect, so
3✔
2153
                                // we use the health check timeout here.
3✔
2154
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2155
                        ),
3✔
2156
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2157
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2158
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2159
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2160
                )
3✔
2161
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2162
        }
3✔
2163

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

×
2182
                                leader, err := leaderElector.IsLeader(
×
2183
                                        timeoutCtx,
×
2184
                                )
×
2185
                                if err != nil {
×
2186
                                        return fmt.Errorf("unable to check if "+
×
2187
                                                "still leader: %v", err)
×
2188
                                }
×
2189

2190
                                if !leader {
×
2191
                                        srvrLog.Debug("Not the current leader")
×
2192
                                        return fmt.Errorf("not the current " +
×
2193
                                                "leader")
×
2194
                                }
×
2195

2196
                                return nil
×
2197
                        },
2198
                        cfg.HealthChecks.LeaderCheck.Interval,
2199
                        cfg.HealthChecks.LeaderCheck.Timeout,
2200
                        cfg.HealthChecks.LeaderCheck.Backoff,
2201
                        cfg.HealthChecks.LeaderCheck.Attempts,
2202
                )
2203

2204
                checks = append(checks, leaderCheck)
×
2205
        }
2206

2207
        // If we have not disabled all of our health checks, we create a
2208
        // liveness monitor with our configured checks.
2209
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2210
                &healthcheck.Config{
3✔
2211
                        Checks:   checks,
3✔
2212
                        Shutdown: srvrLog.Criticalf,
3✔
2213
                },
3✔
2214
        )
3✔
2215
}
2216

2217
// Started returns true if the server has been started, and false otherwise.
2218
// NOTE: This function is safe for concurrent access.
2219
func (s *server) Started() bool {
3✔
2220
        return atomic.LoadInt32(&s.active) != 0
3✔
2221
}
3✔
2222

2223
// cleaner is used to aggregate "cleanup" functions during an operation that
2224
// starts several subsystems. In case one of the subsystem fails to start
2225
// and a proper resource cleanup is required, the "run" method achieves this
2226
// by running all these added "cleanup" functions.
2227
type cleaner []func() error
2228

2229
// add is used to add a cleanup function to be called when
2230
// the run function is executed.
2231
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2232
        return append(c, cleanup)
3✔
2233
}
3✔
2234

2235
// run is used to run all the previousely added cleanup functions.
2236
func (c cleaner) run() {
×
2237
        for i := len(c) - 1; i >= 0; i-- {
×
2238
                if err := c[i](); err != nil {
×
2239
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2240
                }
×
2241
        }
2242
}
2243

2244
// startLowLevelServices starts the low-level services of the server. These
2245
// services must be started successfully before running the main server. The
2246
// services are,
2247
// 1. the chain notifier.
2248
//
2249
// TODO(yy): identify and add more low-level services here.
2250
func (s *server) startLowLevelServices() error {
3✔
2251
        var startErr error
3✔
2252

3✔
2253
        cleanup := cleaner{}
3✔
2254

3✔
2255
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2256
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2257
                startErr = err
×
2258
        }
×
2259

2260
        if startErr != nil {
3✔
2261
                cleanup.run()
×
2262
        }
×
2263

2264
        return startErr
3✔
2265
}
2266

2267
// Start starts the main daemon server, all requested listeners, and any helper
2268
// goroutines.
2269
// NOTE: This function is safe for concurrent access.
2270
//
2271
//nolint:funlen
2272
func (s *server) Start(ctx context.Context) error {
3✔
2273
        // Get the current blockbeat.
3✔
2274
        beat, err := s.getStartingBeat()
3✔
2275
        if err != nil {
3✔
2276
                return err
×
2277
        }
×
2278

2279
        var startErr error
3✔
2280

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

3✔
2286
        s.start.Do(func() {
6✔
2287
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2288
                if err := s.customMessageServer.Start(); err != nil {
3✔
2289
                        startErr = err
×
2290
                        return
×
2291
                }
×
2292

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

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

2309
                // Start the notification server. This is used so channel
2310
                // management goroutines can be notified when a funding
2311
                // transaction reaches a sufficient number of confirmations, or
2312
                // when the input for the funding transaction is spent in an
2313
                // attempt at an uncooperative close by the counterparty.
2314
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2315
                if err := s.sigPool.Start(); err != nil {
3✔
2316
                        startErr = err
×
2317
                        return
×
2318
                }
×
2319

2320
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2321
                if err := s.writePool.Start(); err != nil {
3✔
2322
                        startErr = err
×
2323
                        return
×
2324
                }
×
2325

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

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

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

2344
                cleanup = cleanup.add(func() error {
3✔
2345
                        return s.peerNotifier.Stop()
×
2346
                })
×
2347
                if err := s.peerNotifier.Start(); err != nil {
3✔
2348
                        startErr = err
×
2349
                        return
×
2350
                }
×
2351

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

2358
                if s.towerClientMgr != nil {
6✔
2359
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2360
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2361
                                startErr = err
×
2362
                                return
×
2363
                        }
×
2364
                }
2365

2366
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2367
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2368
                        startErr = err
×
2369
                        return
×
2370
                }
×
2371

2372
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2373
                if err := s.sweeper.Start(beat); err != nil {
3✔
2374
                        startErr = err
×
2375
                        return
×
2376
                }
×
2377

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

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

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

2396
                // htlcSwitch must be started before chainArb since the latter
2397
                // relies on htlcSwitch to deliver resolution message upon
2398
                // start.
2399
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2400
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2401
                        startErr = err
×
2402
                        return
×
2403
                }
×
2404

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

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

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

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

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

2435
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2436
                if err := s.chanRouter.Start(); err != nil {
3✔
2437
                        startErr = err
×
2438
                        return
×
2439
                }
×
2440
                // The authGossiper depends on the chanRouter and therefore
2441
                // should be started after it.
2442
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2443
                if err := s.authGossiper.Start(); err != nil {
3✔
2444
                        startErr = err
×
2445
                        return
×
2446
                }
×
2447

2448
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2449
                if err := s.invoices.Start(); err != nil {
3✔
2450
                        startErr = err
×
2451
                        return
×
2452
                }
×
2453

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

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

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

2472
                cleanup.add(func() error {
3✔
2473
                        s.missionController.StopStoreTickers()
×
2474
                        return nil
×
2475
                })
×
2476
                s.missionController.RunStoreTickers()
3✔
2477

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

2510
                // chanSubSwapper must be started after the `channelNotifier`
2511
                // because it depends on channel events as a synchronization
2512
                // point.
2513
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2514
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2515
                        startErr = err
×
2516
                        return
×
2517
                }
×
2518

2519
                if s.torController != nil {
3✔
2520
                        cleanup = cleanup.add(s.torController.Stop)
×
2521
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2522
                                startErr = err
×
2523
                                return
×
2524
                        }
×
2525
                }
2526

2527
                if s.natTraversal != nil {
3✔
2528
                        s.wg.Add(1)
×
2529
                        go s.watchExternalIP()
×
2530
                }
×
2531

2532
                // Start connmgr last to prevent connections before init.
2533
                cleanup = cleanup.add(func() error {
3✔
2534
                        s.connMgr.Stop()
×
2535
                        return nil
×
2536
                })
×
2537

2538
                // RESOLVE: s.connMgr.Start() is called here, but
2539
                // brontide.NewListener() is called in newServer. This means
2540
                // that we are actually listening and partially accepting
2541
                // inbound connections even before the connMgr starts.
2542
                //
2543
                // TODO(yy): move the log into the connMgr's `Start` method.
2544
                srvrLog.Info("connMgr starting...")
3✔
2545
                s.connMgr.Start()
3✔
2546
                srvrLog.Debug("connMgr started")
3✔
2547

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

2567
                        peerAddr := &lnwire.NetAddress{
3✔
2568
                                IdentityKey: parsedPubkey,
3✔
2569
                                Address:     addr,
3✔
2570
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2571
                        }
3✔
2572

3✔
2573
                        err = s.ConnectToPeer(
3✔
2574
                                peerAddr, true,
3✔
2575
                                s.cfg.ConnectionTimeout,
3✔
2576
                        )
3✔
2577
                        if err != nil {
3✔
2578
                                startErr = fmt.Errorf("unable to connect to "+
×
2579
                                        "peer address provided as a config "+
×
2580
                                        "option: %v", err)
×
2581
                                return
×
2582
                        }
×
2583
                }
2584

2585
                // Subscribe to NodeAnnouncements that advertise new addresses
2586
                // our persistent peers.
2587
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2588
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2589
                                "addr: %v", err)
×
2590

×
2591
                        startErr = err
×
2592
                        return
×
2593
                }
×
2594

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

×
2604
                        startErr = err
×
2605
                        return
×
2606
                }
×
2607

2608
                if err := s.establishPersistentConnections(); err != nil {
3✔
2609
                        srvrLog.Errorf("Failed to establish persistent "+
×
2610
                                "connections: %v", err)
×
2611
                }
×
2612

2613
                // setSeedList is a helper function that turns multiple DNS seed
2614
                // server tuples from the command line or config file into the
2615
                // data structure we need and does a basic formal sanity check
2616
                // in the process.
2617
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2618
                        if len(tuples) == 0 {
×
2619
                                return
×
2620
                        }
×
2621

2622
                        result := make([][2]string, len(tuples))
×
2623
                        for idx, tuple := range tuples {
×
2624
                                tuple = strings.TrimSpace(tuple)
×
2625
                                if len(tuple) == 0 {
×
2626
                                        return
×
2627
                                }
×
2628

2629
                                servers := strings.Split(tuple, ",")
×
2630
                                if len(servers) > 2 || len(servers) == 0 {
×
2631
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2632
                                                "seed tuple: %v", servers)
×
2633
                                        return
×
2634
                                }
×
2635

2636
                                copy(result[idx][:], servers)
×
2637
                        }
2638

2639
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2640
                }
2641

2642
                // Let users overwrite the DNS seed nodes. We only allow them
2643
                // for bitcoin mainnet/testnet/signet.
2644
                if s.cfg.Bitcoin.MainNet {
3✔
2645
                        setSeedList(
×
2646
                                s.cfg.Bitcoin.DNSSeeds,
×
2647
                                chainreg.BitcoinMainnetGenesis,
×
2648
                        )
×
2649
                }
×
2650
                if s.cfg.Bitcoin.TestNet3 {
3✔
2651
                        setSeedList(
×
2652
                                s.cfg.Bitcoin.DNSSeeds,
×
2653
                                chainreg.BitcoinTestnetGenesis,
×
2654
                        )
×
2655
                }
×
2656
                if s.cfg.Bitcoin.TestNet4 {
3✔
2657
                        setSeedList(
×
2658
                                s.cfg.Bitcoin.DNSSeeds,
×
2659
                                chainreg.BitcoinTestnet4Genesis,
×
2660
                        )
×
2661
                }
×
2662
                if s.cfg.Bitcoin.SigNet {
3✔
2663
                        setSeedList(
×
2664
                                s.cfg.Bitcoin.DNSSeeds,
×
2665
                                chainreg.BitcoinSignetGenesis,
×
2666
                        )
×
2667
                }
×
2668

2669
                // If network bootstrapping hasn't been disabled, then we'll
2670
                // configure the set of active bootstrappers, and launch a
2671
                // dedicated goroutine to maintain a set of persistent
2672
                // connections.
2673
                if !s.cfg.NoNetBootstrap {
6✔
2674
                        bootstrappers, err := initNetworkBootstrappers(s)
3✔
2675
                        if err != nil {
3✔
2676
                                startErr = err
×
2677
                                return
×
2678
                        }
×
2679

2680
                        s.wg.Add(1)
3✔
2681
                        go s.peerBootstrapper(
3✔
2682
                                ctx, defaultMinPeers, bootstrappers,
3✔
2683
                        )
3✔
2684
                } else {
3✔
2685
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2686
                }
3✔
2687

2688
                // Start the blockbeat after all other subsystems have been
2689
                // started so they are ready to receive new blocks.
2690
                cleanup = cleanup.add(func() error {
3✔
2691
                        s.blockbeatDispatcher.Stop()
×
2692
                        return nil
×
2693
                })
×
2694
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2695
                        startErr = err
×
2696
                        return
×
2697
                }
×
2698

2699
                // Set the active flag now that we've completed the full
2700
                // startup.
2701
                atomic.StoreInt32(&s.active, 1)
3✔
2702
        })
2703

2704
        if startErr != nil {
3✔
2705
                cleanup.run()
×
2706
        }
×
2707
        return startErr
3✔
2708
}
2709

2710
// Stop gracefully shutsdown the main daemon server. This function will signal
2711
// any active goroutines, or helper objects to exit, then blocks until they've
2712
// all successfully exited. Additionally, any/all listeners are closed.
2713
// NOTE: This function is safe for concurrent access.
2714
func (s *server) Stop() error {
3✔
2715
        s.stop.Do(func() {
6✔
2716
                atomic.StoreInt32(&s.stopping, 1)
3✔
2717

3✔
2718
                ctx := context.Background()
3✔
2719

3✔
2720
                close(s.quit)
3✔
2721

3✔
2722
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2723
                s.connMgr.Stop()
3✔
2724

3✔
2725
                // Stop dispatching blocks to other systems immediately.
3✔
2726
                s.blockbeatDispatcher.Stop()
3✔
2727

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

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

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

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

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

2845
                if s.hostAnn != nil {
3✔
2846
                        if err := s.hostAnn.Stop(); err != nil {
×
2847
                                srvrLog.Warnf("unable to shut down host "+
×
2848
                                        "annoucner: %v", err)
×
2849
                        }
×
2850
                }
2851

2852
                if s.livenessMonitor != nil {
6✔
2853
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2854
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2855
                                        "monitor: %v", err)
×
2856
                        }
×
2857
                }
2858

2859
                // Wait for all lingering goroutines to quit.
2860
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2861
                s.wg.Wait()
3✔
2862

3✔
2863
                srvrLog.Debug("Stopping buffer pools...")
3✔
2864
                s.sigPool.Stop()
3✔
2865
                s.writePool.Stop()
3✔
2866
                s.readPool.Stop()
3✔
2867
        })
2868

2869
        return nil
3✔
2870
}
2871

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

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

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

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

2901
        return externalIPs, nil
×
2902
}
2903

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

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

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

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

2939
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2940

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

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

2971
                        if ip.Equal(s.lastDetectedIP) {
×
2972
                                continue
×
2973
                        }
2974

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

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

2992
                                newAddrs = append(newAddrs, addr)
×
2993
                        }
2994

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

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

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

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

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

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

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

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

3✔
3061
        var bootStrappers []discovery.NetworkPeerBootstrapper
3✔
3062

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

3✔
3073
        // If this isn't simnet mode, then one of our additional bootstrapping
3✔
3074
        // sources will be the set of running DNS seeds.
3✔
3075
        if !s.cfg.Bitcoin.SimNet {
6✔
3076
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
3✔
3077

3✔
3078
                // If we have a set of DNS seeds for this chain, then we'll add
3✔
3079
                // it as an additional bootstrapping source.
3✔
3080
                if ok {
3✔
3081
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3082
                                "seeds: %v", dnsSeeds)
×
3083

×
3084
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3085
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3086
                        )
×
3087
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3088
                }
×
3089
        }
3090

3091
        return bootStrappers, nil
3✔
3092
}
3093

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

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

3✔
3106
        // We should ignore ourselves from bootstrapping.
3✔
3107
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
3✔
3108
        ignore[selfKey] = struct{}{}
3✔
3109

3✔
3110
        // Ignore all connected peers.
3✔
3111
        for _, peer := range s.peersByPub {
3✔
3112
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3113
                ignore[nID] = struct{}{}
×
3114
        }
×
3115

3116
        // Ignore all persistent peers as they have a dedicated reconnecting
3117
        // process.
3118
        for pubKeyStr := range s.persistentPeers {
3✔
3119
                var nID autopilot.NodeID
×
3120
                copy(nID[:], []byte(pubKeyStr))
×
3121
                ignore[nID] = struct{}{}
×
3122
        }
×
3123

3124
        return ignore
3✔
3125
}
3126

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

3✔
3135
        defer s.wg.Done()
3✔
3136

3✔
3137
        // Before we continue, init the ignore peers map.
3✔
3138
        ignoreList := s.createBootstrapIgnorePeers()
3✔
3139

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

3✔
3144
        // Once done, we'll attempt to maintain our target minimum number of
3✔
3145
        // peers.
3✔
3146
        //
3✔
3147
        // We'll use a 15 second backoff, and double the time every time an
3✔
3148
        // epoch fails up to a ceiling.
3✔
3149
        backOff := time.Second * 15
3✔
3150

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

3✔
3156
        // We'll use the number of attempts and errors to determine if we need
3✔
3157
        // to increase the time between discovery epochs.
3✔
3158
        var epochErrors uint32 // To be used atomically.
3✔
3159
        var epochAttempts uint32
3✔
3160

3✔
3161
        for {
6✔
3162
                select {
3✔
3163
                // The ticker has just woken us up, so we'll need to check if
3164
                // we need to attempt to connect our to any more peers.
3165
                case <-sampleTicker.C:
×
3166
                        // Obtain the current number of peers, so we can gauge
×
3167
                        // if we need to sample more peers or not.
×
3168
                        s.mu.RLock()
×
3169
                        numActivePeers := uint32(len(s.peersByPub))
×
3170
                        s.mu.RUnlock()
×
3171

×
3172
                        // If we have enough peers, then we can loop back
×
3173
                        // around to the next round as we're done here.
×
3174
                        if numActivePeers >= numTargetPeers {
×
3175
                                continue
×
3176
                        }
3177

3178
                        // If all of our attempts failed during this last back
3179
                        // off period, then will increase our backoff to 5
3180
                        // minute ceiling to avoid an excessive number of
3181
                        // queries
3182
                        //
3183
                        // TODO(roasbeef): add reverse policy too?
3184

3185
                        if epochAttempts > 0 &&
×
3186
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3187

×
3188
                                sampleTicker.Stop()
×
3189

×
3190
                                backOff *= 2
×
3191
                                if backOff > bootstrapBackOffCeiling {
×
3192
                                        backOff = bootstrapBackOffCeiling
×
3193
                                }
×
3194

3195
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3196
                                        "%v", backOff)
×
3197
                                sampleTicker = time.NewTicker(backOff)
×
3198
                                continue
×
3199
                        }
3200

3201
                        atomic.StoreUint32(&epochErrors, 0)
×
3202
                        epochAttempts = 0
×
3203

×
3204
                        // Since we know need more peers, we'll compute the
×
3205
                        // exact number we need to reach our threshold.
×
3206
                        numNeeded := numTargetPeers - numActivePeers
×
3207

×
3208
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3209
                                "peers", numNeeded)
×
3210

×
3211
                        // With the number of peers we need calculated, we'll
×
3212
                        // query the network bootstrappers to sample a set of
×
3213
                        // random addrs for us.
×
3214
                        //
×
3215
                        // Before we continue, get a copy of the ignore peers
×
3216
                        // map.
×
3217
                        ignoreList = s.createBootstrapIgnorePeers()
×
3218

×
3219
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3220
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3221
                        )
×
3222
                        if err != nil {
×
3223
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3224
                                        "peers: %v", err)
×
3225
                                continue
×
3226
                        }
3227

3228
                        // Finally, we'll launch a new goroutine for each
3229
                        // prospective peer candidates.
3230
                        for _, addr := range peerAddrs {
×
3231
                                epochAttempts++
×
3232

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

3247
                                                srvrLog.Errorf("Unable to "+
×
3248
                                                        "connect to %v: %v",
×
3249
                                                        a, err)
×
3250
                                                atomic.AddUint32(&epochErrors, 1)
×
3251
                                        case <-s.quit:
×
3252
                                        }
3253
                                }(addr)
3254
                        }
3255
                case <-s.quit:
3✔
3256
                        return
3✔
3257
                }
3258
        }
3259
}
3260

3261
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3262
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3263
// query back off each time we encounter a failure.
3264
const bootstrapBackOffCeiling = time.Minute * 5
3265

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

3✔
3273
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
3✔
3274
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
3✔
3275

3✔
3276
        // We'll start off by waiting 2 seconds between failed attempts, then
3✔
3277
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3✔
3278
        var delaySignal <-chan time.Time
3✔
3279
        delayTime := time.Second * 2
3✔
3280

3✔
3281
        // As want to be more aggressive, we'll use a lower back off celling
3✔
3282
        // then the main peer bootstrap logic.
3✔
3283
        backOffCeiling := bootstrapBackOffCeiling / 5
3✔
3284

3✔
3285
        for attempts := 0; ; attempts++ {
6✔
3286
                // Check if the server has been requested to shut down in order
3✔
3287
                // to prevent blocking.
3✔
3288
                if s.Stopped() {
3✔
3289
                        return
×
3290
                }
×
3291

3292
                // We can exit our aggressive initial peer bootstrapping stage
3293
                // if we've reached out target number of peers.
3294
                s.mu.RLock()
3✔
3295
                numActivePeers := uint32(len(s.peersByPub))
3✔
3296
                s.mu.RUnlock()
3✔
3297

3✔
3298
                if numActivePeers >= numTargetPeers {
6✔
3299
                        return
3✔
3300
                }
3✔
3301

3302
                if attempts > 0 {
4✔
3303
                        srvrLog.Debugf("Waiting %v before trying to locate "+
1✔
3304
                                "bootstrap peers (attempt #%v)", delayTime,
1✔
3305
                                attempts)
1✔
3306

1✔
3307
                        // We've completed at least one iterating and haven't
1✔
3308
                        // finished, so we'll start to insert a delay period
1✔
3309
                        // between each attempt.
1✔
3310
                        delaySignal = time.After(delayTime)
1✔
3311
                        select {
1✔
3312
                        case <-delaySignal:
1✔
3313
                        case <-s.quit:
×
3314
                                return
×
3315
                        }
3316

3317
                        // After our delay, we'll double the time we wait up to
3318
                        // the max back off period.
3319
                        delayTime *= 2
1✔
3320
                        if delayTime > backOffCeiling {
1✔
3321
                                delayTime = backOffCeiling
×
3322
                        }
×
3323
                }
3324

3325
                // Otherwise, we'll request for the remaining number of peers
3326
                // in order to reach our target.
3327
                peersNeeded := numTargetPeers - numActivePeers
3✔
3328
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
3✔
3329
                        ctx, ignore, peersNeeded, bootstrappers...,
3✔
3330
                )
3✔
3331
                if err != nil {
4✔
3332
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
1✔
3333
                                "peers: %v", err)
1✔
3334
                        continue
1✔
3335
                }
3336

3337
                // Then, we'll attempt to establish a connection to the
3338
                // different peer addresses retrieved by our bootstrappers.
3339
                var wg sync.WaitGroup
3✔
3340
                for _, bootstrapAddr := range bootstrapAddrs {
6✔
3341
                        wg.Add(1)
3✔
3342
                        go func(addr *lnwire.NetAddress) {
6✔
3343
                                defer wg.Done()
3✔
3344

3✔
3345
                                errChan := make(chan error, 1)
3✔
3346
                                go s.connectToPeer(
3✔
3347
                                        addr, errChan, s.cfg.ConnectionTimeout,
3✔
3348
                                )
3✔
3349

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

3373
                wg.Wait()
3✔
3374
        }
3375
}
3376

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

3389
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3390
        if err != nil {
×
3391
                return err
×
3392
        }
×
3393

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

×
3406
        switch {
×
3407
        case s.cfg.Tor.V2:
×
3408
                onionCfg.Type = tor.V2
×
3409
        case s.cfg.Tor.V3:
×
3410
                onionCfg.Type = tor.V3
×
3411
        }
3412

3413
        addr, err := s.torController.AddOnion(onionCfg)
×
3414
        if err != nil {
×
3415
                return err
×
3416
        }
×
3417

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

3430
        // Finally, we'll update the on-disk version of our announcement so it
3431
        // will eventually propagate to nodes in the network.
3432
        selfNode := &models.LightningNode{
×
3433
                HaveNodeAnnouncement: true,
×
3434
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3435
                Addresses:            newNodeAnn.Addresses,
×
3436
                Alias:                newNodeAnn.Alias.String(),
×
3437
                Features: lnwire.NewFeatureVector(
×
3438
                        newNodeAnn.Features, lnwire.Features,
×
3439
                ),
×
3440
                Color:        newNodeAnn.RGBColor,
×
3441
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3442
        }
×
3443
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3444
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3445
                return fmt.Errorf("can't set self node: %w", err)
×
3446
        }
×
3447

3448
        return nil
×
3449
}
3450

3451
// findChannel finds a channel given a public key and ChannelID. It is an
3452
// optimization that is quicker than seeking for a channel given only the
3453
// ChannelID.
3454
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3455
        *channeldb.OpenChannel, error) {
3✔
3456

3✔
3457
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3458
        if err != nil {
3✔
3459
                return nil, err
×
3460
        }
×
3461

3462
        for _, channel := range nodeChans {
6✔
3463
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3464
                        return channel, nil
3✔
3465
                }
3✔
3466
        }
3467

3468
        return nil, fmt.Errorf("unable to find channel")
3✔
3469
}
3470

3471
// getNodeAnnouncement fetches the current, fully signed node announcement.
3472
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3473
        s.mu.Lock()
3✔
3474
        defer s.mu.Unlock()
3✔
3475

3✔
3476
        return *s.currentNodeAnn
3✔
3477
}
3✔
3478

3479
// genNodeAnnouncement generates and returns the current fully signed node
3480
// announcement. The time stamp of the announcement will be updated in order
3481
// to ensure it propagates through the network.
3482
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3483
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3484

3✔
3485
        s.mu.Lock()
3✔
3486
        defer s.mu.Unlock()
3✔
3487

3✔
3488
        // Create a shallow copy of the current node announcement to work on.
3✔
3489
        // This ensures the original announcement remains unchanged
3✔
3490
        // until the new announcement is fully signed and valid.
3✔
3491
        newNodeAnn := *s.currentNodeAnn
3✔
3492

3✔
3493
        // First, try to update our feature manager with the updated set of
3✔
3494
        // features.
3✔
3495
        if features != nil {
6✔
3496
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3497
                        feature.SetNodeAnn: features,
3✔
3498
                }
3✔
3499
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3500
                if err != nil {
6✔
3501
                        return lnwire.NodeAnnouncement{}, err
3✔
3502
                }
3✔
3503

3504
                // If we could successfully update our feature manager, add
3505
                // an update modifier to include these new features to our
3506
                // set.
3507
                modifiers = append(
3✔
3508
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3509
                )
3✔
3510
        }
3511

3512
        // Always update the timestamp when refreshing to ensure the update
3513
        // propagates.
3514
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3515

3✔
3516
        // Apply the requested changes to the node announcement.
3✔
3517
        for _, modifier := range modifiers {
6✔
3518
                modifier(&newNodeAnn)
3✔
3519
        }
3✔
3520

3521
        // Sign a new update after applying all of the passed modifiers.
3522
        err := netann.SignNodeAnnouncement(
3✔
3523
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
3✔
3524
        )
3✔
3525
        if err != nil {
3✔
3526
                return lnwire.NodeAnnouncement{}, err
×
3527
        }
×
3528

3529
        // If signing succeeds, update the current announcement.
3530
        *s.currentNodeAnn = newNodeAnn
3✔
3531

3✔
3532
        return *s.currentNodeAnn, nil
3✔
3533
}
3534

3535
// updateAndBroadcastSelfNode generates a new node announcement
3536
// applying the giving modifiers and updating the time stamp
3537
// to ensure it propagates through the network. Then it broadcasts
3538
// it to the network.
3539
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3540
        features *lnwire.RawFeatureVector,
3541
        modifiers ...netann.NodeAnnModifier) error {
3✔
3542

3✔
3543
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3544
        if err != nil {
6✔
3545
                return fmt.Errorf("unable to generate new node "+
3✔
3546
                        "announcement: %v", err)
3✔
3547
        }
3✔
3548

3549
        // Update the on-disk version of our announcement.
3550
        // Load and modify self node istead of creating anew instance so we
3551
        // don't risk overwriting any existing values.
3552
        selfNode, err := s.graphDB.SourceNode(ctx)
3✔
3553
        if err != nil {
3✔
3554
                return fmt.Errorf("unable to get current source node: %w", err)
×
3555
        }
×
3556

3557
        selfNode.HaveNodeAnnouncement = true
3✔
3558
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3559
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3560
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3561
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3562
        selfNode.Color = newNodeAnn.RGBColor
3✔
3563
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3564

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

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

3571
        // Finally, propagate it to the nodes in the network.
3572
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3573
        if err != nil {
3✔
3574
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3575
                        "announcement to peers: %v", err)
×
3576
                return err
×
3577
        }
×
3578

3579
        return nil
3✔
3580
}
3581

3582
type nodeAddresses struct {
3583
        pubKey    *btcec.PublicKey
3584
        addresses []net.Addr
3585
}
3586

3587
// establishPersistentConnections attempts to establish persistent connections
3588
// to all our direct channel collaborators. In order to promote liveness of our
3589
// active channels, we instruct the connection manager to attempt to establish
3590
// and maintain persistent connections to all our direct channel counterparties.
3591
func (s *server) establishPersistentConnections() error {
3✔
3592
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3593
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3594
        // since other PubKey forms can't be compared.
3✔
3595
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3596

3✔
3597
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3598
        // attempt to connect to based on our set of previous connections. Set
3✔
3599
        // the reconnection port to the default peer port.
3✔
3600
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3601
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3602
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3603
        }
×
3604

3605
        for _, node := range linkNodes {
6✔
3606
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3607
                nodeAddrs := &nodeAddresses{
3✔
3608
                        pubKey:    node.IdentityPub,
3✔
3609
                        addresses: node.Addresses,
3✔
3610
                }
3✔
3611
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3612
        }
3✔
3613

3614
        // After checking our previous connections for addresses to connect to,
3615
        // iterate through the nodes in our channel graph to find addresses
3616
        // that have been added via NodeAnnouncement messages.
3617
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3618
        // each of the nodes.
3619
        err = s.graphDB.ForEachSourceNodeChannel(func(chanPoint wire.OutPoint,
3✔
3620
                havePolicy bool, channelPeer *models.LightningNode) error {
6✔
3621

3✔
3622
                // If the remote party has announced the channel to us, but we
3✔
3623
                // haven't yet, then we won't have a policy. However, we don't
3✔
3624
                // need this to connect to the peer, so we'll log it and move on.
3✔
3625
                if !havePolicy {
3✔
3626
                        srvrLog.Warnf("No channel policy found for "+
×
3627
                                "ChannelPoint(%v): ", chanPoint)
×
3628
                }
×
3629

3630
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3631

3✔
3632
                // Add all unique addresses from channel
3✔
3633
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3634
                // connect to for this peer.
3✔
3635
                addrSet := make(map[string]net.Addr)
3✔
3636
                for _, addr := range channelPeer.Addresses {
6✔
3637
                        switch addr.(type) {
3✔
3638
                        case *net.TCPAddr:
3✔
3639
                                addrSet[addr.String()] = addr
3✔
3640

3641
                        // We'll only attempt to connect to Tor addresses if Tor
3642
                        // outbound support is enabled.
3643
                        case *tor.OnionAddr:
×
3644
                                if s.cfg.Tor.Active {
×
3645
                                        addrSet[addr.String()] = addr
×
3646
                                }
×
3647
                        }
3648
                }
3649

3650
                // If this peer is also recorded as a link node, we'll add any
3651
                // additional addresses that have not already been selected.
3652
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3653
                if ok {
6✔
3654
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3655
                                switch lnAddress.(type) {
3✔
3656
                                case *net.TCPAddr:
3✔
3657
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3658

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

3669
                // Construct a slice of the deduped addresses.
3670
                var addrs []net.Addr
3✔
3671
                for _, addr := range addrSet {
6✔
3672
                        addrs = append(addrs, addr)
3✔
3673
                }
3✔
3674

3675
                n := &nodeAddresses{
3✔
3676
                        addresses: addrs,
3✔
3677
                }
3✔
3678
                n.pubKey, err = channelPeer.PubKey()
3✔
3679
                if err != nil {
3✔
3680
                        return err
×
3681
                }
×
3682

3683
                nodeAddrsMap[pubStr] = n
3✔
3684
                return nil
3✔
3685
        })
3686
        if err != nil {
3✔
3687
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3688
                        "%v", err)
×
3689

×
3690
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3691
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3692

×
3693
                        return err
×
3694
                }
×
3695
        }
3696

3697
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3698
                len(nodeAddrsMap))
3✔
3699

3✔
3700
        // Acquire and hold server lock until all persistent connection requests
3✔
3701
        // have been recorded and sent to the connection manager.
3✔
3702
        s.mu.Lock()
3✔
3703
        defer s.mu.Unlock()
3✔
3704

3✔
3705
        // Iterate through the combined list of addresses from prior links and
3✔
3706
        // node announcements and attempt to reconnect to each node.
3✔
3707
        var numOutboundConns int
3✔
3708
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3709
                // Add this peer to the set of peers we should maintain a
3✔
3710
                // persistent connection with. We set the value to false to
3✔
3711
                // indicate that we should not continue to reconnect if the
3✔
3712
                // number of channels returns to zero, since this peer has not
3✔
3713
                // been requested as perm by the user.
3✔
3714
                s.persistentPeers[pubStr] = false
3✔
3715
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3716
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3717
                }
3✔
3718

3719
                for _, address := range nodeAddr.addresses {
6✔
3720
                        // Create a wrapper address which couples the IP and
3✔
3721
                        // the pubkey so the brontide authenticated connection
3✔
3722
                        // can be established.
3✔
3723
                        lnAddr := &lnwire.NetAddress{
3✔
3724
                                IdentityKey: nodeAddr.pubKey,
3✔
3725
                                Address:     address,
3✔
3726
                        }
3✔
3727

3✔
3728
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3729
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3730
                }
3✔
3731

3732
                // We'll connect to the first 10 peers immediately, then
3733
                // randomly stagger any remaining connections if the
3734
                // stagger initial reconnect flag is set. This ensures
3735
                // that mobile nodes or nodes with a small number of
3736
                // channels obtain connectivity quickly, but larger
3737
                // nodes are able to disperse the costs of connecting to
3738
                // all peers at once.
3739
                if numOutboundConns < numInstantInitReconnect ||
3✔
3740
                        !s.cfg.StaggerInitialReconnect {
6✔
3741

3✔
3742
                        go s.connectToPersistentPeer(pubStr)
3✔
3743
                } else {
3✔
3744
                        go s.delayInitialReconnect(pubStr)
×
3745
                }
×
3746

3747
                numOutboundConns++
3✔
3748
        }
3749

3750
        return nil
3✔
3751
}
3752

3753
// delayInitialReconnect will attempt a reconnection to the given peer after
3754
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3755
//
3756
// NOTE: This method MUST be run as a goroutine.
3757
func (s *server) delayInitialReconnect(pubStr string) {
×
3758
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3759
        select {
×
3760
        case <-time.After(delay):
×
3761
                s.connectToPersistentPeer(pubStr)
×
3762
        case <-s.quit:
×
3763
        }
3764
}
3765

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

3✔
3772
        s.mu.Lock()
3✔
3773
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3774
                delete(s.persistentPeers, pubKeyStr)
3✔
3775
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3776
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3777
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3778
                s.mu.Unlock()
3✔
3779

3✔
3780
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3781
                        "peer has no open channels", compressedPubKey)
3✔
3782

3✔
3783
                return
3✔
3784
        }
3✔
3785
        s.mu.Unlock()
3✔
3786
}
3787

3788
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3789
// is instead used to remove persistent peer state for a peer that has been
3790
// disconnected for good cause by the server. Currently, a gossip ban from
3791
// sending garbage and the server running out of restricted-access
3792
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3793
// future, this function may expand when more ban criteria is added.
3794
//
3795
// NOTE: The server's write lock MUST be held when this is called.
3796
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3797
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3798
                delete(s.persistentPeers, remotePub)
×
3799
                delete(s.persistentPeersBackoff, remotePub)
×
3800
                delete(s.persistentPeerAddrs, remotePub)
×
3801
                s.cancelConnReqs(remotePub, nil)
×
3802
        }
×
3803
}
3804

3805
// BroadcastMessage sends a request to the server to broadcast a set of
3806
// messages to all peers other than the one specified by the `skips` parameter.
3807
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3808
// the target peers.
3809
//
3810
// NOTE: This function is safe for concurrent access.
3811
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3812
        msgs ...lnwire.Message) error {
3✔
3813

3✔
3814
        // Filter out peers found in the skips map. We synchronize access to
3✔
3815
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3816
        // exact set of peers present at the time of invocation.
3✔
3817
        s.mu.RLock()
3✔
3818
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3819
        for pubStr, sPeer := range s.peersByPub {
6✔
3820
                if skips != nil {
6✔
3821
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3822
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3823
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3824
                                continue
3✔
3825
                        }
3826
                }
3827

3828
                peers = append(peers, sPeer)
3✔
3829
        }
3830
        s.mu.RUnlock()
3✔
3831

3✔
3832
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3833
        // all messages to each of peers.
3✔
3834
        var wg sync.WaitGroup
3✔
3835
        for _, sPeer := range peers {
6✔
3836
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3837
                        sPeer.PubKey())
3✔
3838

3✔
3839
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3840
                wg.Add(1)
3✔
3841
                s.wg.Add(1)
3✔
3842
                go func(p lnpeer.Peer) {
6✔
3843
                        defer s.wg.Done()
3✔
3844
                        defer wg.Done()
3✔
3845

3✔
3846
                        p.SendMessageLazy(false, msgs...)
3✔
3847
                }(sPeer)
3✔
3848
        }
3849

3850
        // Wait for all messages to have been dispatched before returning to
3851
        // caller.
3852
        wg.Wait()
3✔
3853

3✔
3854
        return nil
3✔
3855
}
3856

3857
// NotifyWhenOnline can be called by other subsystems to get notified when a
3858
// particular peer comes online. The peer itself is sent across the peerChan.
3859
//
3860
// NOTE: This function is safe for concurrent access.
3861
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3862
        peerChan chan<- lnpeer.Peer) {
3✔
3863

3✔
3864
        s.mu.Lock()
3✔
3865

3✔
3866
        // Compute the target peer's identifier.
3✔
3867
        pubStr := string(peerKey[:])
3✔
3868

3✔
3869
        // Check if peer is connected.
3✔
3870
        peer, ok := s.peersByPub[pubStr]
3✔
3871
        if ok {
6✔
3872
                // Unlock here so that the mutex isn't held while we are
3✔
3873
                // waiting for the peer to become active.
3✔
3874
                s.mu.Unlock()
3✔
3875

3✔
3876
                // Wait until the peer signals that it is actually active
3✔
3877
                // rather than only in the server's maps.
3✔
3878
                select {
3✔
3879
                case <-peer.ActiveSignal():
3✔
3880
                case <-peer.QuitSignal():
1✔
3881
                        // The peer quit, so we'll add the channel to the slice
1✔
3882
                        // and return.
1✔
3883
                        s.mu.Lock()
1✔
3884
                        s.peerConnectedListeners[pubStr] = append(
1✔
3885
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3886
                        )
1✔
3887
                        s.mu.Unlock()
1✔
3888
                        return
1✔
3889
                }
3890

3891
                // Connected, can return early.
3892
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3893

3✔
3894
                select {
3✔
3895
                case peerChan <- peer:
3✔
UNCOV
3896
                case <-s.quit:
×
3897
                }
3898

3899
                return
3✔
3900
        }
3901

3902
        // Not connected, store this listener such that it can be notified when
3903
        // the peer comes online.
3904
        s.peerConnectedListeners[pubStr] = append(
3✔
3905
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3906
        )
3✔
3907
        s.mu.Unlock()
3✔
3908
}
3909

3910
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3911
// the given public key has been disconnected. The notification is signaled by
3912
// closing the channel returned.
3913
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3914
        s.mu.Lock()
3✔
3915
        defer s.mu.Unlock()
3✔
3916

3✔
3917
        c := make(chan struct{})
3✔
3918

3✔
3919
        // If the peer is already offline, we can immediately trigger the
3✔
3920
        // notification.
3✔
3921
        peerPubKeyStr := string(peerPubKey[:])
3✔
3922
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3923
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3924
                close(c)
×
3925
                return c
×
3926
        }
×
3927

3928
        // Otherwise, the peer is online, so we'll keep track of the channel to
3929
        // trigger the notification once the server detects the peer
3930
        // disconnects.
3931
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3932
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3933
        )
3✔
3934

3✔
3935
        return c
3✔
3936
}
3937

3938
// FindPeer will return the peer that corresponds to the passed in public key.
3939
// This function is used by the funding manager, allowing it to update the
3940
// daemon's local representation of the remote peer.
3941
//
3942
// NOTE: This function is safe for concurrent access.
3943
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3944
        s.mu.RLock()
3✔
3945
        defer s.mu.RUnlock()
3✔
3946

3✔
3947
        pubStr := string(peerKey.SerializeCompressed())
3✔
3948

3✔
3949
        return s.findPeerByPubStr(pubStr)
3✔
3950
}
3✔
3951

3952
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3953
// which should be a string representation of the peer's serialized, compressed
3954
// public key.
3955
//
3956
// NOTE: This function is safe for concurrent access.
3957
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3958
        s.mu.RLock()
3✔
3959
        defer s.mu.RUnlock()
3✔
3960

3✔
3961
        return s.findPeerByPubStr(pubStr)
3✔
3962
}
3✔
3963

3964
// findPeerByPubStr is an internal method that retrieves the specified peer from
3965
// the server's internal state using.
3966
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3967
        peer, ok := s.peersByPub[pubStr]
3✔
3968
        if !ok {
6✔
3969
                return nil, ErrPeerNotConnected
3✔
3970
        }
3✔
3971

3972
        return peer, nil
3✔
3973
}
3974

3975
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3976
// exponential backoff. If no previous backoff was known, the default is
3977
// returned.
3978
func (s *server) nextPeerBackoff(pubStr string,
3979
        startTime time.Time) time.Duration {
3✔
3980

3✔
3981
        // Now, determine the appropriate backoff to use for the retry.
3✔
3982
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3983
        if !ok {
6✔
3984
                // If an existing backoff was unknown, use the default.
3✔
3985
                return s.cfg.MinBackoff
3✔
3986
        }
3✔
3987

3988
        // If the peer failed to start properly, we'll just use the previous
3989
        // backoff to compute the subsequent randomized exponential backoff
3990
        // duration. This will roughly double on average.
3991
        if startTime.IsZero() {
3✔
3992
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3993
        }
×
3994

3995
        // The peer succeeded in starting. If the connection didn't last long
3996
        // enough to be considered stable, we'll continue to back off retries
3997
        // with this peer.
3998
        connDuration := time.Since(startTime)
3✔
3999
        if connDuration < defaultStableConnDuration {
6✔
4000
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
4001
        }
3✔
4002

4003
        // The peer succeed in starting and this was stable peer, so we'll
4004
        // reduce the timeout duration by the length of the connection after
4005
        // applying randomized exponential backoff. We'll only apply this in the
4006
        // case that:
4007
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
4008
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
4009
        if relaxedBackoff > s.cfg.MinBackoff {
×
4010
                return relaxedBackoff
×
4011
        }
×
4012

4013
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
4014
        // the stable connection lasted much longer than our previous backoff.
4015
        // To reward such good behavior, we'll reconnect after the default
4016
        // timeout.
4017
        return s.cfg.MinBackoff
×
4018
}
4019

4020
// shouldDropLocalConnection determines if our local connection to a remote peer
4021
// should be dropped in the case of concurrent connection establishment. In
4022
// order to deterministically decide which connection should be dropped, we'll
4023
// utilize the ordering of the local and remote public key. If we didn't use
4024
// such a tie breaker, then we risk _both_ connections erroneously being
4025
// dropped.
4026
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
4027
        localPubBytes := local.SerializeCompressed()
×
4028
        remotePubPbytes := remote.SerializeCompressed()
×
4029

×
4030
        // The connection that comes from the node with a "smaller" pubkey
×
4031
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
4032
        // should drop our established connection.
×
4033
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
4034
}
×
4035

4036
// InboundPeerConnected initializes a new peer in response to a new inbound
4037
// connection.
4038
//
4039
// NOTE: This function is safe for concurrent access.
4040
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
4041
        // Exit early if we have already been instructed to shutdown, this
3✔
4042
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4043
        if s.Stopped() {
3✔
4044
                return
×
4045
        }
×
4046

4047
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4048
        pubSer := nodePub.SerializeCompressed()
3✔
4049
        pubStr := string(pubSer)
3✔
4050

3✔
4051
        var pubBytes [33]byte
3✔
4052
        copy(pubBytes[:], pubSer)
3✔
4053

3✔
4054
        s.mu.Lock()
3✔
4055
        defer s.mu.Unlock()
3✔
4056

3✔
4057
        // If we already have an outbound connection to this peer, then ignore
3✔
4058
        // this new connection.
3✔
4059
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4060
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4061
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4062
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4063

3✔
4064
                conn.Close()
3✔
4065
                return
3✔
4066
        }
3✔
4067

4068
        // If we already have a valid connection that is scheduled to take
4069
        // precedence once the prior peer has finished disconnecting, we'll
4070
        // ignore this connection.
4071
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4072
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4073
                        "scheduled", conn.RemoteAddr(), p)
×
4074
                conn.Close()
×
4075
                return
×
4076
        }
×
4077

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

3✔
4080
        // Check to see if we already have a connection with this peer. If so,
3✔
4081
        // we may need to drop our existing connection. This prevents us from
3✔
4082
        // having duplicate connections to the same peer. We forgo adding a
3✔
4083
        // default case as we expect these to be the only error values returned
3✔
4084
        // from findPeerByPubStr.
3✔
4085
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4086
        switch err {
3✔
4087
        case ErrPeerNotConnected:
3✔
4088
                // We were unable to locate an existing connection with the
3✔
4089
                // target peer, proceed to connect.
3✔
4090
                s.cancelConnReqs(pubStr, nil)
3✔
4091
                s.peerConnected(conn, nil, true)
3✔
4092

4093
        case nil:
3✔
4094
                // We already have a connection with the incoming peer. If the
3✔
4095
                // connection we've already established should be kept and is
3✔
4096
                // not of the same type of the new connection (inbound), then
3✔
4097
                // we'll close out the new connection s.t there's only a single
3✔
4098
                // connection between us.
3✔
4099
                localPub := s.identityECDH.PubKey()
3✔
4100
                if !connectedPeer.Inbound() &&
3✔
4101
                        !shouldDropLocalConnection(localPub, nodePub) {
3✔
4102

×
4103
                        srvrLog.Warnf("Received inbound connection from "+
×
4104
                                "peer %v, but already have outbound "+
×
4105
                                "connection, dropping conn", connectedPeer)
×
4106
                        conn.Close()
×
4107
                        return
×
4108
                }
×
4109

4110
                // Otherwise, if we should drop the connection, then we'll
4111
                // disconnect our already connected peer.
4112
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4113
                        connectedPeer)
3✔
4114

3✔
4115
                s.cancelConnReqs(pubStr, nil)
3✔
4116

3✔
4117
                // Remove the current peer from the server's internal state and
3✔
4118
                // signal that the peer termination watcher does not need to
3✔
4119
                // execute for this peer.
3✔
4120
                s.removePeerUnsafe(connectedPeer)
3✔
4121
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4122
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4123
                        s.peerConnected(conn, nil, true)
3✔
4124
                }
3✔
4125
        }
4126
}
4127

4128
// OutboundPeerConnected initializes a new peer in response to a new outbound
4129
// connection.
4130
// NOTE: This function is safe for concurrent access.
4131
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4132
        // Exit early if we have already been instructed to shutdown, this
3✔
4133
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4134
        if s.Stopped() {
3✔
4135
                return
×
4136
        }
×
4137

4138
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4139
        pubSer := nodePub.SerializeCompressed()
3✔
4140
        pubStr := string(pubSer)
3✔
4141

3✔
4142
        var pubBytes [33]byte
3✔
4143
        copy(pubBytes[:], pubSer)
3✔
4144

3✔
4145
        s.mu.Lock()
3✔
4146
        defer s.mu.Unlock()
3✔
4147

3✔
4148
        // If we already have an inbound connection to this peer, then ignore
3✔
4149
        // this new connection.
3✔
4150
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4151
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4152
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4153
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4154

3✔
4155
                if connReq != nil {
6✔
4156
                        s.connMgr.Remove(connReq.ID())
3✔
4157
                }
3✔
4158
                conn.Close()
3✔
4159
                return
3✔
4160
        }
4161
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4162
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4163
                s.connMgr.Remove(connReq.ID())
×
4164
                conn.Close()
×
4165
                return
×
4166
        }
×
4167

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

×
4174
                if connReq != nil {
×
4175
                        s.connMgr.Remove(connReq.ID())
×
4176
                }
×
4177

4178
                conn.Close()
×
4179
                return
×
4180
        }
4181

4182
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
3✔
4183
                conn.RemoteAddr())
3✔
4184

3✔
4185
        if connReq != nil {
6✔
4186
                // A successful connection was returned by the connmgr.
3✔
4187
                // Immediately cancel all pending requests, excluding the
3✔
4188
                // outbound connection we just established.
3✔
4189
                ignore := connReq.ID()
3✔
4190
                s.cancelConnReqs(pubStr, &ignore)
3✔
4191
        } else {
6✔
4192
                // This was a successful connection made by some other
3✔
4193
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4194
                s.cancelConnReqs(pubStr, nil)
3✔
4195
        }
3✔
4196

4197
        // If we already have a connection with this peer, decide whether or not
4198
        // we need to drop the stale connection. We forgo adding a default case
4199
        // as we expect these to be the only error values returned from
4200
        // findPeerByPubStr.
4201
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4202
        switch err {
3✔
4203
        case ErrPeerNotConnected:
3✔
4204
                // We were unable to locate an existing connection with the
3✔
4205
                // target peer, proceed to connect.
3✔
4206
                s.peerConnected(conn, connReq, false)
3✔
4207

4208
        case nil:
3✔
4209
                // We already have a connection with the incoming peer. If the
3✔
4210
                // connection we've already established should be kept and is
3✔
4211
                // not of the same type of the new connection (outbound), then
3✔
4212
                // we'll close out the new connection s.t there's only a single
3✔
4213
                // connection between us.
3✔
4214
                localPub := s.identityECDH.PubKey()
3✔
4215
                if connectedPeer.Inbound() &&
3✔
4216
                        shouldDropLocalConnection(localPub, nodePub) {
3✔
4217

×
4218
                        srvrLog.Warnf("Established outbound connection to "+
×
4219
                                "peer %v, but already have inbound "+
×
4220
                                "connection, dropping conn", connectedPeer)
×
4221
                        if connReq != nil {
×
4222
                                s.connMgr.Remove(connReq.ID())
×
4223
                        }
×
4224
                        conn.Close()
×
4225
                        return
×
4226
                }
4227

4228
                // Otherwise, _their_ connection should be dropped. So we'll
4229
                // disconnect the peer and send the now obsolete peer to the
4230
                // server for garbage collection.
4231
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4232
                        connectedPeer)
3✔
4233

3✔
4234
                // Remove the current peer from the server's internal state and
3✔
4235
                // signal that the peer termination watcher does not need to
3✔
4236
                // execute for this peer.
3✔
4237
                s.removePeerUnsafe(connectedPeer)
3✔
4238
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3✔
4239
                s.scheduledPeerConnection[pubStr] = func() {
6✔
4240
                        s.peerConnected(conn, connReq, false)
3✔
4241
                }
3✔
4242
        }
4243
}
4244

4245
// UnassignedConnID is the default connection ID that a request can have before
4246
// it actually is submitted to the connmgr.
4247
// TODO(conner): move into connmgr package, or better, add connmgr method for
4248
// generating atomic IDs
4249
const UnassignedConnID uint64 = 0
4250

4251
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4252
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4253
// Afterwards, each connection request removed from the connmgr. The caller can
4254
// optionally specify a connection ID to ignore, which prevents us from
4255
// canceling a successful request. All persistent connreqs for the provided
4256
// pubkey are discarded after the operationjw.
4257
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4258
        // First, cancel any lingering persistent retry attempts, which will
3✔
4259
        // prevent retries for any with backoffs that are still maturing.
3✔
4260
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4261
                close(cancelChan)
3✔
4262
                delete(s.persistentRetryCancels, pubStr)
3✔
4263
        }
3✔
4264

4265
        // Next, check to see if we have any outstanding persistent connection
4266
        // requests to this peer. If so, then we'll remove all of these
4267
        // connection requests, and also delete the entry from the map.
4268
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4269
        if !ok {
6✔
4270
                return
3✔
4271
        }
3✔
4272

4273
        for _, connReq := range connReqs {
6✔
4274
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4275

3✔
4276
                // Atomically capture the current request identifier.
3✔
4277
                connID := connReq.ID()
3✔
4278

3✔
4279
                // Skip any zero IDs, this indicates the request has not
3✔
4280
                // yet been schedule.
3✔
4281
                if connID == UnassignedConnID {
3✔
4282
                        continue
×
4283
                }
4284

4285
                // Skip a particular connection ID if instructed.
4286
                if skip != nil && connID == *skip {
6✔
4287
                        continue
3✔
4288
                }
4289

4290
                s.connMgr.Remove(connID)
3✔
4291
        }
4292

4293
        delete(s.persistentConnReqs, pubStr)
3✔
4294
}
4295

4296
// handleCustomMessage dispatches an incoming custom peers message to
4297
// subscribers.
4298
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4299
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4300
                peer, msg.Type)
3✔
4301

3✔
4302
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4303
                Peer: peer,
3✔
4304
                Msg:  msg,
3✔
4305
        })
3✔
4306
}
3✔
4307

4308
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4309
// messages.
4310
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4311
        return s.customMessageServer.Subscribe()
3✔
4312
}
3✔
4313

4314
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4315
// the channelNotifier's NotifyOpenChannelEvent.
4316
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4317
        remotePub *btcec.PublicKey) {
3✔
4318

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

4325
        // Notify subscribers about this open channel event.
4326
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4327
}
4328

4329
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4330
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4331
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4332
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
3✔
4333

3✔
4334
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4335
        // peer.
3✔
4336
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4337
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4338
                        "channel[%v] pending open",
×
4339
                        remotePub.SerializeCompressed(), op)
×
4340
        }
×
4341

4342
        // Notify subscribers about this event.
4343
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4344
}
4345

4346
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4347
// calls the channelNotifier's NotifyFundingTimeout.
4348
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4349
        remotePub *btcec.PublicKey) {
3✔
4350

3✔
4351
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4352
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4353
        if err != nil {
3✔
4354
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4355
                        "channel[%v] pending close",
×
4356
                        remotePub.SerializeCompressed(), op)
×
4357
        }
×
4358

4359
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4360
                // If we encounter an error while attempting to disconnect the
×
4361
                // peer, log the error.
×
4362
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4363
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4364
                }
×
4365
        }
4366

4367
        // Notify subscribers about this event.
4368
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4369
}
4370

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

3✔
4378
        brontideConn := conn.(*brontide.Conn)
3✔
4379
        addr := conn.RemoteAddr()
3✔
4380
        pubKey := brontideConn.RemotePub()
3✔
4381

3✔
4382
        // Only restrict access for inbound connections, which means if the
3✔
4383
        // remote node's public key is banned or the restricted slots are used
3✔
4384
        // up, we will drop the connection.
3✔
4385
        //
3✔
4386
        // TODO(yy): Consider perform this check in
3✔
4387
        // `peerAccessMan.addPeerAccess`.
3✔
4388
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
3✔
4389
        if inbound && err != nil {
3✔
4390
                pubSer := pubKey.SerializeCompressed()
×
4391

×
4392
                // Clean up the persistent peer maps if we're dropping this
×
4393
                // connection.
×
4394
                s.bannedPersistentPeerConnection(string(pubSer))
×
4395

×
4396
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4397
                        "of restricted-access connection slots: %v.", pubSer,
×
4398
                        err)
×
4399

×
4400
                conn.Close()
×
4401

×
4402
                return
×
4403
        }
×
4404

4405
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4406
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4407

3✔
4408
        peerAddr := &lnwire.NetAddress{
3✔
4409
                IdentityKey: pubKey,
3✔
4410
                Address:     addr,
3✔
4411
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4412
        }
3✔
4413

3✔
4414
        // With the brontide connection established, we'll now craft the feature
3✔
4415
        // vectors to advertise to the remote node.
3✔
4416
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4417
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4418

3✔
4419
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4420
        // found, create a fresh buffer.
3✔
4421
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4422
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4423
        if !ok {
6✔
4424
                var err error
3✔
4425
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4426
                if err != nil {
3✔
4427
                        srvrLog.Errorf("unable to create peer %v", err)
×
4428
                        return
×
4429
                }
×
4430
        }
4431

4432
        // If we directly set the peer.Config TowerClient member to the
4433
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4434
        // the peer.Config's TowerClient member will not evaluate to nil even
4435
        // though the underlying value is nil. To avoid this gotcha which can
4436
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4437
        // TowerClient if needed.
4438
        var towerClient wtclient.ClientManager
3✔
4439
        if s.towerClientMgr != nil {
6✔
4440
                towerClient = s.towerClientMgr
3✔
4441
        }
3✔
4442

4443
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4444
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4445

3✔
4446
        // Now that we've established a connection, create a peer, and it to the
3✔
4447
        // set of currently active peers. Configure the peer with the incoming
3✔
4448
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4449
        // offered that would trigger channel closure. In case of outgoing
3✔
4450
        // htlcs, an extra block is added to prevent the channel from being
3✔
4451
        // closed when the htlc is outstanding and a new block comes in.
3✔
4452
        pCfg := peer.Config{
3✔
4453
                Conn:                    brontideConn,
3✔
4454
                ConnReq:                 connReq,
3✔
4455
                Addr:                    peerAddr,
3✔
4456
                Inbound:                 inbound,
3✔
4457
                Features:                initFeatures,
3✔
4458
                LegacyFeatures:          legacyFeatures,
3✔
4459
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4460
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4461
                ErrorBuffer:             errBuffer,
3✔
4462
                WritePool:               s.writePool,
3✔
4463
                ReadPool:                s.readPool,
3✔
4464
                Switch:                  s.htlcSwitch,
3✔
4465
                InterceptSwitch:         s.interceptableSwitch,
3✔
4466
                ChannelDB:               s.chanStateDB,
3✔
4467
                ChannelGraph:            s.graphDB,
3✔
4468
                ChainArb:                s.chainArb,
3✔
4469
                AuthGossiper:            s.authGossiper,
3✔
4470
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4471
                ChainIO:                 s.cc.ChainIO,
3✔
4472
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4473
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4474
                SigPool:                 s.sigPool,
3✔
4475
                Wallet:                  s.cc.Wallet,
3✔
4476
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4477
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4478
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4479
                Sphinx:                  s.sphinx,
3✔
4480
                WitnessBeacon:           s.witnessBeacon,
3✔
4481
                Invoices:                s.invoices,
3✔
4482
                ChannelNotifier:         s.channelNotifier,
3✔
4483
                HtlcNotifier:            s.htlcNotifier,
3✔
4484
                TowerClient:             towerClient,
3✔
4485
                DisconnectPeer:          s.DisconnectPeer,
3✔
4486
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4487
                        lnwire.NodeAnnouncement, error) {
6✔
4488

3✔
4489
                        return s.genNodeAnnouncement(nil)
3✔
4490
                },
3✔
4491

4492
                PongBuf: s.pongBuf,
4493

4494
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4495

4496
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4497

4498
                FundingManager: s.fundingMgr,
4499

4500
                Hodl:                    s.cfg.Hodl,
4501
                UnsafeReplay:            s.cfg.UnsafeReplay,
4502
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4503
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4504
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4505
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4506
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4507
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4508
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4509
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4510
                HandleCustomMessage:    s.handleCustomMessage,
4511
                GetAliases:             s.aliasMgr.GetAliases,
4512
                RequestAlias:           s.aliasMgr.RequestAlias,
4513
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4514
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4515
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4516
                MaxFeeExposure:         thresholdMSats,
4517
                Quit:                   s.quit,
4518
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4519
                AuxSigner:              s.implCfg.AuxSigner,
4520
                MsgRouter:              s.implCfg.MsgRouter,
4521
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4522
                AuxResolver:            s.implCfg.AuxContractResolver,
4523
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4524
                ShouldFwdExpEndorsement: func() bool {
3✔
4525
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4526
                                return false
3✔
4527
                        }
3✔
4528

4529
                        return clock.NewDefaultClock().Now().Before(
3✔
4530
                                EndorsementExperimentEnd,
3✔
4531
                        )
3✔
4532
                },
4533
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4534
        }
4535

4536
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4537
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4538

3✔
4539
        p := peer.NewBrontide(pCfg)
3✔
4540

3✔
4541
        // Update the access manager with the access permission for this peer.
3✔
4542
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
3✔
4543

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

3✔
4547
        s.addPeer(p)
3✔
4548

3✔
4549
        // Once we have successfully added the peer to the server, we can
3✔
4550
        // delete the previous error buffer from the server's map of error
3✔
4551
        // buffers.
3✔
4552
        delete(s.peerErrors, pkStr)
3✔
4553

3✔
4554
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4555
        // includes sending and receiving Init messages, which would be a DOS
3✔
4556
        // vector if we held the server's mutex throughout the procedure.
3✔
4557
        s.wg.Add(1)
3✔
4558
        go s.peerInitializer(p)
3✔
4559
}
4560

4561
// addPeer adds the passed peer to the server's global state of all active
4562
// peers.
4563
func (s *server) addPeer(p *peer.Brontide) {
3✔
4564
        if p == nil {
3✔
4565
                return
×
4566
        }
×
4567

4568
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4569

3✔
4570
        // Ignore new peers if we're shutting down.
3✔
4571
        if s.Stopped() {
3✔
4572
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4573
                        pubBytes)
×
4574
                p.Disconnect(ErrServerShuttingDown)
×
4575

×
4576
                return
×
4577
        }
×
4578

4579
        // Track the new peer in our indexes so we can quickly look it up either
4580
        // according to its public key, or its peer ID.
4581
        // TODO(roasbeef): pipe all requests through to the
4582
        // queryHandler/peerManager
4583

4584
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4585
        // be human-readable.
4586
        pubStr := string(pubBytes)
3✔
4587

3✔
4588
        s.peersByPub[pubStr] = p
3✔
4589

3✔
4590
        if p.Inbound() {
6✔
4591
                s.inboundPeers[pubStr] = p
3✔
4592
        } else {
6✔
4593
                s.outboundPeers[pubStr] = p
3✔
4594
        }
3✔
4595

4596
        // Inform the peer notifier of a peer online event so that it can be reported
4597
        // to clients listening for peer events.
4598
        var pubKey [33]byte
3✔
4599
        copy(pubKey[:], pubBytes)
3✔
4600

3✔
4601
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4602
}
4603

4604
// peerInitializer asynchronously starts a newly connected peer after it has
4605
// been added to the server's peer map. This method sets up a
4606
// peerTerminationWatcher for the given peer, and ensures that it executes even
4607
// if the peer failed to start. In the event of a successful connection, this
4608
// method reads the negotiated, local feature-bits and spawns the appropriate
4609
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4610
// be signaled of the new peer once the method returns.
4611
//
4612
// NOTE: This MUST be launched as a goroutine.
4613
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4614
        defer s.wg.Done()
3✔
4615

3✔
4616
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4617

3✔
4618
        // Avoid initializing peers while the server is exiting.
3✔
4619
        if s.Stopped() {
3✔
4620
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4621
                        pubBytes)
×
4622
                return
×
4623
        }
×
4624

4625
        // Create a channel that will be used to signal a successful start of
4626
        // the link. This prevents the peer termination watcher from beginning
4627
        // its duty too early.
4628
        ready := make(chan struct{})
3✔
4629

3✔
4630
        // Before starting the peer, launch a goroutine to watch for the
3✔
4631
        // unexpected termination of this peer, which will ensure all resources
3✔
4632
        // are properly cleaned up, and re-establish persistent connections when
3✔
4633
        // necessary. The peer termination watcher will be short circuited if
3✔
4634
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4635
        // that the server has already handled the removal of this peer.
3✔
4636
        s.wg.Add(1)
3✔
4637
        go s.peerTerminationWatcher(p, ready)
3✔
4638

3✔
4639
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4640
        // will unblock the peerTerminationWatcher.
3✔
4641
        if err := p.Start(); err != nil {
6✔
4642
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4643

3✔
4644
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4645
                return
3✔
4646
        }
3✔
4647

4648
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4649
        // was successful, and to begin watching the peer's wait group.
4650
        close(ready)
3✔
4651

3✔
4652
        s.mu.Lock()
3✔
4653
        defer s.mu.Unlock()
3✔
4654

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

3✔
4658
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4659
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4660
        pubStr := string(pubBytes)
3✔
4661
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4662
                select {
3✔
4663
                case peerChan <- p:
3✔
4664
                case <-s.quit:
×
4665
                        return
×
4666
                }
4667
        }
4668
        delete(s.peerConnectedListeners, pubStr)
3✔
4669
}
4670

4671
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4672
// and then cleans up all resources allocated to the peer, notifies relevant
4673
// sub-systems of its demise, and finally handles re-connecting to the peer if
4674
// it's persistent. If the server intentionally disconnects a peer, it should
4675
// have a corresponding entry in the ignorePeerTermination map which will cause
4676
// the cleanup routine to exit early. The passed `ready` chan is used to
4677
// synchronize when WaitForDisconnect should begin watching on the peer's
4678
// waitgroup. The ready chan should only be signaled if the peer starts
4679
// successfully, otherwise the peer should be disconnected instead.
4680
//
4681
// NOTE: This MUST be launched as a goroutine.
4682
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4683
        defer s.wg.Done()
3✔
4684

3✔
4685
        ctx := context.TODO()
3✔
4686

3✔
4687
        p.WaitForDisconnect(ready)
3✔
4688

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

3✔
4691
        // If the server is exiting then we can bail out early ourselves as all
3✔
4692
        // the other sub-systems will already be shutting down.
3✔
4693
        if s.Stopped() {
6✔
4694
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4695
                return
3✔
4696
        }
3✔
4697

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

3✔
4704
        pubKey := p.IdentityKey()
3✔
4705

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

3✔
4710
        // Tell the switch to remove all links associated with this peer.
3✔
4711
        // Passing nil as the target link indicates that all links associated
3✔
4712
        // with this interface should be closed.
3✔
4713
        //
3✔
4714
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4715
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4716
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4717
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4718
        }
×
4719

4720
        for _, link := range links {
6✔
4721
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4722
        }
3✔
4723

4724
        s.mu.Lock()
3✔
4725
        defer s.mu.Unlock()
3✔
4726

3✔
4727
        // If there were any notification requests for when this peer
3✔
4728
        // disconnected, we can trigger them now.
3✔
4729
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4730
        pubStr := string(pubKey.SerializeCompressed())
3✔
4731
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4732
                close(offlineChan)
3✔
4733
        }
3✔
4734
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4735

3✔
4736
        // If the server has already removed this peer, we can short circuit the
3✔
4737
        // peer termination watcher and skip cleanup.
3✔
4738
        if _, ok := s.ignorePeerTermination[p]; ok {
6✔
4739
                delete(s.ignorePeerTermination, p)
3✔
4740

3✔
4741
                pubKey := p.PubKey()
3✔
4742
                pubStr := string(pubKey[:])
3✔
4743

3✔
4744
                // If a connection callback is present, we'll go ahead and
3✔
4745
                // execute it now that previous peer has fully disconnected. If
3✔
4746
                // the callback is not present, this likely implies the peer was
3✔
4747
                // purposefully disconnected via RPC, and that no reconnect
3✔
4748
                // should be attempted.
3✔
4749
                connCallback, ok := s.scheduledPeerConnection[pubStr]
3✔
4750
                if ok {
6✔
4751
                        delete(s.scheduledPeerConnection, pubStr)
3✔
4752
                        connCallback()
3✔
4753
                }
3✔
4754
                return
3✔
4755
        }
4756

4757
        // First, cleanup any remaining state the server has regarding the peer
4758
        // in question.
4759
        s.removePeerUnsafe(p)
3✔
4760

3✔
4761
        // Next, check to see if this is a persistent peer or not.
3✔
4762
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4763
                return
3✔
4764
        }
3✔
4765

4766
        // Get the last address that we used to connect to the peer.
4767
        addrs := []net.Addr{
3✔
4768
                p.NetAddress().Address,
3✔
4769
        }
3✔
4770

3✔
4771
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4772
        // reconnection purposes.
3✔
4773
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
3✔
4774
        switch {
3✔
4775
        // We found advertised addresses, so use them.
4776
        case err == nil:
3✔
4777
                addrs = advertisedAddrs
3✔
4778

4779
        // The peer doesn't have an advertised address.
4780
        case err == errNoAdvertisedAddr:
3✔
4781
                // If it is an outbound peer then we fall back to the existing
3✔
4782
                // peer address.
3✔
4783
                if !p.Inbound() {
6✔
4784
                        break
3✔
4785
                }
4786

4787
                // Fall back to the existing peer address if
4788
                // we're not accepting connections over Tor.
4789
                if s.torController == nil {
6✔
4790
                        break
3✔
4791
                }
4792

4793
                // If we are, the peer's address won't be known
4794
                // to us (we'll see a private address, which is
4795
                // the address used by our onion service to dial
4796
                // to lnd), so we don't have enough information
4797
                // to attempt a reconnect.
4798
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4799
                        "to inbound peer %v without "+
×
4800
                        "advertised address", p)
×
4801
                return
×
4802

4803
        // We came across an error retrieving an advertised
4804
        // address, log it, and fall back to the existing peer
4805
        // address.
4806
        default:
3✔
4807
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4808
                        "address for node %x: %v", p.PubKey(),
3✔
4809
                        err)
3✔
4810
        }
4811

4812
        // Make an easy lookup map so that we can check if an address
4813
        // is already in the address list that we have stored for this peer.
4814
        existingAddrs := make(map[string]bool)
3✔
4815
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4816
                existingAddrs[addr.String()] = true
3✔
4817
        }
3✔
4818

4819
        // Add any missing addresses for this peer to persistentPeerAddr.
4820
        for _, addr := range addrs {
6✔
4821
                if existingAddrs[addr.String()] {
3✔
4822
                        continue
×
4823
                }
4824

4825
                s.persistentPeerAddrs[pubStr] = append(
3✔
4826
                        s.persistentPeerAddrs[pubStr],
3✔
4827
                        &lnwire.NetAddress{
3✔
4828
                                IdentityKey: p.IdentityKey(),
3✔
4829
                                Address:     addr,
3✔
4830
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4831
                        },
3✔
4832
                )
3✔
4833
        }
4834

4835
        // Record the computed backoff in the backoff map.
4836
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4837
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4838

3✔
4839
        // Initialize a retry canceller for this peer if one does not
3✔
4840
        // exist.
3✔
4841
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4842
        if !ok {
6✔
4843
                cancelChan = make(chan struct{})
3✔
4844
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4845
        }
3✔
4846

4847
        // We choose not to wait group this go routine since the Connect
4848
        // call can stall for arbitrarily long if we shutdown while an
4849
        // outbound connection attempt is being made.
4850
        go func() {
6✔
4851
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4852
                        "persistent peer %x in %s",
3✔
4853
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4854

3✔
4855
                select {
3✔
4856
                case <-time.After(backoff):
3✔
4857
                case <-cancelChan:
3✔
4858
                        return
3✔
4859
                case <-s.quit:
3✔
4860
                        return
3✔
4861
                }
4862

4863
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4864
                        "connection to peer %x",
3✔
4865
                        p.IdentityKey().SerializeCompressed())
3✔
4866

3✔
4867
                s.connectToPersistentPeer(pubStr)
3✔
4868
        }()
4869
}
4870

4871
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4872
// to connect to the peer. It creates connection requests if there are
4873
// currently none for a given address and it removes old connection requests
4874
// if the associated address is no longer in the latest address list for the
4875
// peer.
4876
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4877
        s.mu.Lock()
3✔
4878
        defer s.mu.Unlock()
3✔
4879

3✔
4880
        // Create an easy lookup map of the addresses we have stored for the
3✔
4881
        // peer. We will remove entries from this map if we have existing
3✔
4882
        // connection requests for the associated address and then any leftover
3✔
4883
        // entries will indicate which addresses we should create new
3✔
4884
        // connection requests for.
3✔
4885
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4886
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4887
                addrMap[addr.String()] = addr
3✔
4888
        }
3✔
4889

4890
        // Go through each of the existing connection requests and
4891
        // check if they correspond to the latest set of addresses. If
4892
        // there is a connection requests that does not use one of the latest
4893
        // advertised addresses then remove that connection request.
4894
        var updatedConnReqs []*connmgr.ConnReq
3✔
4895
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4896
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4897

3✔
4898
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4899
                // If the existing connection request is using one of the
4900
                // latest advertised addresses for the peer then we add it to
4901
                // updatedConnReqs and remove the associated address from
4902
                // addrMap so that we don't recreate this connReq later on.
4903
                case true:
×
4904
                        updatedConnReqs = append(
×
4905
                                updatedConnReqs, connReq,
×
4906
                        )
×
4907
                        delete(addrMap, lnAddr)
×
4908

4909
                // If the existing connection request is using an address that
4910
                // is not one of the latest advertised addresses for the peer
4911
                // then we remove the connecting request from the connection
4912
                // manager.
4913
                case false:
3✔
4914
                        srvrLog.Info(
3✔
4915
                                "Removing conn req:", connReq.Addr.String(),
3✔
4916
                        )
3✔
4917
                        s.connMgr.Remove(connReq.ID())
3✔
4918
                }
4919
        }
4920

4921
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4922

3✔
4923
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4924
        if !ok {
6✔
4925
                cancelChan = make(chan struct{})
3✔
4926
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4927
        }
3✔
4928

4929
        // Any addresses left in addrMap are new ones that we have not made
4930
        // connection requests for. So create new connection requests for those.
4931
        // If there is more than one address in the address map, stagger the
4932
        // creation of the connection requests for those.
4933
        go func() {
6✔
4934
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4935
                defer ticker.Stop()
3✔
4936

3✔
4937
                for _, addr := range addrMap {
6✔
4938
                        // Send the persistent connection request to the
3✔
4939
                        // connection manager, saving the request itself so we
3✔
4940
                        // can cancel/restart the process as needed.
3✔
4941
                        connReq := &connmgr.ConnReq{
3✔
4942
                                Addr:      addr,
3✔
4943
                                Permanent: true,
3✔
4944
                        }
3✔
4945

3✔
4946
                        s.mu.Lock()
3✔
4947
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4948
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4949
                        )
3✔
4950
                        s.mu.Unlock()
3✔
4951

3✔
4952
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4953
                                "channel peer %v", addr)
3✔
4954

3✔
4955
                        go s.connMgr.Connect(connReq)
3✔
4956

3✔
4957
                        select {
3✔
4958
                        case <-s.quit:
3✔
4959
                                return
3✔
4960
                        case <-cancelChan:
3✔
4961
                                return
3✔
4962
                        case <-ticker.C:
3✔
4963
                        }
4964
                }
4965
        }()
4966
}
4967

4968
// removePeerUnsafe removes the passed peer from the server's state of all
4969
// active peers.
4970
//
4971
// NOTE: Server mutex must be held when calling this function.
4972
func (s *server) removePeerUnsafe(p *peer.Brontide) {
3✔
4973
        if p == nil {
3✔
4974
                return
×
4975
        }
×
4976

4977
        srvrLog.Debugf("Removing peer %v", p)
3✔
4978

3✔
4979
        // Exit early if we have already been instructed to shutdown, the peers
3✔
4980
        // will be disconnected in the server shutdown process.
3✔
4981
        if s.Stopped() {
3✔
4982
                return
×
4983
        }
×
4984

4985
        // Capture the peer's public key and string representation.
4986
        pKey := p.PubKey()
3✔
4987
        pubSer := pKey[:]
3✔
4988
        pubStr := string(pubSer)
3✔
4989

3✔
4990
        delete(s.peersByPub, pubStr)
3✔
4991

3✔
4992
        if p.Inbound() {
6✔
4993
                delete(s.inboundPeers, pubStr)
3✔
4994
        } else {
6✔
4995
                delete(s.outboundPeers, pubStr)
3✔
4996
        }
3✔
4997

4998
        // When removing the peer we make sure to disconnect it asynchronously
4999
        // to avoid blocking the main server goroutine because it is holding the
5000
        // server's mutex. Disconnecting the peer might block and wait until the
5001
        // peer has fully started up. This can happen if an inbound and outbound
5002
        // race condition occurs.
5003
        s.wg.Add(1)
3✔
5004
        go func() {
6✔
5005
                defer s.wg.Done()
3✔
5006

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

3✔
5009
                // If this peer had an active persistent connection request,
3✔
5010
                // remove it.
3✔
5011
                if p.ConnReq() != nil {
6✔
5012
                        s.connMgr.Remove(p.ConnReq().ID())
3✔
5013
                }
3✔
5014

5015
                // Remove the peer's access permission from the access manager.
5016
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
3✔
5017
                s.peerAccessMan.removePeerAccess(peerPubStr)
3✔
5018

3✔
5019
                // Copy the peer's error buffer across to the server if it has
3✔
5020
                // any items in it so that we can restore peer errors across
3✔
5021
                // connections. We need to look up the error after the peer has
3✔
5022
                // been disconnected because we write the error in the
3✔
5023
                // `Disconnect` method.
3✔
5024
                s.mu.Lock()
3✔
5025
                if p.ErrorBuffer().Total() > 0 {
6✔
5026
                        s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
5027
                }
3✔
5028
                s.mu.Unlock()
3✔
5029

3✔
5030
                // Inform the peer notifier of a peer offline event so that it
3✔
5031
                // can be reported to clients listening for peer events.
3✔
5032
                var pubKey [33]byte
3✔
5033
                copy(pubKey[:], pubSer)
3✔
5034

3✔
5035
                s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
5036
        }()
5037
}
5038

5039
// ConnectToPeer requests that the server connect to a Lightning Network peer
5040
// at the specified address. This function will *block* until either a
5041
// connection is established, or the initial handshake process fails.
5042
//
5043
// NOTE: This function is safe for concurrent access.
5044
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
5045
        perm bool, timeout time.Duration) error {
3✔
5046

3✔
5047
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
5048

3✔
5049
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
5050
        // better granularity.  In certain conditions, this method requires
3✔
5051
        // making an outbound connection to a remote peer, which requires the
3✔
5052
        // lock to be released, and subsequently reacquired.
3✔
5053
        s.mu.Lock()
3✔
5054

3✔
5055
        // Ensure we're not already connected to this peer.
3✔
5056
        peer, err := s.findPeerByPubStr(targetPub)
3✔
5057

3✔
5058
        // When there's no error it means we already have a connection with this
3✔
5059
        // peer. If this is a dev environment with the `--unsafeconnect` flag
3✔
5060
        // set, we will ignore the existing connection and continue.
3✔
5061
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
6✔
5062
                s.mu.Unlock()
3✔
5063
                return &errPeerAlreadyConnected{peer: peer}
3✔
5064
        }
3✔
5065

5066
        // Peer was not found, continue to pursue connection with peer.
5067

5068
        // If there's already a pending connection request for this pubkey,
5069
        // then we ignore this request to ensure we don't create a redundant
5070
        // connection.
5071
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
5072
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
5073
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
5074
        }
3✔
5075

5076
        // If there's not already a pending or active connection to this node,
5077
        // then instruct the connection manager to attempt to establish a
5078
        // persistent connection to the peer.
5079
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5080
        if perm {
6✔
5081
                connReq := &connmgr.ConnReq{
3✔
5082
                        Addr:      addr,
3✔
5083
                        Permanent: true,
3✔
5084
                }
3✔
5085

3✔
5086
                // Since the user requested a permanent connection, we'll set
3✔
5087
                // the entry to true which will tell the server to continue
3✔
5088
                // reconnecting even if the number of channels with this peer is
3✔
5089
                // zero.
3✔
5090
                s.persistentPeers[targetPub] = true
3✔
5091
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5092
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5093
                }
3✔
5094
                s.persistentConnReqs[targetPub] = append(
3✔
5095
                        s.persistentConnReqs[targetPub], connReq,
3✔
5096
                )
3✔
5097
                s.mu.Unlock()
3✔
5098

3✔
5099
                go s.connMgr.Connect(connReq)
3✔
5100

3✔
5101
                return nil
3✔
5102
        }
5103
        s.mu.Unlock()
3✔
5104

3✔
5105
        // If we're not making a persistent connection, then we'll attempt to
3✔
5106
        // connect to the target peer. If the we can't make the connection, or
3✔
5107
        // the crypto negotiation breaks down, then return an error to the
3✔
5108
        // caller.
3✔
5109
        errChan := make(chan error, 1)
3✔
5110
        s.connectToPeer(addr, errChan, timeout)
3✔
5111

3✔
5112
        select {
3✔
5113
        case err := <-errChan:
3✔
5114
                return err
3✔
5115
        case <-s.quit:
×
5116
                return ErrServerShuttingDown
×
5117
        }
5118
}
5119

5120
// connectToPeer establishes a connection to a remote peer. errChan is used to
5121
// notify the caller if the connection attempt has failed. Otherwise, it will be
5122
// closed.
5123
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5124
        errChan chan<- error, timeout time.Duration) {
3✔
5125

3✔
5126
        conn, err := brontide.Dial(
3✔
5127
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5128
        )
3✔
5129
        if err != nil {
6✔
5130
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5131
                select {
3✔
5132
                case errChan <- err:
3✔
5133
                case <-s.quit:
×
5134
                }
5135
                return
3✔
5136
        }
5137

5138
        close(errChan)
3✔
5139

3✔
5140
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5141
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5142

3✔
5143
        s.OutboundPeerConnected(nil, conn)
3✔
5144
}
5145

5146
// DisconnectPeer sends the request to server to close the connection with peer
5147
// identified by public key.
5148
//
5149
// NOTE: This function is safe for concurrent access.
5150
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5151
        pubBytes := pubKey.SerializeCompressed()
3✔
5152
        pubStr := string(pubBytes)
3✔
5153

3✔
5154
        s.mu.Lock()
3✔
5155
        defer s.mu.Unlock()
3✔
5156

3✔
5157
        // Check that were actually connected to this peer. If not, then we'll
3✔
5158
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5159
        // currently connected to.
3✔
5160
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5161
        if err == ErrPeerNotConnected {
6✔
5162
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5163
        }
3✔
5164

5165
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5166

3✔
5167
        s.cancelConnReqs(pubStr, nil)
3✔
5168

3✔
5169
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5170
        // them from this map so we don't attempt to re-connect after we
3✔
5171
        // disconnect.
3✔
5172
        delete(s.persistentPeers, pubStr)
3✔
5173
        delete(s.persistentPeersBackoff, pubStr)
3✔
5174

3✔
5175
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5176
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
3✔
5177
        //
3✔
5178
        // NOTE: We call it in a goroutine to avoid blocking the main server
3✔
5179
        // goroutine because we might hold the server's mutex.
3✔
5180
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5181

3✔
5182
        return nil
3✔
5183
}
5184

5185
// OpenChannel sends a request to the server to open a channel to the specified
5186
// peer identified by nodeKey with the passed channel funding parameters.
5187
//
5188
// NOTE: This function is safe for concurrent access.
5189
func (s *server) OpenChannel(
5190
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5191

3✔
5192
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5193
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5194
        // not blocked if the caller is not reading the updates.
3✔
5195
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5196
        req.Err = make(chan error, 1)
3✔
5197

3✔
5198
        // First attempt to locate the target peer to open a channel with, if
3✔
5199
        // we're unable to locate the peer then this request will fail.
3✔
5200
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5201
        s.mu.RLock()
3✔
5202
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5203
        if !ok {
3✔
5204
                s.mu.RUnlock()
×
5205

×
5206
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5207
                return req.Updates, req.Err
×
5208
        }
×
5209
        req.Peer = peer
3✔
5210
        s.mu.RUnlock()
3✔
5211

3✔
5212
        // We'll wait until the peer is active before beginning the channel
3✔
5213
        // opening process.
3✔
5214
        select {
3✔
5215
        case <-peer.ActiveSignal():
3✔
5216
        case <-peer.QuitSignal():
×
5217
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5218
                return req.Updates, req.Err
×
5219
        case <-s.quit:
×
5220
                req.Err <- ErrServerShuttingDown
×
5221
                return req.Updates, req.Err
×
5222
        }
5223

5224
        // If the fee rate wasn't specified at this point we fail the funding
5225
        // because of the missing fee rate information. The caller of the
5226
        // `OpenChannel` method needs to make sure that default values for the
5227
        // fee rate are set beforehand.
5228
        if req.FundingFeePerKw == 0 {
3✔
5229
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5230
                        "the channel opening transaction")
×
5231

×
5232
                return req.Updates, req.Err
×
5233
        }
×
5234

5235
        // Spawn a goroutine to send the funding workflow request to the funding
5236
        // manager. This allows the server to continue handling queries instead
5237
        // of blocking on this request which is exported as a synchronous
5238
        // request to the outside world.
5239
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5240

3✔
5241
        return req.Updates, req.Err
3✔
5242
}
5243

5244
// Peers returns a slice of all active peers.
5245
//
5246
// NOTE: This function is safe for concurrent access.
5247
func (s *server) Peers() []*peer.Brontide {
3✔
5248
        s.mu.RLock()
3✔
5249
        defer s.mu.RUnlock()
3✔
5250

3✔
5251
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5252
        for _, peer := range s.peersByPub {
6✔
5253
                peers = append(peers, peer)
3✔
5254
        }
3✔
5255

5256
        return peers
3✔
5257
}
5258

5259
// computeNextBackoff uses a truncated exponential backoff to compute the next
5260
// backoff using the value of the exiting backoff. The returned duration is
5261
// randomized in either direction by 1/20 to prevent tight loops from
5262
// stabilizing.
5263
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5264
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5265
        nextBackoff := 2 * currBackoff
3✔
5266
        if nextBackoff > maxBackoff {
6✔
5267
                nextBackoff = maxBackoff
3✔
5268
        }
3✔
5269

5270
        // Using 1/10 of our duration as a margin, compute a random offset to
5271
        // avoid the nodes entering connection cycles.
5272
        margin := nextBackoff / 10
3✔
5273

3✔
5274
        var wiggle big.Int
3✔
5275
        wiggle.SetUint64(uint64(margin))
3✔
5276
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5277
                // Randomizing is not mission critical, so we'll just return the
×
5278
                // current backoff.
×
5279
                return nextBackoff
×
5280
        }
×
5281

5282
        // Otherwise add in our wiggle, but subtract out half of the margin so
5283
        // that the backoff can tweaked by 1/20 in either direction.
5284
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5285
}
5286

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

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

3✔
5295
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5296
        if err != nil {
3✔
5297
                return nil, err
×
5298
        }
×
5299

5300
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
3✔
5301
        if err != nil {
6✔
5302
                return nil, err
3✔
5303
        }
3✔
5304

5305
        if len(node.Addresses) == 0 {
6✔
5306
                return nil, errNoAdvertisedAddr
3✔
5307
        }
3✔
5308

5309
        return node.Addresses, nil
3✔
5310
}
5311

5312
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5313
// channel update for a target channel.
5314
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5315
        *lnwire.ChannelUpdate1, error) {
3✔
5316

3✔
5317
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5318
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5319
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5320
                if err != nil {
6✔
5321
                        return nil, err
3✔
5322
                }
3✔
5323

5324
                return netann.ExtractChannelUpdate(
3✔
5325
                        ourPubKey[:], info, edge1, edge2,
3✔
5326
                )
3✔
5327
        }
5328
}
5329

5330
// applyChannelUpdate applies the channel update to the different sub-systems of
5331
// the server. The useAlias boolean denotes whether or not to send an alias in
5332
// place of the real SCID.
5333
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5334
        op *wire.OutPoint, useAlias bool) error {
3✔
5335

3✔
5336
        var (
3✔
5337
                peerAlias    *lnwire.ShortChannelID
3✔
5338
                defaultAlias lnwire.ShortChannelID
3✔
5339
        )
3✔
5340

3✔
5341
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5342

3✔
5343
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5344
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5345
        if useAlias {
6✔
5346
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5347
                if foundAlias != defaultAlias {
6✔
5348
                        peerAlias = &foundAlias
3✔
5349
                }
3✔
5350
        }
5351

5352
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5353
                update, discovery.RemoteAlias(peerAlias),
3✔
5354
        )
3✔
5355
        select {
3✔
5356
        case err := <-errChan:
3✔
5357
                return err
3✔
5358
        case <-s.quit:
×
5359
                return ErrServerShuttingDown
×
5360
        }
5361
}
5362

5363
// SendCustomMessage sends a custom message to the peer with the specified
5364
// pubkey.
5365
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5366
        data []byte) error {
3✔
5367

3✔
5368
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5369
        if err != nil {
3✔
5370
                return err
×
5371
        }
×
5372

5373
        // We'll wait until the peer is active.
5374
        select {
3✔
5375
        case <-peer.ActiveSignal():
3✔
5376
        case <-peer.QuitSignal():
×
5377
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5378
        case <-s.quit:
×
5379
                return ErrServerShuttingDown
×
5380
        }
5381

5382
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5383
        if err != nil {
6✔
5384
                return err
3✔
5385
        }
3✔
5386

5387
        // Send the message as low-priority. For now we assume that all
5388
        // application-defined message are low priority.
5389
        return peer.SendMessageLazy(true, msg)
3✔
5390
}
5391

5392
// newSweepPkScriptGen creates closure that generates a new public key script
5393
// which should be used to sweep any funds into the on-chain wallet.
5394
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5395
// (p2wkh) output.
5396
func newSweepPkScriptGen(
5397
        wallet lnwallet.WalletController,
5398
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5399

3✔
5400
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5401
                sweepAddr, err := wallet.NewAddress(
3✔
5402
                        lnwallet.TaprootPubkey, false,
3✔
5403
                        lnwallet.DefaultAccountName,
3✔
5404
                )
3✔
5405
                if err != nil {
3✔
5406
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5407
                }
×
5408

5409
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5410
                if err != nil {
3✔
5411
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5412
                }
×
5413

5414
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5415
                        wallet, netParams, addr,
3✔
5416
                )
3✔
5417
                if err != nil {
3✔
5418
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5419
                }
×
5420

5421
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5422
                        DeliveryAddress: addr,
3✔
5423
                        InternalKey:     internalKeyDesc,
3✔
5424
                })
3✔
5425
        }
5426
}
5427

5428
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5429
// finished.
5430
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5431
        // Get a list of closed channels.
3✔
5432
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5433
        if err != nil {
3✔
5434
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5435
                return nil
×
5436
        }
×
5437

5438
        // Save the SCIDs in a map.
5439
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5440
        for _, c := range channels {
6✔
5441
                // If the channel is not pending, its FC has been finalized.
3✔
5442
                if !c.IsPending {
6✔
5443
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5444
                }
3✔
5445
        }
5446

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

5461
        for _, c := range pendings {
6✔
5462
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5463
                        continue
3✔
5464
                }
5465

5466
                // If the channel is still reported as pending, remove it from
5467
                // the map.
5468
                delete(closedSCIDs, c.ShortChannelID)
×
5469

×
5470
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5471
                        c.ShortChannelID)
×
5472
        }
5473

5474
        return closedSCIDs
3✔
5475
}
5476

5477
// getStartingBeat returns the current beat. This is used during the startup to
5478
// initialize blockbeat consumers.
5479
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5480
        // beat is the current blockbeat.
3✔
5481
        var beat *chainio.Beat
3✔
5482

3✔
5483
        // If the node is configured with nochainbackend mode (remote signer),
3✔
5484
        // we will skip fetching the best block.
3✔
5485
        if s.cfg.Bitcoin.Node == "nochainbackend" {
3✔
5486
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5487
                        "mode")
×
5488

×
5489
                return &chainio.Beat{}, nil
×
5490
        }
×
5491

5492
        // We should get a notification with the current best block immediately
5493
        // by passing a nil block.
5494
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5495
        if err != nil {
3✔
5496
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5497
        }
×
5498
        defer blockEpochs.Cancel()
3✔
5499

3✔
5500
        // We registered for the block epochs with a nil request. The notifier
3✔
5501
        // should send us the current best block immediately. So we need to
3✔
5502
        // wait for it here because we need to know the current best height.
3✔
5503
        select {
3✔
5504
        case bestBlock := <-blockEpochs.Epochs:
3✔
5505
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5506
                        bestBlock.Hash, bestBlock.Height)
3✔
5507

3✔
5508
                // Update the current blockbeat.
3✔
5509
                beat = chainio.NewBeat(*bestBlock)
3✔
5510

5511
        case <-s.quit:
×
5512
                srvrLog.Debug("LND shutting down")
×
5513
        }
5514

5515
        return beat, nil
3✔
5516
}
5517

5518
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5519
// point has an active RBF chan closer.
5520
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5521
        chanPoint wire.OutPoint) bool {
3✔
5522

3✔
5523
        pubBytes := peerPub.SerializeCompressed()
3✔
5524

3✔
5525
        s.mu.RLock()
3✔
5526
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5527
        s.mu.RUnlock()
3✔
5528
        if !ok {
3✔
5529
                return false
×
5530
        }
×
5531

5532
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5533
}
5534

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

3✔
5543
        // First, we'll attempt to look up the channel based on it's
3✔
5544
        // ChannelPoint.
3✔
5545
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5546
        if err != nil {
3✔
5547
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5548
        }
×
5549

5550
        // From the channel, we can now get the pubkey of the peer, then use
5551
        // that to eventually get the chan closer.
5552
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5553

3✔
5554
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5555
        s.mu.RLock()
3✔
5556
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5557
        s.mu.RUnlock()
3✔
5558
        if !ok {
3✔
5559
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5560
                        "not online", chanPoint)
×
5561
        }
×
5562

5563
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5564
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5565
        )
3✔
5566
        if err != nil {
3✔
5567
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5568
                        "%w", err)
×
5569
        }
×
5570

5571
        return closeUpdates, nil
3✔
5572
}
5573

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

3✔
5582
        // If the channel is present in the switch, then the request should flow
3✔
5583
        // through the switch instead.
3✔
5584
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5585
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5586
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5587
                        "invalid request", chanPoint)
×
5588
        }
×
5589

5590
        // At this point, we know that the channel isn't present in the link, so
5591
        // we'll check to see if we have an entry in the active chan closer map.
5592
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5593
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5594
        )
3✔
5595
        if err != nil {
3✔
5596
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5597
                        "ChannelPoint(%v)", chanPoint)
×
5598
        }
×
5599

5600
        return updates, nil
3✔
5601
}
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