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

lightningnetwork / lnd / 16301175807

15 Jul 2025 06:21PM UTC coverage: 55.206% (-2.4%) from 57.559%
16301175807

Pull #10075

github

web-flow
Merge 9039cd139 into 7f491dbd8
Pull Request #10075: Fix flake in `TestChangeWalletPasswordStateless`

108554 of 196635 relevant lines covered (55.21%)

22247.78 hits per line

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

0.0
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

204
        case peerStatusTemporary:
×
205
                return "temporary"
×
206

207
        case peerStatusProtected:
×
208
                return "protected"
×
209

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

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

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

230
        start sync.Once
231
        stop  sync.Once
232

233
        cfg *Config
234

235
        implCfg *ImplementationCfg
236

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

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

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

248
        chanStatusMgr *netann.ChanStatusManager
249

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

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

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

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

270
        mu sync.RWMutex
271

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

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

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

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

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

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

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

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

322
        cc *chainreg.ChainControl
323

324
        fundingMgr *funding.Manager
325

326
        graphDB *graphdb.ChannelGraph
327

328
        chanStateDB *channeldb.ChannelStateDB
329

330
        addrSource channeldb.AddrSource
331

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

336
        invoicesDB invoices.InvoiceDB
337

338
        aliasMgr *aliasmgr.Manager
339

340
        htlcSwitch *htlcswitch.Switch
341

342
        interceptableSwitch *htlcswitch.InterceptableSwitch
343

344
        invoices *invoices.InvoiceRegistry
345

346
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
347

348
        channelNotifier *channelnotifier.ChannelNotifier
349

350
        peerNotifier *peernotifier.PeerNotifier
351

352
        htlcNotifier *htlcswitch.HtlcNotifier
353

354
        witnessBeacon contractcourt.WitnessBeacon
355

356
        breachArbitrator *contractcourt.BreachArbitrator
357

358
        missionController *routing.MissionController
359
        defaultMC         *routing.MissionControl
360

361
        graphBuilder *graph.Builder
362

363
        chanRouter *routing.ChannelRouter
364

365
        controlTower routing.ControlTower
366

367
        authGossiper *discovery.AuthenticatedGossiper
368

369
        localChanMgr *localchans.Manager
370

371
        utxoNursery *contractcourt.UtxoNursery
372

373
        sweeper *sweep.UtxoSweeper
374

375
        chainArb *contractcourt.ChainArbitrator
376

377
        sphinx *hop.OnionProcessor
378

379
        towerClientMgr *wtclient.Manager
380

381
        connMgr *connmgr.ConnManager
382

383
        sigPool *lnwallet.SigPool
384

385
        writePool *pool.Write
386

387
        readPool *pool.Read
388

389
        tlsManager *TLSManager
390

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

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

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

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

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

413
        hostAnn *netann.HostAnnouncer
414

415
        // livenessMonitor monitors that lnd has access to critical resources.
416
        livenessMonitor *healthcheck.Monitor
417

418
        customMessageServer *subscribe.Server
419

420
        // txPublisher is a publisher with fee-bumping capability.
421
        txPublisher *sweep.TxPublisher
422

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

427
        // peerAccessMan implements peer access controls.
428
        peerAccessMan *accessMan
429

430
        quit chan struct{}
431

432
        wg sync.WaitGroup
433
}
434

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

443
        s.wg.Add(1)
×
444
        go func() {
×
445
                defer func() {
×
446
                        graphSub.Cancel()
×
447
                        s.wg.Done()
×
448
                }()
×
449

450
                for {
×
451
                        select {
×
452
                        case <-s.quit:
×
453
                                return
×
454

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

462
                                for _, update := range topChange.NodeUpdates {
×
463
                                        pubKeyStr := string(
×
464
                                                update.IdentityKey.
×
465
                                                        SerializeCompressed(),
×
466
                                        )
×
467

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

477
                                        addrs := make([]*lnwire.NetAddress, 0,
×
478
                                                len(update.Addresses))
×
479

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

490
                                        s.mu.Lock()
×
491

×
492
                                        // Update the stored addresses for this
×
493
                                        // to peer to reflect the new set.
×
494
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
495

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

506
                                        s.mu.Unlock()
×
507

×
508
                                        s.connectToPersistentPeer(pubKeyStr)
×
509
                                }
510
                        }
511
                }
512
        }()
513

514
        return nil
×
515
}
516

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

522
        // Msg is the custom wire message.
523
        Msg *lnwire.Custom
524
}
525

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

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

550
        if tor.IsOnionHost(host) {
×
551
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
552
        }
×
553

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

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

×
567
        return func(a net.Addr) (net.Conn, error) {
×
568
                lnAddr := a.(*lnwire.NetAddress)
×
569
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
570
        }
×
571
}
572

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

×
586
        var (
×
587
                err         error
×
588
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
589

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

×
597
        var serializedPubKey [33]byte
×
598
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
599

×
600
        netParams := cfg.ActiveNetParams.Params
×
601

×
602
        // Initialize the sphinx router.
×
603
        replayLog := htlcswitch.NewDecayedLog(
×
604
                dbs.DecayedLogDB, cc.ChainNotifier,
×
605
        )
×
606
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
607

×
608
        writeBufferPool := pool.NewWriteBuffer(
×
609
                pool.DefaultWriteBufferGCInterval,
×
610
                pool.DefaultWriteBufferExpiryInterval,
×
611
        )
×
612

×
613
        writePool := pool.NewWrite(
×
614
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
615
        )
×
616

×
617
        readBufferPool := pool.NewReadBuffer(
×
618
                pool.DefaultReadBufferGCInterval,
×
619
                pool.DefaultReadBufferExpiryInterval,
×
620
        )
×
621

×
622
        readPool := pool.NewRead(
×
623
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
624
        )
×
625

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

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

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

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

×
671
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
672

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

×
687
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
688
                        cc.ChainNotifier,
×
689
                ),
×
690
                channelNotifier: channelnotifier.New(
×
691
                        dbs.ChanStateDB.ChannelStateDB(),
×
692
                ),
×
693

×
694
                identityECDH:   nodeKeyECDH,
×
695
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
696
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
697

×
698
                listenAddrs: listenAddrs,
×
699

×
700
                // TODO(roasbeef): derive proper onion key based on rotation
×
701
                // schedule
×
702
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
703

×
704
                torController: torController,
×
705

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

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

×
722
                invoiceHtlcModifier: invoiceHtlcModifier,
×
723

×
724
                customMessageServer: subscribe.NewServer(),
×
725

×
726
                tlsManager: tlsManager,
×
727

×
728
                featureMgr: featureMgr,
×
729
                quit:       make(chan struct{}),
×
730
        }
×
731

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

743
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
744
        if err != nil {
×
745
                return nil, err
×
746
        }
×
747

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

×
756
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
757

×
758
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
759
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
760

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

767
                s.htlcSwitch.UpdateLinkAliases(link)
×
768

×
769
                return nil
×
770
        }
771

772
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
773
        if err != nil {
×
774
                return nil, err
×
775
        }
×
776

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

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

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

829
        s.witnessBeacon = newPreimageBeacon(
×
830
                dbs.ChanStateDB.NewWitnessCache(),
×
831
                s.interceptableSwitch.ForwardPacket,
×
832
        )
×
833

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

×
847
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
848
        if err != nil {
×
849
                return nil, err
×
850
        }
×
851
        s.chanStatusMgr = chanStatusMgr
×
852

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

×
858
                discoveryTimeout := time.Duration(10 * time.Second)
×
859

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

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

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

886
                        s.natTraversal = pmp
×
887
                }
888
        }
889

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

×
905
                        listenPorts = append(listenPorts, uint16(port))
×
906
                }
×
907

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

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

931
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
932
        selfAddrs = append(selfAddrs, externalIPs...)
×
933

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

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

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

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

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

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

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

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

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

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

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

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

×
1051
                        estimator, err = routing.NewAprioriEstimator(
×
1052
                                aprioriConfig,
×
1053
                        )
×
1054
                        if err != nil {
×
1055
                                return nil, err
×
1056
                        }
×
1057

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

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

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

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

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

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

×
1110
        pathFindingConfig := routing.PathFindingConfig{
×
1111
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
1112
                        routingConfig.AttemptCost,
×
1113
                ),
×
1114
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
1115
                MinProbability: routingConfig.MinRouteProbability,
×
1116
        }
×
1117

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

×
1130
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
1131

×
1132
        s.controlTower = routing.NewControlTower(paymentControl)
×
1133

×
1134
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
1135
                cfg.Routing.StrictZombiePruning
×
1136

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

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

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

1184
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
1185

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

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

1230
        accessCfg := &accessManConfig{
×
1231
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
1232
                        error) {
×
1233

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

1243
        peerAccessMan, err := newAccessMan(accessCfg)
×
1244
        if err != nil {
×
1245
                return nil, err
×
1246
        }
×
1247

1248
        s.peerAccessMan = peerAccessMan
×
1249

×
1250
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
1251
        //nolint:ll
×
1252
        s.localChanMgr = &localchans.Manager{
×
1253
                SelfPub:              nodeKeyDesc.PubKey,
×
1254
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
1255
                ForAllOutgoingChannels: func(ctx context.Context,
×
1256
                        cb func(*models.ChannelEdgeInfo,
×
1257
                                *models.ChannelEdgePolicy) error,
×
1258
                        reset func()) error {
×
1259

×
1260
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
1261
                                func(c *models.ChannelEdgeInfo,
×
1262
                                        e *models.ChannelEdgePolicy,
×
1263
                                        _ *models.ChannelEdgePolicy) error {
×
1264

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

×
1277
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1278
                },
×
1279
        }
1280

1281
        utxnStore, err := contractcourt.NewNurseryStore(
×
1282
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
1283
        )
×
1284
        if err != nil {
×
1285
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1286
                return nil, err
×
1287
        }
×
1288

1289
        sweeperStore, err := sweep.NewSweeperStore(
×
1290
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
1291
        )
×
1292
        if err != nil {
×
1293
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1294
                return nil, err
×
1295
        }
×
1296

1297
        aggregator := sweep.NewBudgetAggregator(
×
1298
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
1299
                s.implCfg.AuxSweeper,
×
1300
        )
×
1301

×
1302
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1303
                Signer:     cc.Wallet.Cfg.Signer,
×
1304
                Wallet:     cc.Wallet,
×
1305
                Estimator:  cc.FeeEstimator,
×
1306
                Notifier:   cc.ChainNotifier,
×
1307
                AuxSweeper: s.implCfg.AuxSweeper,
×
1308
        })
×
1309

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

×
1327
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
1328
                ChainIO:             cc.ChainIO,
×
1329
                ConfDepth:           1,
×
1330
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
1331
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
1332
                Notifier:            cc.ChainNotifier,
×
1333
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
1334
                Store:               utxnStore,
×
1335
                SweepInput:          s.sweeper.SweepInput,
×
1336
                Budget:              s.cfg.Sweeper.Budget,
×
1337
        })
×
1338

×
1339
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
1340
        closeLink := func(chanPoint *wire.OutPoint,
×
1341
                closureType contractcourt.ChannelCloseType) {
×
1342
                // TODO(conner): Properly respect the update and error channels
×
1343
                // returned by CloseLink.
×
1344

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

1353
        // We will use the following channel to reliably hand off contract
1354
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1355
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
×
1356

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

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

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

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

×
1427
                        // processACK will handle the BreachArbitrator ACKing
×
1428
                        // the event.
×
1429
                        finalErr := make(chan error, 1)
×
1430
                        processACK := func(brarErr error) {
×
1431
                                if brarErr != nil {
×
1432
                                        finalErr <- brarErr
×
1433
                                        return
×
1434
                                }
×
1435

1436
                                // If the BreachArbitrator successfully handled
1437
                                // the event, we can signal that the handoff
1438
                                // was successful.
1439
                                finalErr <- nil
×
1440
                        }
1441

1442
                        event := &contractcourt.ContractBreachEvent{
×
1443
                                ChanPoint:         chanPoint,
×
1444
                                ProcessACK:        processACK,
×
1445
                                BreachRetribution: breachRet,
×
1446
                        }
×
1447

×
1448
                        // Send the contract breach event to the
×
1449
                        // BreachArbitrator.
×
1450
                        select {
×
1451
                        case contractBreaches <- event:
×
1452
                        case <-s.quit:
×
1453
                                return ErrServerShuttingDown
×
1454
                        }
1455

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

1481
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1482
                QueryIncomingCircuit: func(
1483
                        circuit models.CircuitKey) *models.CircuitKey {
×
1484

×
1485
                        // Get the circuit map.
×
1486
                        circuits := s.htlcSwitch.CircuitLookup()
×
1487

×
1488
                        // Lookup the outgoing circuit.
×
1489
                        pc := circuits.LookupOpenCircuit(circuit)
×
1490
                        if pc == nil {
×
1491
                                return nil
×
1492
                        }
×
1493

1494
                        return &pc.Incoming
×
1495
                },
1496
                AuxLeafStore: implCfg.AuxLeafStore,
1497
                AuxSigner:    implCfg.AuxSigner,
1498
                AuxResolver:  implCfg.AuxContractResolver,
1499
        }, dbs.ChanStateDB)
1500

1501
        // Select the configuration and funding parameters for Bitcoin.
1502
        chainCfg := cfg.Bitcoin
×
1503
        minRemoteDelay := funding.MinBtcRemoteDelay
×
1504
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
1505

×
1506
        var chanIDSeed [32]byte
×
1507
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1508
                return nil, err
×
1509
        }
×
1510

1511
        // Wrap the DeleteChannelEdges method so that the funding manager can
1512
        // use it without depending on several layers of indirection.
1513
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
1514
                *models.ChannelEdgePolicy, error) {
×
1515

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

1529
                // Grab our key to find our policy.
1530
                var ourKey [33]byte
×
1531
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1532

×
1533
                var ourPolicy *models.ChannelEdgePolicy
×
1534
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1535
                        ourPolicy = e1
×
1536
                } else {
×
1537
                        ourPolicy = e2
×
1538
                }
×
1539

1540
                if ourPolicy == nil {
×
1541
                        // Something is wrong, so return an error.
×
1542
                        return nil, fmt.Errorf("we don't have an edge")
×
1543
                }
×
1544

1545
                err = s.graphDB.DeleteChannelEdges(
×
1546
                        false, false, scid.ToUint64(),
×
1547
                )
×
1548
                return ourPolicy, err
×
1549
        }
1550

1551
        // For the reservationTimeout and the zombieSweeperInterval different
1552
        // values are set in case we are in a dev environment so enhance test
1553
        // capacilities.
1554
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
1555
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
1556

×
1557
        // Get the development config for funding manager. If we are not in
×
1558
        // development mode, this would be nil.
×
1559
        var devCfg *funding.DevConfig
×
1560
        if lncfg.IsDevBuild() {
×
1561
                devCfg = &funding.DevConfig{
×
1562
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
1563
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
1564
                                GetMaxWaitNumBlocksFundingConf(),
×
1565
                }
×
1566

×
1567
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
1568
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
1569

×
1570
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1571
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1572
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
1573
        }
×
1574

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

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

×
1613
                        // In case the user has explicitly specified
×
1614
                        // a default value for the number of
×
1615
                        // confirmations, we use it.
×
1616
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
1617
                        if defaultConf != 0 {
×
1618
                                return defaultConf
×
1619
                        }
×
1620

1621
                        minConf := uint64(3)
×
1622
                        maxConf := uint64(6)
×
1623

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

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

×
1652
                        // In case the user has explicitly specified
×
1653
                        // a default value for the remote delay, we
×
1654
                        // use it.
×
1655
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
1656
                        if defaultDelay > 0 {
×
1657
                                return defaultDelay
×
1658
                        }
×
1659

1660
                        // If this is a wumbo channel, then we'll require the
1661
                        // max value.
1662
                        if chanAmt > MaxFundingAmount {
×
1663
                                return maxRemoteDelay
×
1664
                        }
×
1665

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

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

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

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

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

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

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

1779
        // Assemble a peer notifier which will provide clients with subscriptions
1780
        // to peer online and offline events.
1781
        s.peerNotifier = peernotifier.New()
×
1782

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

1798
        if cfg.WtClient.Active {
×
1799
                policy := wtpolicy.DefaultPolicy()
×
1800
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
1801

×
1802
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1803
                // protocol operations on sat/kw.
×
1804
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
1805
                        1000 * cfg.WtClient.SweepFeeRate,
×
1806
                )
×
1807

×
1808
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1809

×
1810
                if err := policy.Validate(); err != nil {
×
1811
                        return nil, err
×
1812
                }
×
1813

1814
                // authDial is the wrapper around the btrontide.Dial for the
1815
                // watchtower.
1816
                authDial := func(localKey keychain.SingleKeyECDH,
×
1817
                        netAddr *lnwire.NetAddress,
×
1818
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
1819

×
1820
                        return brontide.Dial(
×
1821
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1822
                        )
×
1823
                }
×
1824

1825
                // buildBreachRetribution is a call-back that can be used to
1826
                // query the BreachRetribution info and channel type given a
1827
                // channel ID and commitment height.
1828
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
1829
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
1830
                        channeldb.ChannelType, error) {
×
1831

×
1832
                        channel, err := s.chanStateDB.FetchChannelByID(
×
1833
                                nil, chanID,
×
1834
                        )
×
1835
                        if err != nil {
×
1836
                                return nil, 0, err
×
1837
                        }
×
1838

1839
                        br, err := lnwallet.NewBreachRetribution(
×
1840
                                channel, commitHeight, 0, nil,
×
1841
                                implCfg.AuxLeafStore,
×
1842
                                implCfg.AuxContractResolver,
×
1843
                        )
×
1844
                        if err != nil {
×
1845
                                return nil, 0, err
×
1846
                        }
×
1847

1848
                        return br, channel.ChanType, nil
×
1849
                }
1850

1851
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
1852

×
1853
                // Copy the policy for legacy channels and set the blob flag
×
1854
                // signalling support for anchor channels.
×
1855
                anchorPolicy := policy
×
1856
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1857

×
1858
                // Copy the policy for legacy channels and set the blob flag
×
1859
                // signalling support for taproot channels.
×
1860
                taprootPolicy := policy
×
1861
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
1862
                        blob.FlagTaprootChannel,
×
1863
                )
×
1864

×
1865
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1866
                        FetchClosedChannel:     fetchClosedChannel,
×
1867
                        BuildBreachRetribution: buildBreachRetribution,
×
1868
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
1869
                        ChainNotifier:          s.cc.ChainNotifier,
×
1870
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
1871
                                error) {
×
1872

×
1873
                                return s.channelNotifier.
×
1874
                                        SubscribeChannelEvents()
×
1875
                        },
×
1876
                        Signer: cc.Wallet.Cfg.Signer,
1877
                        NewAddress: func() ([]byte, error) {
×
1878
                                addr, err := newSweepPkScriptGen(
×
1879
                                        cc.Wallet, netParams,
×
1880
                                )().Unpack()
×
1881
                                if err != nil {
×
1882
                                        return nil, err
×
1883
                                }
×
1884

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

1901
        if len(cfg.ExternalHosts) != 0 {
×
1902
                advertisedIPs := make(map[string]struct{})
×
1903
                for _, addr := range s.currentNodeAnn.Addresses {
×
1904
                        advertisedIPs[addr.String()] = struct{}{}
×
1905
                }
×
1906

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

×
1921
                                        return s.genNodeAnnouncement(
×
1922
                                                nil, modifier...,
×
1923
                                        )
×
1924
                                }),
×
1925
                })
1926
        }
1927

1928
        // Create liveness monitor.
1929
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1930

×
1931
        listeners := make([]net.Listener, len(listenAddrs))
×
1932
        for i, listenAddr := range listenAddrs {
×
1933
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
1934
                // doesn't need to call the general lndResolveTCP function
×
1935
                // since we are resolving a local address.
×
1936

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

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

×
1968
        // Finally, register the subsystems in blockbeat.
×
1969
        s.registerBlockConsumers()
×
1970

×
1971
        return s, nil
×
1972
}
1973

1974
// UpdateRoutingConfig is a callback function to update the routing config
1975
// values in the main cfg.
1976
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1977
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
1978

×
1979
        switch c := cfg.Estimator.Config().(type) {
×
1980
        case routing.AprioriConfig:
×
1981
                routerCfg.ProbabilityEstimatorType =
×
1982
                        routing.AprioriEstimatorName
×
1983

×
1984
                targetCfg := routerCfg.AprioriConfig
×
1985
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
1986
                targetCfg.Weight = c.AprioriWeight
×
1987
                targetCfg.CapacityFraction = c.CapacityFraction
×
1988
                targetCfg.HopProbability = c.AprioriHopProbability
×
1989

1990
        case routing.BimodalConfig:
×
1991
                routerCfg.ProbabilityEstimatorType =
×
1992
                        routing.BimodalEstimatorName
×
1993

×
1994
                targetCfg := routerCfg.BimodalConfig
×
1995
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
1996
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
1997
                targetCfg.DecayTime = c.BimodalDecayTime
×
1998
        }
1999

2000
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
2001
}
2002

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

2022
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
2023
// used for option_scid_alias channels where the ChannelUpdate to be sent back
2024
// may differ from what is on disk.
2025
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
2026
        error) {
×
2027

×
2028
        data, err := u.DataToSign()
×
2029
        if err != nil {
×
2030
                return nil, err
×
2031
        }
×
2032

2033
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
2034
}
2035

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

×
2049
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
2050
        if cfg.Bitcoin.Node == "nochainbackend" {
×
2051
                srvrLog.Info("Disabling chain backend checks for " +
×
2052
                        "nochainbackend mode")
×
2053

×
2054
                chainBackendAttempts = 0
×
2055
        }
×
2056

2057
        chainHealthCheck := healthcheck.NewObservation(
×
2058
                "chain backend",
×
2059
                cc.HealthCheck,
×
2060
                cfg.HealthChecks.ChainCheck.Interval,
×
2061
                cfg.HealthChecks.ChainCheck.Timeout,
×
2062
                cfg.HealthChecks.ChainCheck.Backoff,
×
2063
                chainBackendAttempts,
×
2064
        )
×
2065

×
2066
        diskCheck := healthcheck.NewObservation(
×
2067
                "disk space",
×
2068
                func() error {
×
2069
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2070
                                cfg.LndDir,
×
2071
                        )
×
2072
                        if err != nil {
×
2073
                                return err
×
2074
                        }
×
2075

2076
                        // If we have more free space than we require,
2077
                        // we return a nil error.
2078
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2079
                                return nil
×
2080
                        }
×
2081

2082
                        return fmt.Errorf("require: %v free space, got: %v",
×
2083
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2084
                                free)
×
2085
                },
2086
                cfg.HealthChecks.DiskCheck.Interval,
2087
                cfg.HealthChecks.DiskCheck.Timeout,
2088
                cfg.HealthChecks.DiskCheck.Backoff,
2089
                cfg.HealthChecks.DiskCheck.Attempts,
2090
        )
2091

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

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

2116
        checks := []*healthcheck.Observation{
×
2117
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
2118
        }
×
2119

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

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

×
2150
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2151
                        "remote signer connection",
×
2152
                        rpcwallet.HealthCheck(
×
2153
                                s.cfg.RemoteSigner,
×
2154

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

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

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

2194
                                if !leader {
×
2195
                                        srvrLog.Debug("Not the current leader")
×
2196
                                        return fmt.Errorf("not the current " +
×
2197
                                                "leader")
×
2198
                                }
×
2199

2200
                                return nil
×
2201
                        },
2202
                        cfg.HealthChecks.LeaderCheck.Interval,
2203
                        cfg.HealthChecks.LeaderCheck.Timeout,
2204
                        cfg.HealthChecks.LeaderCheck.Backoff,
2205
                        cfg.HealthChecks.LeaderCheck.Attempts,
2206
                )
2207

2208
                checks = append(checks, leaderCheck)
×
2209
        }
2210

2211
        // If we have not disabled all of our health checks, we create a
2212
        // liveness monitor with our configured checks.
2213
        s.livenessMonitor = healthcheck.NewMonitor(
×
2214
                &healthcheck.Config{
×
2215
                        Checks:   checks,
×
2216
                        Shutdown: srvrLog.Criticalf,
×
2217
                },
×
2218
        )
×
2219
}
2220

2221
// Started returns true if the server has been started, and false otherwise.
2222
// NOTE: This function is safe for concurrent access.
2223
func (s *server) Started() bool {
×
2224
        return atomic.LoadInt32(&s.active) != 0
×
2225
}
×
2226

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

2233
// add is used to add a cleanup function to be called when
2234
// the run function is executed.
2235
func (c cleaner) add(cleanup func() error) cleaner {
×
2236
        return append(c, cleanup)
×
2237
}
×
2238

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

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

×
2257
        cleanup := cleaner{}
×
2258

×
2259
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2260
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2261
                startErr = err
×
2262
        }
×
2263

2264
        if startErr != nil {
×
2265
                cleanup.run()
×
2266
        }
×
2267

2268
        return startErr
×
2269
}
2270

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

2283
        var startErr error
×
2284

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

×
2290
        s.start.Do(func() {
×
2291
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
2292
                if err := s.customMessageServer.Start(); err != nil {
×
2293
                        startErr = err
×
2294
                        return
×
2295
                }
×
2296

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

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

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

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

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

2336
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
2337
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2338
                        startErr = err
×
2339
                        return
×
2340
                }
×
2341

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

2348
                cleanup = cleanup.add(func() error {
×
2349
                        return s.peerNotifier.Stop()
×
2350
                })
×
2351
                if err := s.peerNotifier.Start(); err != nil {
×
2352
                        startErr = err
×
2353
                        return
×
2354
                }
×
2355

2356
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
2357
                if err := s.htlcNotifier.Start(); err != nil {
×
2358
                        startErr = err
×
2359
                        return
×
2360
                }
×
2361

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

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

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

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

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

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

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

2409
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
2410
                if err := s.interceptableSwitch.Start(); err != nil {
×
2411
                        startErr = err
×
2412
                        return
×
2413
                }
×
2414

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

2421
                cleanup = cleanup.add(s.chainArb.Stop)
×
2422
                if err := s.chainArb.Start(beat); err != nil {
×
2423
                        startErr = err
×
2424
                        return
×
2425
                }
×
2426

2427
                cleanup = cleanup.add(s.graphDB.Stop)
×
2428
                if err := s.graphDB.Start(); err != nil {
×
2429
                        startErr = err
×
2430
                        return
×
2431
                }
×
2432

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

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

2452
                cleanup = cleanup.add(s.invoices.Stop)
×
2453
                if err := s.invoices.Start(); err != nil {
×
2454
                        startErr = err
×
2455
                        return
×
2456
                }
×
2457

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

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

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

2476
                cleanup.add(func() error {
×
2477
                        s.missionController.StopStoreTickers()
×
2478
                        return nil
×
2479
                })
×
2480
                s.missionController.RunStoreTickers()
×
2481

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

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

2523
                if s.torController != nil {
×
2524
                        cleanup = cleanup.add(s.torController.Stop)
×
2525
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2526
                                startErr = err
×
2527
                                return
×
2528
                        }
×
2529
                }
2530

2531
                if s.natTraversal != nil {
×
2532
                        s.wg.Add(1)
×
2533
                        go s.watchExternalIP()
×
2534
                }
×
2535

2536
                // Start connmgr last to prevent connections before init.
2537
                cleanup = cleanup.add(func() error {
×
2538
                        s.connMgr.Stop()
×
2539
                        return nil
×
2540
                })
×
2541

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

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

2571
                        peerAddr := &lnwire.NetAddress{
×
2572
                                IdentityKey: parsedPubkey,
×
2573
                                Address:     addr,
×
2574
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2575
                        }
×
2576

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

2589
                // Subscribe to NodeAnnouncements that advertise new addresses
2590
                // our persistent peers.
2591
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2592
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2593
                                "addr: %v", err)
×
2594

×
2595
                        startErr = err
×
2596
                        return
×
2597
                }
×
2598

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

×
2608
                        startErr = err
×
2609
                        return
×
2610
                }
×
2611

2612
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2613
                        srvrLog.Errorf("Failed to establish persistent "+
×
2614
                                "connections: %v", err)
×
2615
                }
×
2616

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

2626
                        result := make([][2]string, len(tuples))
×
2627
                        for idx, tuple := range tuples {
×
2628
                                tuple = strings.TrimSpace(tuple)
×
2629
                                if len(tuple) == 0 {
×
2630
                                        return
×
2631
                                }
×
2632

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

2640
                                copy(result[idx][:], servers)
×
2641
                        }
2642

2643
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2644
                }
2645

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

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

2684
                        s.wg.Add(1)
×
2685
                        go s.peerBootstrapper(
×
2686
                                ctx, defaultMinPeers, bootstrappers,
×
2687
                        )
×
2688
                } else {
×
2689
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2690
                }
×
2691

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

2703
                // Set the active flag now that we've completed the full
2704
                // startup.
2705
                atomic.StoreInt32(&s.active, 1)
×
2706
        })
2707

2708
        if startErr != nil {
×
2709
                cleanup.run()
×
2710
        }
×
2711
        return startErr
×
2712
}
2713

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

×
2722
                ctx := context.Background()
×
2723

×
2724
                close(s.quit)
×
2725

×
2726
                // Shutdown connMgr first to prevent conns during shutdown.
×
2727
                s.connMgr.Stop()
×
2728

×
2729
                // Stop dispatching blocks to other systems immediately.
×
2730
                s.blockbeatDispatcher.Stop()
×
2731

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

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

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

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

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

2849
                if s.hostAnn != nil {
×
2850
                        if err := s.hostAnn.Stop(); err != nil {
×
2851
                                srvrLog.Warnf("unable to shut down host "+
×
2852
                                        "annoucner: %v", err)
×
2853
                        }
×
2854
                }
2855

2856
                if s.livenessMonitor != nil {
×
2857
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2858
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2859
                                        "monitor: %v", err)
×
2860
                        }
×
2861
                }
2862

2863
                // Wait for all lingering goroutines to quit.
2864
                srvrLog.Debug("Waiting for server to shutdown...")
×
2865
                s.wg.Wait()
×
2866

×
2867
                srvrLog.Debug("Stopping buffer pools...")
×
2868
                s.sigPool.Stop()
×
2869
                s.writePool.Stop()
×
2870
                s.readPool.Stop()
×
2871
        })
2872

2873
        return nil
×
2874
}
2875

2876
// Stopped returns true if the server has been instructed to shutdown.
2877
// NOTE: This function is safe for concurrent access.
2878
func (s *server) Stopped() bool {
×
2879
        return atomic.LoadInt32(&s.stopping) != 0
×
2880
}
×
2881

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

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

2901
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2902
                externalIPs = append(externalIPs, hostIP)
×
2903
        }
2904

2905
        return externalIPs, nil
×
2906
}
2907

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

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

×
2932
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2933
        // up by the server.
×
2934
        defer s.removePortForwarding()
×
2935

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

2943
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2944

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

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

2975
                        if ip.Equal(s.lastDetectedIP) {
×
2976
                                continue
×
2977
                        }
2978

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

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

2996
                                newAddrs = append(newAddrs, addr)
×
2997
                        }
2998

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

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

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

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

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

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

3051
                        // Finally, update the last IP seen to the current one.
3052
                        s.lastDetectedIP = ip
×
3053
                case <-s.quit:
×
3054
                        break out
×
3055
                }
3056
        }
3057
}
3058

3059
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3060
// based on the server, and currently active bootstrap mechanisms as defined
3061
// within the current configuration.
3062
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3063
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3064

×
3065
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3066

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

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

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

×
3092
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3093
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3094
                        )
×
3095
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3096
                }
×
3097
        }
3098

3099
        return bootStrappers, nil
×
3100
}
3101

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

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

×
3114
        // We should ignore ourselves from bootstrapping.
×
3115
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3116
        ignore[selfKey] = struct{}{}
×
3117

×
3118
        // Ignore all connected peers.
×
3119
        for _, peer := range s.peersByPub {
×
3120
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3121
                ignore[nID] = struct{}{}
×
3122
        }
×
3123

3124
        // Ignore all persistent peers as they have a dedicated reconnecting
3125
        // process.
3126
        for pubKeyStr := range s.persistentPeers {
×
3127
                var nID autopilot.NodeID
×
3128
                copy(nID[:], []byte(pubKeyStr))
×
3129
                ignore[nID] = struct{}{}
×
3130
        }
×
3131

3132
        return ignore
×
3133
}
3134

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

×
3143
        defer s.wg.Done()
×
3144

×
3145
        // Before we continue, init the ignore peers map.
×
3146
        ignoreList := s.createBootstrapIgnorePeers()
×
3147

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

×
3152
        // Once done, we'll attempt to maintain our target minimum number of
×
3153
        // peers.
×
3154
        //
×
3155
        // We'll use a 15 second backoff, and double the time every time an
×
3156
        // epoch fails up to a ceiling.
×
3157
        backOff := time.Second * 15
×
3158

×
3159
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3160
        // see if we've reached our minimum number of peers.
×
3161
        sampleTicker := time.NewTicker(backOff)
×
3162
        defer sampleTicker.Stop()
×
3163

×
3164
        // We'll use the number of attempts and errors to determine if we need
×
3165
        // to increase the time between discovery epochs.
×
3166
        var epochErrors uint32 // To be used atomically.
×
3167
        var epochAttempts uint32
×
3168

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

×
3180
                        // If we have enough peers, then we can loop back
×
3181
                        // around to the next round as we're done here.
×
3182
                        if numActivePeers >= numTargetPeers {
×
3183
                                continue
×
3184
                        }
3185

3186
                        // If all of our attempts failed during this last back
3187
                        // off period, then will increase our backoff to 5
3188
                        // minute ceiling to avoid an excessive number of
3189
                        // queries
3190
                        //
3191
                        // TODO(roasbeef): add reverse policy too?
3192

3193
                        if epochAttempts > 0 &&
×
3194
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3195

×
3196
                                sampleTicker.Stop()
×
3197

×
3198
                                backOff *= 2
×
3199
                                if backOff > bootstrapBackOffCeiling {
×
3200
                                        backOff = bootstrapBackOffCeiling
×
3201
                                }
×
3202

3203
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3204
                                        "%v", backOff)
×
3205
                                sampleTicker = time.NewTicker(backOff)
×
3206
                                continue
×
3207
                        }
3208

3209
                        atomic.StoreUint32(&epochErrors, 0)
×
3210
                        epochAttempts = 0
×
3211

×
3212
                        // Since we know need more peers, we'll compute the
×
3213
                        // exact number we need to reach our threshold.
×
3214
                        numNeeded := numTargetPeers - numActivePeers
×
3215

×
3216
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3217
                                "peers", numNeeded)
×
3218

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

×
3227
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3228
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3229
                        )
×
3230
                        if err != nil {
×
3231
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3232
                                        "peers: %v", err)
×
3233
                                continue
×
3234
                        }
3235

3236
                        // Finally, we'll launch a new goroutine for each
3237
                        // prospective peer candidates.
3238
                        for _, addr := range peerAddrs {
×
3239
                                epochAttempts++
×
3240

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

3255
                                                srvrLog.Errorf("Unable to "+
×
3256
                                                        "connect to %v: %v",
×
3257
                                                        a, err)
×
3258
                                                atomic.AddUint32(&epochErrors, 1)
×
3259
                                        case <-s.quit:
×
3260
                                        }
3261
                                }(addr)
3262
                        }
3263
                case <-s.quit:
×
3264
                        return
×
3265
                }
3266
        }
3267
}
3268

3269
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3270
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3271
// query back off each time we encounter a failure.
3272
const bootstrapBackOffCeiling = time.Minute * 5
3273

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

×
3281
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3282
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3283

×
3284
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3285
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3286
        var delaySignal <-chan time.Time
×
3287
        delayTime := time.Second * 2
×
3288

×
3289
        // As want to be more aggressive, we'll use a lower back off celling
×
3290
        // then the main peer bootstrap logic.
×
3291
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3292

×
3293
        for attempts := 0; ; attempts++ {
×
3294
                // Check if the server has been requested to shut down in order
×
3295
                // to prevent blocking.
×
3296
                if s.Stopped() {
×
3297
                        return
×
3298
                }
×
3299

3300
                // We can exit our aggressive initial peer bootstrapping stage
3301
                // if we've reached out target number of peers.
3302
                s.mu.RLock()
×
3303
                numActivePeers := uint32(len(s.peersByPub))
×
3304
                s.mu.RUnlock()
×
3305

×
3306
                if numActivePeers >= numTargetPeers {
×
3307
                        return
×
3308
                }
×
3309

3310
                if attempts > 0 {
×
3311
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3312
                                "bootstrap peers (attempt #%v)", delayTime,
×
3313
                                attempts)
×
3314

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

3325
                        // After our delay, we'll double the time we wait up to
3326
                        // the max back off period.
3327
                        delayTime *= 2
×
3328
                        if delayTime > backOffCeiling {
×
3329
                                delayTime = backOffCeiling
×
3330
                        }
×
3331
                }
3332

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

3345
                // Then, we'll attempt to establish a connection to the
3346
                // different peer addresses retrieved by our bootstrappers.
3347
                var wg sync.WaitGroup
×
3348
                for _, bootstrapAddr := range bootstrapAddrs {
×
3349
                        wg.Add(1)
×
3350
                        go func(addr *lnwire.NetAddress) {
×
3351
                                defer wg.Done()
×
3352

×
3353
                                errChan := make(chan error, 1)
×
3354
                                go s.connectToPeer(
×
3355
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3356
                                )
×
3357

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

3381
                wg.Wait()
×
3382
        }
3383
}
3384

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

3397
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3398
        if err != nil {
×
3399
                return err
×
3400
        }
×
3401

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

×
3414
        switch {
×
3415
        case s.cfg.Tor.V2:
×
3416
                onionCfg.Type = tor.V2
×
3417
        case s.cfg.Tor.V3:
×
3418
                onionCfg.Type = tor.V3
×
3419
        }
3420

3421
        addr, err := s.torController.AddOnion(onionCfg)
×
3422
        if err != nil {
×
3423
                return err
×
3424
        }
×
3425

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

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

3456
        return nil
×
3457
}
3458

3459
// findChannel finds a channel given a public key and ChannelID. It is an
3460
// optimization that is quicker than seeking for a channel given only the
3461
// ChannelID.
3462
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3463
        *channeldb.OpenChannel, error) {
×
3464

×
3465
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3466
        if err != nil {
×
3467
                return nil, err
×
3468
        }
×
3469

3470
        for _, channel := range nodeChans {
×
3471
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3472
                        return channel, nil
×
3473
                }
×
3474
        }
3475

3476
        return nil, fmt.Errorf("unable to find channel")
×
3477
}
3478

3479
// getNodeAnnouncement fetches the current, fully signed node announcement.
3480
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
3481
        s.mu.Lock()
×
3482
        defer s.mu.Unlock()
×
3483

×
3484
        return *s.currentNodeAnn
×
3485
}
×
3486

3487
// genNodeAnnouncement generates and returns the current fully signed node
3488
// announcement. The time stamp of the announcement will be updated in order
3489
// to ensure it propagates through the network.
3490
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3491
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
3492

×
3493
        s.mu.Lock()
×
3494
        defer s.mu.Unlock()
×
3495

×
3496
        // Create a shallow copy of the current node announcement to work on.
×
3497
        // This ensures the original announcement remains unchanged
×
3498
        // until the new announcement is fully signed and valid.
×
3499
        newNodeAnn := *s.currentNodeAnn
×
3500

×
3501
        // First, try to update our feature manager with the updated set of
×
3502
        // features.
×
3503
        if features != nil {
×
3504
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
3505
                        feature.SetNodeAnn: features,
×
3506
                }
×
3507
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
3508
                if err != nil {
×
3509
                        return lnwire.NodeAnnouncement{}, err
×
3510
                }
×
3511

3512
                // If we could successfully update our feature manager, add
3513
                // an update modifier to include these new features to our
3514
                // set.
3515
                modifiers = append(
×
3516
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3517
                )
×
3518
        }
3519

3520
        // Always update the timestamp when refreshing to ensure the update
3521
        // propagates.
3522
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3523

×
3524
        // Apply the requested changes to the node announcement.
×
3525
        for _, modifier := range modifiers {
×
3526
                modifier(&newNodeAnn)
×
3527
        }
×
3528

3529
        // Sign a new update after applying all of the passed modifiers.
3530
        err := netann.SignNodeAnnouncement(
×
3531
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
3532
        )
×
3533
        if err != nil {
×
3534
                return lnwire.NodeAnnouncement{}, err
×
3535
        }
×
3536

3537
        // If signing succeeds, update the current announcement.
3538
        *s.currentNodeAnn = newNodeAnn
×
3539

×
3540
        return *s.currentNodeAnn, nil
×
3541
}
3542

3543
// updateAndBroadcastSelfNode generates a new node announcement
3544
// applying the giving modifiers and updating the time stamp
3545
// to ensure it propagates through the network. Then it broadcasts
3546
// it to the network.
3547
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3548
        features *lnwire.RawFeatureVector,
3549
        modifiers ...netann.NodeAnnModifier) error {
×
3550

×
3551
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
3552
        if err != nil {
×
3553
                return fmt.Errorf("unable to generate new node "+
×
3554
                        "announcement: %v", err)
×
3555
        }
×
3556

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

3565
        selfNode.HaveNodeAnnouncement = true
×
3566
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
3567
        selfNode.Addresses = newNodeAnn.Addresses
×
3568
        selfNode.Alias = newNodeAnn.Alias.String()
×
3569
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
3570
        selfNode.Color = newNodeAnn.RGBColor
×
3571
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
3572

×
3573
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3574

×
3575
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3576
                return fmt.Errorf("can't set self node: %w", err)
×
3577
        }
×
3578

3579
        // Finally, propagate it to the nodes in the network.
3580
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3581
        if err != nil {
×
3582
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3583
                        "announcement to peers: %v", err)
×
3584
                return err
×
3585
        }
×
3586

3587
        return nil
×
3588
}
3589

3590
type nodeAddresses struct {
3591
        pubKey    *btcec.PublicKey
3592
        addresses []net.Addr
3593
}
3594

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

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

3613
        for _, node := range linkNodes {
×
3614
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
3615
                nodeAddrs := &nodeAddresses{
×
3616
                        pubKey:    node.IdentityPub,
×
3617
                        addresses: node.Addresses,
×
3618
                }
×
3619
                nodeAddrsMap[pubStr] = nodeAddrs
×
3620
        }
×
3621

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

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

3639
                pubStr := string(channelPeer.PubKeyBytes[:])
×
3640

×
3641
                // Add all unique addresses from channel
×
3642
                // graph/NodeAnnouncements to the list of addresses we'll
×
3643
                // connect to for this peer.
×
3644
                addrSet := make(map[string]net.Addr)
×
3645
                for _, addr := range channelPeer.Addresses {
×
3646
                        switch addr.(type) {
×
3647
                        case *net.TCPAddr:
×
3648
                                addrSet[addr.String()] = addr
×
3649

3650
                        // We'll only attempt to connect to Tor addresses if Tor
3651
                        // outbound support is enabled.
3652
                        case *tor.OnionAddr:
×
3653
                                if s.cfg.Tor.Active {
×
3654
                                        addrSet[addr.String()] = addr
×
3655
                                }
×
3656
                        }
3657
                }
3658

3659
                // If this peer is also recorded as a link node, we'll add any
3660
                // additional addresses that have not already been selected.
3661
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
3662
                if ok {
×
3663
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
3664
                                switch lnAddress.(type) {
×
3665
                                case *net.TCPAddr:
×
3666
                                        addrSet[lnAddress.String()] = lnAddress
×
3667

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

3679
                // Construct a slice of the deduped addresses.
3680
                var addrs []net.Addr
×
3681
                for _, addr := range addrSet {
×
3682
                        addrs = append(addrs, addr)
×
3683
                }
×
3684

3685
                n := &nodeAddresses{
×
3686
                        addresses: addrs,
×
3687
                }
×
3688
                n.pubKey, err = channelPeer.PubKey()
×
3689
                if err != nil {
×
3690
                        return err
×
3691
                }
×
3692

3693
                graphAddrs[pubStr] = n
×
3694
                return nil
×
3695
        }
3696
        err = s.graphDB.ForEachSourceNodeChannel(
×
3697
                ctx, forEachSrcNodeChan, func() {
×
3698
                        clear(graphAddrs)
×
3699
                },
×
3700
        )
3701
        if err != nil {
×
3702
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3703
                        "%v", err)
×
3704

×
3705
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3706
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3707

×
3708
                        return err
×
3709
                }
×
3710
        }
3711

3712
        // Combine the addresses from the link nodes and the channel graph.
3713
        for pubStr, nodeAddr := range graphAddrs {
×
3714
                nodeAddrsMap[pubStr] = nodeAddr
×
3715
        }
×
3716

3717
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3718
                len(nodeAddrsMap))
×
3719

×
3720
        // Acquire and hold server lock until all persistent connection requests
×
3721
        // have been recorded and sent to the connection manager.
×
3722
        s.mu.Lock()
×
3723
        defer s.mu.Unlock()
×
3724

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

3739
                for _, address := range nodeAddr.addresses {
×
3740
                        // Create a wrapper address which couples the IP and
×
3741
                        // the pubkey so the brontide authenticated connection
×
3742
                        // can be established.
×
3743
                        lnAddr := &lnwire.NetAddress{
×
3744
                                IdentityKey: nodeAddr.pubKey,
×
3745
                                Address:     address,
×
3746
                        }
×
3747

×
3748
                        s.persistentPeerAddrs[pubStr] = append(
×
3749
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3750
                }
×
3751

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

×
3762
                        go s.connectToPersistentPeer(pubStr)
×
3763
                } else {
×
3764
                        go s.delayInitialReconnect(pubStr)
×
3765
                }
×
3766

3767
                numOutboundConns++
×
3768
        }
3769

3770
        return nil
×
3771
}
3772

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

3786
// prunePersistentPeerConnection removes all internal state related to
3787
// persistent connections to a peer within the server. This is used to avoid
3788
// persistent connection retries to peers we do not have any open channels with.
3789
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
×
3790
        pubKeyStr := string(compressedPubKey[:])
×
3791

×
3792
        s.mu.Lock()
×
3793
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3794
                delete(s.persistentPeers, pubKeyStr)
×
3795
                delete(s.persistentPeersBackoff, pubKeyStr)
×
3796
                delete(s.persistentPeerAddrs, pubKeyStr)
×
3797
                s.cancelConnReqs(pubKeyStr, nil)
×
3798
                s.mu.Unlock()
×
3799

×
3800
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3801
                        "peer has no open channels", compressedPubKey)
×
3802

×
3803
                return
×
3804
        }
×
3805
        s.mu.Unlock()
×
3806
}
3807

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

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

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

3848
                peers = append(peers, sPeer)
×
3849
        }
3850
        s.mu.RUnlock()
×
3851

×
3852
        // Iterate over all known peers, dispatching a go routine to enqueue
×
3853
        // all messages to each of peers.
×
3854
        var wg sync.WaitGroup
×
3855
        for _, sPeer := range peers {
×
3856
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
3857
                        sPeer.PubKey())
×
3858

×
3859
                // Dispatch a go routine to enqueue all messages to this peer.
×
3860
                wg.Add(1)
×
3861
                s.wg.Add(1)
×
3862
                go func(p lnpeer.Peer) {
×
3863
                        defer s.wg.Done()
×
3864
                        defer wg.Done()
×
3865

×
3866
                        p.SendMessageLazy(false, msgs...)
×
3867
                }(sPeer)
×
3868
        }
3869

3870
        // Wait for all messages to have been dispatched before returning to
3871
        // caller.
3872
        wg.Wait()
×
3873

×
3874
        return nil
×
3875
}
3876

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

×
3884
        s.mu.Lock()
×
3885

×
3886
        // Compute the target peer's identifier.
×
3887
        pubStr := string(peerKey[:])
×
3888

×
3889
        // Check if peer is connected.
×
3890
        peer, ok := s.peersByPub[pubStr]
×
3891
        if ok {
×
3892
                // Unlock here so that the mutex isn't held while we are
×
3893
                // waiting for the peer to become active.
×
3894
                s.mu.Unlock()
×
3895

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

3911
                // Connected, can return early.
3912
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
3913

×
3914
                select {
×
3915
                case peerChan <- peer:
×
3916
                case <-s.quit:
×
3917
                }
3918

3919
                return
×
3920
        }
3921

3922
        // Not connected, store this listener such that it can be notified when
3923
        // the peer comes online.
3924
        s.peerConnectedListeners[pubStr] = append(
×
3925
                s.peerConnectedListeners[pubStr], peerChan,
×
3926
        )
×
3927
        s.mu.Unlock()
×
3928
}
3929

3930
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3931
// the given public key has been disconnected. The notification is signaled by
3932
// closing the channel returned.
3933
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
3934
        s.mu.Lock()
×
3935
        defer s.mu.Unlock()
×
3936

×
3937
        c := make(chan struct{})
×
3938

×
3939
        // If the peer is already offline, we can immediately trigger the
×
3940
        // notification.
×
3941
        peerPubKeyStr := string(peerPubKey[:])
×
3942
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3943
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3944
                close(c)
×
3945
                return c
×
3946
        }
×
3947

3948
        // Otherwise, the peer is online, so we'll keep track of the channel to
3949
        // trigger the notification once the server detects the peer
3950
        // disconnects.
3951
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
3952
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
3953
        )
×
3954

×
3955
        return c
×
3956
}
3957

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

×
3967
        pubStr := string(peerKey.SerializeCompressed())
×
3968

×
3969
        return s.findPeerByPubStr(pubStr)
×
3970
}
×
3971

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

×
3981
        return s.findPeerByPubStr(pubStr)
×
3982
}
×
3983

3984
// findPeerByPubStr is an internal method that retrieves the specified peer from
3985
// the server's internal state using.
3986
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3987
        peer, ok := s.peersByPub[pubStr]
×
3988
        if !ok {
×
3989
                return nil, ErrPeerNotConnected
×
3990
        }
×
3991

3992
        return peer, nil
×
3993
}
3994

3995
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3996
// exponential backoff. If no previous backoff was known, the default is
3997
// returned.
3998
func (s *server) nextPeerBackoff(pubStr string,
3999
        startTime time.Time) time.Duration {
×
4000

×
4001
        // Now, determine the appropriate backoff to use for the retry.
×
4002
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
4003
        if !ok {
×
4004
                // If an existing backoff was unknown, use the default.
×
4005
                return s.cfg.MinBackoff
×
4006
        }
×
4007

4008
        // If the peer failed to start properly, we'll just use the previous
4009
        // backoff to compute the subsequent randomized exponential backoff
4010
        // duration. This will roughly double on average.
4011
        if startTime.IsZero() {
×
4012
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4013
        }
×
4014

4015
        // The peer succeeded in starting. If the connection didn't last long
4016
        // enough to be considered stable, we'll continue to back off retries
4017
        // with this peer.
4018
        connDuration := time.Since(startTime)
×
4019
        if connDuration < defaultStableConnDuration {
×
4020
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
4021
        }
×
4022

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

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

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

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

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

4067
        nodePub := conn.(*brontide.Conn).RemotePub()
×
4068
        pubSer := nodePub.SerializeCompressed()
×
4069
        pubStr := string(pubSer)
×
4070

×
4071
        var pubBytes [33]byte
×
4072
        copy(pubBytes[:], pubSer)
×
4073

×
4074
        s.mu.Lock()
×
4075
        defer s.mu.Unlock()
×
4076

×
4077
        // If we already have an outbound connection to this peer, then ignore
×
4078
        // this new connection.
×
4079
        if p, ok := s.outboundPeers[pubStr]; ok {
×
4080
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
4081
                        "ignoring inbound connection from local=%v, remote=%v",
×
4082
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
4083

×
4084
                conn.Close()
×
4085
                return
×
4086
        }
×
4087

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

4098
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
×
4099

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

4113
        case nil:
×
4114
                ctx := btclog.WithCtx(
×
4115
                        context.TODO(),
×
4116
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
4117
                )
×
4118

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

×
4128
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4129
                                "peer, but already have outbound "+
×
4130
                                "connection, dropping conn",
×
4131
                                fmt.Errorf("already have outbound conn"))
×
4132
                        conn.Close()
×
4133
                        return
×
4134
                }
×
4135

4136
                // Otherwise, if we should drop the connection, then we'll
4137
                // disconnect our already connected peer.
4138
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4139

×
4140
                s.cancelConnReqs(pubStr, nil)
×
4141

×
4142
                // Remove the current peer from the server's internal state and
×
4143
                // signal that the peer termination watcher does not need to
×
4144
                // execute for this peer.
×
4145
                s.removePeerUnsafe(ctx, connectedPeer)
×
4146
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4147
                s.scheduledPeerConnection[pubStr] = func() {
×
4148
                        s.peerConnected(conn, nil, true)
×
4149
                }
×
4150
        }
4151
}
4152

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

4163
        nodePub := conn.(*brontide.Conn).RemotePub()
×
4164
        pubSer := nodePub.SerializeCompressed()
×
4165
        pubStr := string(pubSer)
×
4166

×
4167
        var pubBytes [33]byte
×
4168
        copy(pubBytes[:], pubSer)
×
4169

×
4170
        s.mu.Lock()
×
4171
        defer s.mu.Unlock()
×
4172

×
4173
        // If we already have an inbound connection to this peer, then ignore
×
4174
        // this new connection.
×
4175
        if p, ok := s.inboundPeers[pubStr]; ok {
×
4176
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
4177
                        "ignoring outbound connection from local=%v, remote=%v",
×
4178
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
4179

×
4180
                if connReq != nil {
×
4181
                        s.connMgr.Remove(connReq.ID())
×
4182
                }
×
4183
                conn.Close()
×
4184
                return
×
4185
        }
4186
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4187
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4188
                s.connMgr.Remove(connReq.ID())
×
4189
                conn.Close()
×
4190
                return
×
4191
        }
×
4192

4193
        // If we already have a valid connection that is scheduled to take
4194
        // precedence once the prior peer has finished disconnecting, we'll
4195
        // ignore this connection.
4196
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4197
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4198

×
4199
                if connReq != nil {
×
4200
                        s.connMgr.Remove(connReq.ID())
×
4201
                }
×
4202

4203
                conn.Close()
×
4204
                return
×
4205
        }
4206

4207
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
4208
                conn.RemoteAddr())
×
4209

×
4210
        if connReq != nil {
×
4211
                // A successful connection was returned by the connmgr.
×
4212
                // Immediately cancel all pending requests, excluding the
×
4213
                // outbound connection we just established.
×
4214
                ignore := connReq.ID()
×
4215
                s.cancelConnReqs(pubStr, &ignore)
×
4216
        } else {
×
4217
                // This was a successful connection made by some other
×
4218
                // subsystem. Remove all requests being managed by the connmgr.
×
4219
                s.cancelConnReqs(pubStr, nil)
×
4220
        }
×
4221

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

4233
        case nil:
×
4234
                ctx := btclog.WithCtx(
×
4235
                        context.TODO(),
×
4236
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
4237
                )
×
4238

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

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

4259
                // Otherwise, _their_ connection should be dropped. So we'll
4260
                // disconnect the peer and send the now obsolete peer to the
4261
                // server for garbage collection.
4262
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4263

×
4264
                // Remove the current peer from the server's internal state and
×
4265
                // signal that the peer termination watcher does not need to
×
4266
                // execute for this peer.
×
4267
                s.removePeerUnsafe(ctx, connectedPeer)
×
4268
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4269
                s.scheduledPeerConnection[pubStr] = func() {
×
4270
                        s.peerConnected(conn, connReq, false)
×
4271
                }
×
4272
        }
4273
}
4274

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

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

4295
        // Next, check to see if we have any outstanding persistent connection
4296
        // requests to this peer. If so, then we'll remove all of these
4297
        // connection requests, and also delete the entry from the map.
4298
        connReqs, ok := s.persistentConnReqs[pubStr]
×
4299
        if !ok {
×
4300
                return
×
4301
        }
×
4302

4303
        for _, connReq := range connReqs {
×
4304
                srvrLog.Tracef("Canceling %s:", connReqs)
×
4305

×
4306
                // Atomically capture the current request identifier.
×
4307
                connID := connReq.ID()
×
4308

×
4309
                // Skip any zero IDs, this indicates the request has not
×
4310
                // yet been schedule.
×
4311
                if connID == UnassignedConnID {
×
4312
                        continue
×
4313
                }
4314

4315
                // Skip a particular connection ID if instructed.
4316
                if skip != nil && connID == *skip {
×
4317
                        continue
×
4318
                }
4319

4320
                s.connMgr.Remove(connID)
×
4321
        }
4322

4323
        delete(s.persistentConnReqs, pubStr)
×
4324
}
4325

4326
// handleCustomMessage dispatches an incoming custom peers message to
4327
// subscribers.
4328
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
4329
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
4330
                peer, msg.Type)
×
4331

×
4332
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4333
                Peer: peer,
×
4334
                Msg:  msg,
×
4335
        })
×
4336
}
×
4337

4338
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4339
// messages.
4340
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4341
        return s.customMessageServer.Subscribe()
×
4342
}
×
4343

4344
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4345
// the channelNotifier's NotifyOpenChannelEvent.
4346
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4347
        remotePub *btcec.PublicKey) {
×
4348

×
4349
        // Call newOpenChan to update the access manager's maps for this peer.
×
4350
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
4351
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4352
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
4353
        }
×
4354

4355
        // Notify subscribers about this open channel event.
4356
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4357
}
4358

4359
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4360
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4361
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4362
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
4363

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

4372
        // Notify subscribers about this event.
4373
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4374
}
4375

4376
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4377
// calls the channelNotifier's NotifyFundingTimeout.
4378
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4379
        remotePub *btcec.PublicKey) {
×
4380

×
4381
        // Call newPendingCloseChan to potentially demote the peer.
×
4382
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
4383
        if err != nil {
×
4384
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4385
                        "channel[%v] pending close",
×
4386
                        remotePub.SerializeCompressed(), op)
×
4387
        }
×
4388

4389
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4390
                // If we encounter an error while attempting to disconnect the
×
4391
                // peer, log the error.
×
4392
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4393
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4394
                }
×
4395
        }
4396

4397
        // Notify subscribers about this event.
4398
        s.channelNotifier.NotifyFundingTimeout(op)
×
4399
}
4400

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

×
4408
        brontideConn := conn.(*brontide.Conn)
×
4409
        addr := conn.RemoteAddr()
×
4410
        pubKey := brontideConn.RemotePub()
×
4411

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

×
4422
                // Clean up the persistent peer maps if we're dropping this
×
4423
                // connection.
×
4424
                s.bannedPersistentPeerConnection(string(pubSer))
×
4425

×
4426
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4427
                        "of restricted-access connection slots: %v.", pubSer,
×
4428
                        err)
×
4429

×
4430
                conn.Close()
×
4431

×
4432
                return
×
4433
        }
×
4434

4435
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4436
                pubKey.SerializeCompressed(), addr, inbound)
×
4437

×
4438
        peerAddr := &lnwire.NetAddress{
×
4439
                IdentityKey: pubKey,
×
4440
                Address:     addr,
×
4441
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4442
        }
×
4443

×
4444
        // With the brontide connection established, we'll now craft the feature
×
4445
        // vectors to advertise to the remote node.
×
4446
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
4447
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4448

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

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

4473
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
4474
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
4475

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

×
4519
                        return s.genNodeAnnouncement(nil)
×
4520
                },
×
4521

4522
                PongBuf: s.pongBuf,
4523

4524
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4525

4526
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4527

4528
                FundingManager: s.fundingMgr,
4529

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

4560
                        return clock.NewDefaultClock().Now().Before(
×
4561
                                EndorsementExperimentEnd,
×
4562
                        )
×
4563
                },
4564
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4565
        }
4566

4567
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
4568
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
4569

×
4570
        p := peer.NewBrontide(pCfg)
×
4571

×
4572
        // Update the access manager with the access permission for this peer.
×
4573
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
4574

×
4575
        // TODO(roasbeef): update IP address for link-node
×
4576
        //  * also mark last-seen, do it one single transaction?
×
4577

×
4578
        s.addPeer(p)
×
4579

×
4580
        // Once we have successfully added the peer to the server, we can
×
4581
        // delete the previous error buffer from the server's map of error
×
4582
        // buffers.
×
4583
        delete(s.peerErrors, pkStr)
×
4584

×
4585
        // Dispatch a goroutine to asynchronously start the peer. This process
×
4586
        // includes sending and receiving Init messages, which would be a DOS
×
4587
        // vector if we held the server's mutex throughout the procedure.
×
4588
        s.wg.Add(1)
×
4589
        go s.peerInitializer(p)
×
4590
}
4591

4592
// addPeer adds the passed peer to the server's global state of all active
4593
// peers.
4594
func (s *server) addPeer(p *peer.Brontide) {
×
4595
        if p == nil {
×
4596
                return
×
4597
        }
×
4598

4599
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4600

×
4601
        // Ignore new peers if we're shutting down.
×
4602
        if s.Stopped() {
×
4603
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4604
                        pubBytes)
×
4605
                p.Disconnect(ErrServerShuttingDown)
×
4606

×
4607
                return
×
4608
        }
×
4609

4610
        // Track the new peer in our indexes so we can quickly look it up either
4611
        // according to its public key, or its peer ID.
4612
        // TODO(roasbeef): pipe all requests through to the
4613
        // queryHandler/peerManager
4614

4615
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4616
        // be human-readable.
4617
        pubStr := string(pubBytes)
×
4618

×
4619
        s.peersByPub[pubStr] = p
×
4620

×
4621
        if p.Inbound() {
×
4622
                s.inboundPeers[pubStr] = p
×
4623
        } else {
×
4624
                s.outboundPeers[pubStr] = p
×
4625
        }
×
4626

4627
        // Inform the peer notifier of a peer online event so that it can be reported
4628
        // to clients listening for peer events.
4629
        var pubKey [33]byte
×
4630
        copy(pubKey[:], pubBytes)
×
4631
}
4632

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

×
4645
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4646

×
4647
        // Avoid initializing peers while the server is exiting.
×
4648
        if s.Stopped() {
×
4649
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4650
                        pubBytes)
×
4651
                return
×
4652
        }
×
4653

4654
        // Create a channel that will be used to signal a successful start of
4655
        // the link. This prevents the peer termination watcher from beginning
4656
        // its duty too early.
4657
        ready := make(chan struct{})
×
4658

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

×
4668
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
4669
        // will unblock the peerTerminationWatcher.
×
4670
        if err := p.Start(); err != nil {
×
4671
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4672

×
4673
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4674
                return
×
4675
        }
×
4676

4677
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4678
        // was successful, and to begin watching the peer's wait group.
4679
        close(ready)
×
4680

×
4681
        s.mu.Lock()
×
4682
        defer s.mu.Unlock()
×
4683

×
4684
        // Check if there are listeners waiting for this peer to come online.
×
4685
        srvrLog.Debugf("Notifying that peer %v is online", p)
×
4686

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

×
4699
        // Since the peer has been fully initialized, now it's time to notify
×
4700
        // the RPC about the peer online event.
×
4701
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4702
}
4703

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

×
4718
        ctx := btclog.WithCtx(
×
4719
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
4720
        )
×
4721

×
4722
        p.WaitForDisconnect(ready)
×
4723

×
4724
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
4725

×
4726
        // If the server is exiting then we can bail out early ourselves as all
×
4727
        // the other sub-systems will already be shutting down.
×
4728
        if s.Stopped() {
×
4729
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
4730
                return
×
4731
        }
×
4732

4733
        // Next, we'll cancel all pending funding reservations with this node.
4734
        // If we tried to initiate any funding flows that haven't yet finished,
4735
        // then we need to unlock those committed outputs so they're still
4736
        // available for use.
4737
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
4738

×
4739
        pubKey := p.IdentityKey()
×
4740

×
4741
        // We'll also inform the gossiper that this peer is no longer active,
×
4742
        // so we don't need to maintain sync state for it any longer.
×
4743
        s.authGossiper.PruneSyncState(p.PubKey())
×
4744

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

4755
        for _, link := range links {
×
4756
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4757
        }
×
4758

4759
        s.mu.Lock()
×
4760
        defer s.mu.Unlock()
×
4761

×
4762
        // If there were any notification requests for when this peer
×
4763
        // disconnected, we can trigger them now.
×
4764
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
4765
        pubStr := string(pubKey.SerializeCompressed())
×
4766
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
4767
                close(offlineChan)
×
4768
        }
×
4769
        delete(s.peerDisconnectedListeners, pubStr)
×
4770

×
4771
        // If the server has already removed this peer, we can short circuit the
×
4772
        // peer termination watcher and skip cleanup.
×
4773
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4774
                delete(s.ignorePeerTermination, p)
×
4775

×
4776
                pubKey := p.PubKey()
×
4777
                pubStr := string(pubKey[:])
×
4778

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

4792
        // First, cleanup any remaining state the server has regarding the peer
4793
        // in question.
4794
        s.removePeerUnsafe(ctx, p)
×
4795

×
4796
        // Next, check to see if this is a persistent peer or not.
×
4797
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4798
                return
×
4799
        }
×
4800

4801
        // Get the last address that we used to connect to the peer.
4802
        addrs := []net.Addr{
×
4803
                p.NetAddress().Address,
×
4804
        }
×
4805

×
4806
        // We'll ensure that we locate all the peers advertised addresses for
×
4807
        // reconnection purposes.
×
4808
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
4809
        switch {
×
4810
        // We found advertised addresses, so use them.
4811
        case err == nil:
×
4812
                addrs = advertisedAddrs
×
4813

4814
        // The peer doesn't have an advertised address.
4815
        case err == errNoAdvertisedAddr:
×
4816
                // If it is an outbound peer then we fall back to the existing
×
4817
                // peer address.
×
4818
                if !p.Inbound() {
×
4819
                        break
×
4820
                }
4821

4822
                // Fall back to the existing peer address if
4823
                // we're not accepting connections over Tor.
4824
                if s.torController == nil {
×
4825
                        break
×
4826
                }
4827

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

4837
        // We came across an error retrieving an advertised
4838
        // address, log it, and fall back to the existing peer
4839
        // address.
4840
        default:
×
4841
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
4842
                        "address for peer", err)
×
4843
        }
4844

4845
        // Make an easy lookup map so that we can check if an address
4846
        // is already in the address list that we have stored for this peer.
4847
        existingAddrs := make(map[string]bool)
×
4848
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
4849
                existingAddrs[addr.String()] = true
×
4850
        }
×
4851

4852
        // Add any missing addresses for this peer to persistentPeerAddr.
4853
        for _, addr := range addrs {
×
4854
                if existingAddrs[addr.String()] {
×
4855
                        continue
×
4856
                }
4857

4858
                s.persistentPeerAddrs[pubStr] = append(
×
4859
                        s.persistentPeerAddrs[pubStr],
×
4860
                        &lnwire.NetAddress{
×
4861
                                IdentityKey: p.IdentityKey(),
×
4862
                                Address:     addr,
×
4863
                                ChainNet:    p.NetAddress().ChainNet,
×
4864
                        },
×
4865
                )
×
4866
        }
4867

4868
        // Record the computed backoff in the backoff map.
4869
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4870
        s.persistentPeersBackoff[pubStr] = backoff
×
4871

×
4872
        // Initialize a retry canceller for this peer if one does not
×
4873
        // exist.
×
4874
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4875
        if !ok {
×
4876
                cancelChan = make(chan struct{})
×
4877
                s.persistentRetryCancels[pubStr] = cancelChan
×
4878
        }
×
4879

4880
        // We choose not to wait group this go routine since the Connect
4881
        // call can stall for arbitrarily long if we shutdown while an
4882
        // outbound connection attempt is being made.
4883
        go func() {
×
4884
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
4885
                        "re-establishment to persistent peer",
×
4886
                        "reconnecting_in", backoff)
×
4887

×
4888
                select {
×
4889
                case <-time.After(backoff):
×
4890
                case <-cancelChan:
×
4891
                        return
×
4892
                case <-s.quit:
×
4893
                        return
×
4894
                }
4895

4896
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
4897
                        "connection")
×
4898

×
4899
                s.connectToPersistentPeer(pubStr)
×
4900
        }()
4901
}
4902

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

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

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

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

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

4953
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
4954

×
4955
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
4956
        if !ok {
×
4957
                cancelChan = make(chan struct{})
×
4958
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
4959
        }
×
4960

4961
        // Any addresses left in addrMap are new ones that we have not made
4962
        // connection requests for. So create new connection requests for those.
4963
        // If there is more than one address in the address map, stagger the
4964
        // creation of the connection requests for those.
4965
        go func() {
×
4966
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4967
                defer ticker.Stop()
×
4968

×
4969
                for _, addr := range addrMap {
×
4970
                        // Send the persistent connection request to the
×
4971
                        // connection manager, saving the request itself so we
×
4972
                        // can cancel/restart the process as needed.
×
4973
                        connReq := &connmgr.ConnReq{
×
4974
                                Addr:      addr,
×
4975
                                Permanent: true,
×
4976
                        }
×
4977

×
4978
                        s.mu.Lock()
×
4979
                        s.persistentConnReqs[pubKeyStr] = append(
×
4980
                                s.persistentConnReqs[pubKeyStr], connReq,
×
4981
                        )
×
4982
                        s.mu.Unlock()
×
4983

×
4984
                        srvrLog.Debugf("Attempting persistent connection to "+
×
4985
                                "channel peer %v", addr)
×
4986

×
4987
                        go s.connMgr.Connect(connReq)
×
4988

×
4989
                        select {
×
4990
                        case <-s.quit:
×
4991
                                return
×
4992
                        case <-cancelChan:
×
4993
                                return
×
4994
                        case <-ticker.C:
×
4995
                        }
4996
                }
4997
        }()
4998
}
4999

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

5009
        srvrLog.DebugS(ctx, "Removing peer")
×
5010

×
5011
        // Exit early if we have already been instructed to shutdown, the peers
×
5012
        // will be disconnected in the server shutdown process.
×
5013
        if s.Stopped() {
×
5014
                return
×
5015
        }
×
5016

5017
        // Capture the peer's public key and string representation.
5018
        pKey := p.PubKey()
×
5019
        pubSer := pKey[:]
×
5020
        pubStr := string(pubSer)
×
5021

×
5022
        delete(s.peersByPub, pubStr)
×
5023

×
5024
        if p.Inbound() {
×
5025
                delete(s.inboundPeers, pubStr)
×
5026
        } else {
×
5027
                delete(s.outboundPeers, pubStr)
×
5028
        }
×
5029

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

×
5039
                p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
×
5040

×
5041
                // If this peer had an active persistent connection request,
×
5042
                // remove it.
×
5043
                if p.ConnReq() != nil {
×
5044
                        s.connMgr.Remove(p.ConnReq().ID())
×
5045
                }
×
5046

5047
                // Remove the peer's access permission from the access manager.
5048
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
5049
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
5050

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

×
5062
                // Inform the peer notifier of a peer offline event so that it
×
5063
                // can be reported to clients listening for peer events.
×
5064
                var pubKey [33]byte
×
5065
                copy(pubKey[:], pubSer)
×
5066

×
5067
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
5068
        }()
5069
}
5070

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

×
5079
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
5080

×
5081
        // Acquire mutex, but use explicit unlocking instead of defer for
×
5082
        // better granularity.  In certain conditions, this method requires
×
5083
        // making an outbound connection to a remote peer, which requires the
×
5084
        // lock to be released, and subsequently reacquired.
×
5085
        s.mu.Lock()
×
5086

×
5087
        // Ensure we're not already connected to this peer.
×
5088
        peer, err := s.findPeerByPubStr(targetPub)
×
5089

×
5090
        // When there's no error it means we already have a connection with this
×
5091
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
5092
        // set, we will ignore the existing connection and continue.
×
5093
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
5094
                s.mu.Unlock()
×
5095
                return &errPeerAlreadyConnected{peer: peer}
×
5096
        }
×
5097

5098
        // Peer was not found, continue to pursue connection with peer.
5099

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

5108
        // If there's not already a pending or active connection to this node,
5109
        // then instruct the connection manager to attempt to establish a
5110
        // persistent connection to the peer.
5111
        srvrLog.Debugf("Connecting to %v", addr)
×
5112
        if perm {
×
5113
                connReq := &connmgr.ConnReq{
×
5114
                        Addr:      addr,
×
5115
                        Permanent: true,
×
5116
                }
×
5117

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

×
5131
                go s.connMgr.Connect(connReq)
×
5132

×
5133
                return nil
×
5134
        }
5135
        s.mu.Unlock()
×
5136

×
5137
        // If we're not making a persistent connection, then we'll attempt to
×
5138
        // connect to the target peer. If the we can't make the connection, or
×
5139
        // the crypto negotiation breaks down, then return an error to the
×
5140
        // caller.
×
5141
        errChan := make(chan error, 1)
×
5142
        s.connectToPeer(addr, errChan, timeout)
×
5143

×
5144
        select {
×
5145
        case err := <-errChan:
×
5146
                return err
×
5147
        case <-s.quit:
×
5148
                return ErrServerShuttingDown
×
5149
        }
5150
}
5151

5152
// connectToPeer establishes a connection to a remote peer. errChan is used to
5153
// notify the caller if the connection attempt has failed. Otherwise, it will be
5154
// closed.
5155
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5156
        errChan chan<- error, timeout time.Duration) {
×
5157

×
5158
        conn, err := brontide.Dial(
×
5159
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
5160
        )
×
5161
        if err != nil {
×
5162
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
5163
                select {
×
5164
                case errChan <- err:
×
5165
                case <-s.quit:
×
5166
                }
5167
                return
×
5168
        }
5169

5170
        close(errChan)
×
5171

×
5172
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
5173
                conn.LocalAddr(), conn.RemoteAddr())
×
5174

×
5175
        s.OutboundPeerConnected(nil, conn)
×
5176
}
5177

5178
// DisconnectPeer sends the request to server to close the connection with peer
5179
// identified by public key.
5180
//
5181
// NOTE: This function is safe for concurrent access.
5182
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
5183
        pubBytes := pubKey.SerializeCompressed()
×
5184
        pubStr := string(pubBytes)
×
5185

×
5186
        s.mu.Lock()
×
5187
        defer s.mu.Unlock()
×
5188

×
5189
        // Check that were actually connected to this peer. If not, then we'll
×
5190
        // exit in an error as we can't disconnect from a peer that we're not
×
5191
        // currently connected to.
×
5192
        peer, err := s.findPeerByPubStr(pubStr)
×
5193
        if err == ErrPeerNotConnected {
×
5194
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
5195
        }
×
5196

5197
        srvrLog.Infof("Disconnecting from %v", peer)
×
5198

×
5199
        s.cancelConnReqs(pubStr, nil)
×
5200

×
5201
        // If this peer was formerly a persistent connection, then we'll remove
×
5202
        // them from this map so we don't attempt to re-connect after we
×
5203
        // disconnect.
×
5204
        delete(s.persistentPeers, pubStr)
×
5205
        delete(s.persistentPeersBackoff, pubStr)
×
5206

×
5207
        // Remove the peer by calling Disconnect. Previously this was done with
×
5208
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
5209
        //
×
5210
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
5211
        // goroutine because we might hold the server's mutex.
×
5212
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
5213

×
5214
        return nil
×
5215
}
5216

5217
// OpenChannel sends a request to the server to open a channel to the specified
5218
// peer identified by nodeKey with the passed channel funding parameters.
5219
//
5220
// NOTE: This function is safe for concurrent access.
5221
func (s *server) OpenChannel(
5222
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
5223

×
5224
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
5225
        // + a ChanOpen update, and we want to make sure the funding process is
×
5226
        // not blocked if the caller is not reading the updates.
×
5227
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
5228
        req.Err = make(chan error, 1)
×
5229

×
5230
        // First attempt to locate the target peer to open a channel with, if
×
5231
        // we're unable to locate the peer then this request will fail.
×
5232
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
5233
        s.mu.RLock()
×
5234
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
5235
        if !ok {
×
5236
                s.mu.RUnlock()
×
5237

×
5238
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5239
                return req.Updates, req.Err
×
5240
        }
×
5241
        req.Peer = peer
×
5242
        s.mu.RUnlock()
×
5243

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

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

×
5264
                return req.Updates, req.Err
×
5265
        }
×
5266

5267
        // Spawn a goroutine to send the funding workflow request to the funding
5268
        // manager. This allows the server to continue handling queries instead
5269
        // of blocking on this request which is exported as a synchronous
5270
        // request to the outside world.
5271
        go s.fundingMgr.InitFundingWorkflow(req)
×
5272

×
5273
        return req.Updates, req.Err
×
5274
}
5275

5276
// Peers returns a slice of all active peers.
5277
//
5278
// NOTE: This function is safe for concurrent access.
5279
func (s *server) Peers() []*peer.Brontide {
×
5280
        s.mu.RLock()
×
5281
        defer s.mu.RUnlock()
×
5282

×
5283
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
5284
        for _, peer := range s.peersByPub {
×
5285
                peers = append(peers, peer)
×
5286
        }
×
5287

5288
        return peers
×
5289
}
5290

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

5302
        // Using 1/10 of our duration as a margin, compute a random offset to
5303
        // avoid the nodes entering connection cycles.
5304
        margin := nextBackoff / 10
×
5305

×
5306
        var wiggle big.Int
×
5307
        wiggle.SetUint64(uint64(margin))
×
5308
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5309
                // Randomizing is not mission critical, so we'll just return the
×
5310
                // current backoff.
×
5311
                return nextBackoff
×
5312
        }
×
5313

5314
        // Otherwise add in our wiggle, but subtract out half of the margin so
5315
        // that the backoff can tweaked by 1/20 in either direction.
5316
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5317
}
5318

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

5323
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5324
func (s *server) fetchNodeAdvertisedAddrs(ctx context.Context,
5325
        pub *btcec.PublicKey) ([]net.Addr, error) {
×
5326

×
5327
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
5328
        if err != nil {
×
5329
                return nil, err
×
5330
        }
×
5331

5332
        node, err := s.graphDB.FetchLightningNode(ctx, vertex)
×
5333
        if err != nil {
×
5334
                return nil, err
×
5335
        }
×
5336

5337
        if len(node.Addresses) == 0 {
×
5338
                return nil, errNoAdvertisedAddr
×
5339
        }
×
5340

5341
        return node.Addresses, nil
×
5342
}
5343

5344
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5345
// channel update for a target channel.
5346
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5347
        *lnwire.ChannelUpdate1, error) {
×
5348

×
5349
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
5350
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
5351
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
5352
                if err != nil {
×
5353
                        return nil, err
×
5354
                }
×
5355

5356
                return netann.ExtractChannelUpdate(
×
5357
                        ourPubKey[:], info, edge1, edge2,
×
5358
                )
×
5359
        }
5360
}
5361

5362
// applyChannelUpdate applies the channel update to the different sub-systems of
5363
// the server. The useAlias boolean denotes whether or not to send an alias in
5364
// place of the real SCID.
5365
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5366
        op *wire.OutPoint, useAlias bool) error {
×
5367

×
5368
        var (
×
5369
                peerAlias    *lnwire.ShortChannelID
×
5370
                defaultAlias lnwire.ShortChannelID
×
5371
        )
×
5372

×
5373
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
5374

×
5375
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
5376
        // in the ChannelUpdate if it hasn't been announced yet.
×
5377
        if useAlias {
×
5378
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
5379
                if foundAlias != defaultAlias {
×
5380
                        peerAlias = &foundAlias
×
5381
                }
×
5382
        }
5383

5384
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
5385
                update, discovery.RemoteAlias(peerAlias),
×
5386
        )
×
5387
        select {
×
5388
        case err := <-errChan:
×
5389
                return err
×
5390
        case <-s.quit:
×
5391
                return ErrServerShuttingDown
×
5392
        }
5393
}
5394

5395
// SendCustomMessage sends a custom message to the peer with the specified
5396
// pubkey.
5397
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5398
        data []byte) error {
×
5399

×
5400
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5401
        if err != nil {
×
5402
                return err
×
5403
        }
×
5404

5405
        // We'll wait until the peer is active.
5406
        select {
×
5407
        case <-peer.ActiveSignal():
×
5408
        case <-peer.QuitSignal():
×
5409
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5410
        case <-s.quit:
×
5411
                return ErrServerShuttingDown
×
5412
        }
5413

5414
        msg, err := lnwire.NewCustom(msgType, data)
×
5415
        if err != nil {
×
5416
                return err
×
5417
        }
×
5418

5419
        // Send the message as low-priority. For now we assume that all
5420
        // application-defined message are low priority.
5421
        return peer.SendMessageLazy(true, msg)
×
5422
}
5423

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

×
5432
        return func() fn.Result[lnwallet.AddrWithKey] {
×
5433
                sweepAddr, err := wallet.NewAddress(
×
5434
                        lnwallet.TaprootPubkey, false,
×
5435
                        lnwallet.DefaultAccountName,
×
5436
                )
×
5437
                if err != nil {
×
5438
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5439
                }
×
5440

5441
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
5442
                if err != nil {
×
5443
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5444
                }
×
5445

5446
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
5447
                        wallet, netParams, addr,
×
5448
                )
×
5449
                if err != nil {
×
5450
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5451
                }
×
5452

5453
                return fn.Ok(lnwallet.AddrWithKey{
×
5454
                        DeliveryAddress: addr,
×
5455
                        InternalKey:     internalKeyDesc,
×
5456
                })
×
5457
        }
5458
}
5459

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

5470
        // Save the SCIDs in a map.
5471
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5472
        for _, c := range channels {
×
5473
                // If the channel is not pending, its FC has been finalized.
×
5474
                if !c.IsPending {
×
5475
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
5476
                }
×
5477
        }
5478

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

5493
        for _, c := range pendings {
×
5494
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5495
                        continue
×
5496
                }
5497

5498
                // If the channel is still reported as pending, remove it from
5499
                // the map.
5500
                delete(closedSCIDs, c.ShortChannelID)
×
5501

×
5502
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5503
                        c.ShortChannelID)
×
5504
        }
5505

5506
        return closedSCIDs
×
5507
}
5508

5509
// getStartingBeat returns the current beat. This is used during the startup to
5510
// initialize blockbeat consumers.
5511
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
5512
        // beat is the current blockbeat.
×
5513
        var beat *chainio.Beat
×
5514

×
5515
        // If the node is configured with nochainbackend mode (remote signer),
×
5516
        // we will skip fetching the best block.
×
5517
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5518
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5519
                        "mode")
×
5520

×
5521
                return &chainio.Beat{}, nil
×
5522
        }
×
5523

5524
        // We should get a notification with the current best block immediately
5525
        // by passing a nil block.
5526
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
5527
        if err != nil {
×
5528
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5529
        }
×
5530
        defer blockEpochs.Cancel()
×
5531

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

×
5540
                // Update the current blockbeat.
×
5541
                beat = chainio.NewBeat(*bestBlock)
×
5542

5543
        case <-s.quit:
×
5544
                srvrLog.Debug("LND shutting down")
×
5545
        }
5546

5547
        return beat, nil
×
5548
}
5549

5550
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5551
// point has an active RBF chan closer.
5552
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5553
        chanPoint wire.OutPoint) bool {
×
5554

×
5555
        pubBytes := peerPub.SerializeCompressed()
×
5556

×
5557
        s.mu.RLock()
×
5558
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
5559
        s.mu.RUnlock()
×
5560
        if !ok {
×
5561
                return false
×
5562
        }
×
5563

5564
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5565
}
5566

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

×
5575
        // First, we'll attempt to look up the channel based on it's
×
5576
        // ChannelPoint.
×
5577
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
5578
        if err != nil {
×
5579
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5580
        }
×
5581

5582
        // From the channel, we can now get the pubkey of the peer, then use
5583
        // that to eventually get the chan closer.
5584
        peerPub := channel.IdentityPub.SerializeCompressed()
×
5585

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

5595
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
5596
                ctx, chanPoint, feeRate, deliveryScript,
×
5597
        )
×
5598
        if err != nil {
×
5599
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5600
                        "%w", err)
×
5601
        }
×
5602

5603
        return closeUpdates, nil
×
5604
}
5605

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

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

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

5632
        return updates, nil
×
5633
}
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