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

lightningnetwork / lnd / 19153182187

06 Nov 2025 11:36PM UTC coverage: 54.793% (-11.9%) from 66.712%
19153182187

Pull #10352

github

web-flow
Merge d6c3e8fa9 into 096ab65b1
Pull Request #10352: [WIP] chainrpc: return Unavailable while notifier starts

110400 of 201486 relevant lines covered (54.79%)

21823.7 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
        paymentsdb "github.com/lightningnetwork/lnd/payments/db"
69
        "github.com/lightningnetwork/lnd/peer"
70
        "github.com/lightningnetwork/lnd/peernotifier"
71
        "github.com/lightningnetwork/lnd/pool"
72
        "github.com/lightningnetwork/lnd/queue"
73
        "github.com/lightningnetwork/lnd/routing"
74
        "github.com/lightningnetwork/lnd/routing/localchans"
75
        "github.com/lightningnetwork/lnd/routing/route"
76
        "github.com/lightningnetwork/lnd/subscribe"
77
        "github.com/lightningnetwork/lnd/sweep"
78
        "github.com/lightningnetwork/lnd/ticker"
79
        "github.com/lightningnetwork/lnd/tor"
80
        "github.com/lightningnetwork/lnd/walletunlocker"
81
        "github.com/lightningnetwork/lnd/watchtower/blob"
82
        "github.com/lightningnetwork/lnd/watchtower/wtclient"
83
        "github.com/lightningnetwork/lnd/watchtower/wtpolicy"
84
        "github.com/lightningnetwork/lnd/watchtower/wtserver"
85
)
86

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

231
        start sync.Once
232
        stop  sync.Once
233

234
        cfg *Config
235

236
        implCfg *ImplementationCfg
237

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

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

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

249
        chanStatusMgr *netann.ChanStatusManager
250

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

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

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

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

271
        mu sync.RWMutex
272

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

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

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

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

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

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

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

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

323
        cc *chainreg.ChainControl
324

325
        fundingMgr *funding.Manager
326

327
        graphDB *graphdb.ChannelGraph
328

329
        chanStateDB *channeldb.ChannelStateDB
330

331
        addrSource channeldb.AddrSource
332

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

337
        invoicesDB invoices.InvoiceDB
338

339
        // paymentsDB is the DB that contains all functions for managing
340
        // payments.
341
        paymentsDB paymentsdb.DB
342

343
        aliasMgr *aliasmgr.Manager
344

345
        htlcSwitch *htlcswitch.Switch
346

347
        interceptableSwitch *htlcswitch.InterceptableSwitch
348

349
        invoices *invoices.InvoiceRegistry
350

351
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
352

353
        channelNotifier *channelnotifier.ChannelNotifier
354

355
        peerNotifier *peernotifier.PeerNotifier
356

357
        htlcNotifier *htlcswitch.HtlcNotifier
358

359
        witnessBeacon contractcourt.WitnessBeacon
360

361
        breachArbitrator *contractcourt.BreachArbitrator
362

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

366
        graphBuilder *graph.Builder
367

368
        chanRouter *routing.ChannelRouter
369

370
        controlTower routing.ControlTower
371

372
        authGossiper *discovery.AuthenticatedGossiper
373

374
        localChanMgr *localchans.Manager
375

376
        utxoNursery *contractcourt.UtxoNursery
377

378
        sweeper *sweep.UtxoSweeper
379

380
        chainArb *contractcourt.ChainArbitrator
381

382
        sphinx *hop.OnionProcessor
383

384
        towerClientMgr *wtclient.Manager
385

386
        connMgr *connmgr.ConnManager
387

388
        sigPool *lnwallet.SigPool
389

390
        writePool *pool.Write
391

392
        readPool *pool.Read
393

394
        tlsManager *TLSManager
395

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

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

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

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

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

418
        hostAnn *netann.HostAnnouncer
419

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

423
        customMessageServer *subscribe.Server
424

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

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

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

435
        quit chan struct{}
436

437
        wg sync.WaitGroup
438
}
439

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

448
        s.wg.Add(1)
×
449
        go func() {
×
450
                defer func() {
×
451
                        graphSub.Cancel()
×
452
                        s.wg.Done()
×
453
                }()
×
454

455
                for {
×
456
                        select {
×
457
                        case <-s.quit:
×
458
                                return
×
459

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

467
                                for _, update := range topChange.NodeUpdates {
×
468
                                        pubKeyStr := string(
×
469
                                                update.IdentityKey.
×
470
                                                        SerializeCompressed(),
×
471
                                        )
×
472

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

482
                                        addrs := make([]*lnwire.NetAddress, 0,
×
483
                                                len(update.Addresses))
×
484

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

495
                                        s.mu.Lock()
×
496

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

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

511
                                        s.mu.Unlock()
×
512

×
513
                                        s.connectToPersistentPeer(pubKeyStr)
×
514
                                }
515
                        }
516
                }
517
        }()
518

519
        return nil
×
520
}
521

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

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

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

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

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

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

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

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

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

×
591
        var (
×
592
                err         error
×
593
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
594

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

×
602
        netParams := cfg.ActiveNetParams.Params
×
603

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

×
610
        writeBufferPool := pool.NewWriteBuffer(
×
611
                pool.DefaultWriteBufferGCInterval,
×
612
                pool.DefaultWriteBufferExpiryInterval,
×
613
        )
×
614

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

×
619
        readBufferPool := pool.NewReadBuffer(
×
620
                pool.DefaultReadBufferGCInterval,
×
621
                pool.DefaultReadBufferExpiryInterval,
×
622
        )
×
623

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

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

×
633
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
634
                        "overlay channels are not supported " +
×
635
                        "in a standalone lnd build")
×
636
        }
×
637

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

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

×
674
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
675

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

×
691
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
692
                        cc.ChainNotifier,
×
693
                ),
×
694
                channelNotifier: channelnotifier.New(
×
695
                        dbs.ChanStateDB.ChannelStateDB(),
×
696
                ),
×
697

×
698
                identityECDH:   nodeKeyECDH,
×
699
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
700
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
701

×
702
                listenAddrs: listenAddrs,
×
703

×
704
                // TODO(roasbeef): derive proper onion key based on rotation
×
705
                // schedule
×
706
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
707

×
708
                torController: torController,
×
709

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

×
720
                peersByPub:                make(map[string]*peer.Brontide),
×
721
                inboundPeers:              make(map[string]*peer.Brontide),
×
722
                outboundPeers:             make(map[string]*peer.Brontide),
×
723
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
724
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
725

×
726
                invoiceHtlcModifier: invoiceHtlcModifier,
×
727

×
728
                customMessageServer: subscribe.NewServer(),
×
729

×
730
                tlsManager: tlsManager,
×
731

×
732
                featureMgr: featureMgr,
×
733
                quit:       make(chan struct{}),
×
734
        }
×
735

×
736
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
737
        if err != nil {
×
738
                return nil, err
×
739
        }
×
740

741
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
742
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
743
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
744
        )
×
745
        s.invoices = invoices.NewRegistry(
×
746
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
747
        )
×
748

×
749
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
750

×
751
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
752
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
753

×
754
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
755
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
756
                if err != nil {
×
757
                        return err
×
758
                }
×
759

760
                s.htlcSwitch.UpdateLinkAliases(link)
×
761

×
762
                return nil
×
763
        }
764

765
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
766
        if err != nil {
×
767
                return nil, err
×
768
        }
×
769

770
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
771
                DB:                   dbs.ChanStateDB,
×
772
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
773
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
774
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
775
                LocalChannelClose: func(pubKey []byte,
×
776
                        request *htlcswitch.ChanClose) {
×
777

×
778
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
779
                        if err != nil {
×
780
                                srvrLog.Errorf("unable to close channel, peer"+
×
781
                                        " with %v id can't be found: %v",
×
782
                                        pubKey, err,
×
783
                                )
×
784
                                return
×
785
                        }
×
786

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

822
        s.witnessBeacon = newPreimageBeacon(
×
823
                dbs.ChanStateDB.NewWitnessCache(),
×
824
                s.interceptableSwitch.ForwardPacket,
×
825
        )
×
826

×
827
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
828
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
829
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
830
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
831
                OurPubKey:                nodeKeyDesc.PubKey,
×
832
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
833
                MessageSigner:            s.nodeSigner,
×
834
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
835
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
836
                DB:                       s.chanStateDB,
×
837
                Graph:                    dbs.GraphDB,
×
838
        }
×
839

×
840
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
841
        if err != nil {
×
842
                return nil, err
×
843
        }
×
844
        s.chanStatusMgr = chanStatusMgr
×
845

×
846
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
847
        // port forwarding for users behind a NAT.
×
848
        if cfg.NAT {
×
849
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
850

×
851
                discoveryTimeout := time.Duration(10 * time.Second)
×
852

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

×
867
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
868
                                "enabled device")
×
869

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

879
                        s.natTraversal = pmp
×
880
                }
881
        }
882

883
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
×
884
        // Set the self node which represents our node in the graph.
×
885
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
×
886
        if err != nil {
×
887
                return nil, err
×
888
        }
×
889

890
        // The router will get access to the payment ID sequencer, such that it
891
        // can generate unique payment IDs.
892
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
893
        if err != nil {
×
894
                return nil, err
×
895
        }
×
896

897
        // Instantiate mission control with config from the sub server.
898
        //
899
        // TODO(joostjager): When we are further in the process of moving to sub
900
        // servers, the mission control instance itself can be moved there too.
901
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
902

×
903
        // We only initialize a probability estimator if there's no custom one.
×
904
        var estimator routing.Estimator
×
905
        if cfg.Estimator != nil {
×
906
                estimator = cfg.Estimator
×
907
        } else {
×
908
                switch routingConfig.ProbabilityEstimatorType {
×
909
                case routing.AprioriEstimatorName:
×
910
                        aCfg := routingConfig.AprioriConfig
×
911
                        aprioriConfig := routing.AprioriConfig{
×
912
                                AprioriHopProbability: aCfg.HopProbability,
×
913
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
914
                                AprioriWeight:         aCfg.Weight,
×
915
                                CapacityFraction:      aCfg.CapacityFraction,
×
916
                        }
×
917

×
918
                        estimator, err = routing.NewAprioriEstimator(
×
919
                                aprioriConfig,
×
920
                        )
×
921
                        if err != nil {
×
922
                                return nil, err
×
923
                        }
×
924

925
                case routing.BimodalEstimatorName:
×
926
                        bCfg := routingConfig.BimodalConfig
×
927
                        bimodalConfig := routing.BimodalConfig{
×
928
                                BimodalNodeWeight: bCfg.NodeWeight,
×
929
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
930
                                        bCfg.Scale,
×
931
                                ),
×
932
                                BimodalDecayTime: bCfg.DecayTime,
×
933
                        }
×
934

×
935
                        estimator, err = routing.NewBimodalEstimator(
×
936
                                bimodalConfig,
×
937
                        )
×
938
                        if err != nil {
×
939
                                return nil, err
×
940
                        }
×
941

942
                default:
×
943
                        return nil, fmt.Errorf("unknown estimator type %v",
×
944
                                routingConfig.ProbabilityEstimatorType)
×
945
                }
946
        }
947

948
        mcCfg := &routing.MissionControlConfig{
×
949
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
950
                Estimator:               estimator,
×
951
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
952
                McFlushInterval:         routingConfig.McFlushInterval,
×
953
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
954
        }
×
955

×
956
        s.missionController, err = routing.NewMissionController(
×
957
                dbs.ChanStateDB, nodePubKey, mcCfg,
×
958
        )
×
959
        if err != nil {
×
960
                return nil, fmt.Errorf("can't create mission control "+
×
961
                        "manager: %w", err)
×
962
        }
×
963
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
964
                routing.DefaultMissionControlNamespace,
×
965
        )
×
966
        if err != nil {
×
967
                return nil, fmt.Errorf("can't create mission control in the "+
×
968
                        "default namespace: %w", err)
×
969
        }
×
970

971
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
972
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
973
                int64(routingConfig.AttemptCost),
×
974
                float64(routingConfig.AttemptCostPPM)/10000,
×
975
                routingConfig.MinRouteProbability)
×
976

×
977
        pathFindingConfig := routing.PathFindingConfig{
×
978
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
979
                        routingConfig.AttemptCost,
×
980
                ),
×
981
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
982
                MinProbability: routingConfig.MinRouteProbability,
×
983
        }
×
984

×
985
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
986
        if err != nil {
×
987
                return nil, fmt.Errorf("error getting source node: %w", err)
×
988
        }
×
989
        paymentSessionSource := &routing.SessionSource{
×
990
                GraphSessionFactory: dbs.GraphDB,
×
991
                SourceNode:          sourceNode,
×
992
                MissionControl:      s.defaultMC,
×
993
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
994
                PathFindingConfig:   pathFindingConfig,
×
995
        }
×
996

×
997
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
×
998

×
999
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
1000
                cfg.Routing.StrictZombiePruning
×
1001

×
1002
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
1003
                SelfNode:            nodePubKey,
×
1004
                Graph:               dbs.GraphDB,
×
1005
                Chain:               cc.ChainIO,
×
1006
                ChainView:           cc.ChainView,
×
1007
                Notifier:            cc.ChainNotifier,
×
1008
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
1009
                GraphPruneInterval:  time.Hour,
×
1010
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
1011
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
1012
                StrictZombiePruning: strictPruning,
×
1013
                IsAlias:             aliasmgr.IsAlias,
×
1014
        })
×
1015
        if err != nil {
×
1016
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1017
        }
×
1018

1019
        s.chanRouter, err = routing.New(routing.Config{
×
1020
                SelfNode:           nodePubKey,
×
1021
                RoutingGraph:       dbs.GraphDB,
×
1022
                Chain:              cc.ChainIO,
×
1023
                Payer:              s.htlcSwitch,
×
1024
                Control:            s.controlTower,
×
1025
                MissionControl:     s.defaultMC,
×
1026
                SessionSource:      paymentSessionSource,
×
1027
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
1028
                NextPaymentID:      sequencer.NextID,
×
1029
                PathFindingConfig:  pathFindingConfig,
×
1030
                Clock:              clock.NewDefaultClock(),
×
1031
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
1032
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
1033
                TrafficShaper:      implCfg.TrafficShaper,
×
1034
        })
×
1035
        if err != nil {
×
1036
                return nil, fmt.Errorf("can't create router: %w", err)
×
1037
        }
×
1038

1039
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
1040
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
1041
        if err != nil {
×
1042
                return nil, err
×
1043
        }
×
1044
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
1045
        if err != nil {
×
1046
                return nil, err
×
1047
        }
×
1048

1049
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
1050

×
1051
        s.authGossiper = discovery.New(discovery.Config{
×
1052
                Graph:                 s.graphBuilder,
×
1053
                ChainIO:               s.cc.ChainIO,
×
1054
                Notifier:              s.cc.ChainNotifier,
×
1055
                ChainParams:           s.cfg.ActiveNetParams.Params,
×
1056
                Broadcast:             s.BroadcastMessage,
×
1057
                ChanSeries:            chanSeries,
×
1058
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
1059
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
1060
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
1061
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
×
1062
                        error) {
×
1063

×
1064
                        return s.genNodeAnnouncement(nil)
×
1065
                },
×
1066
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1067
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1068
                RetransmitTicker:        ticker.New(time.Minute * 30),
1069
                RebroadcastInterval:     time.Hour * 24,
1070
                WaitingProofStore:       waitingProofStore,
1071
                MessageStore:            gossipMessageStore,
1072
                AnnSigner:               s.nodeSigner,
1073
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1074
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1075
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1076
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1077
                MinimumBatchSize:        10,
1078
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1079
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1080
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1081
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1082
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1083
                IsAlias:                 aliasmgr.IsAlias,
1084
                SignAliasUpdate:         s.signAliasUpdate,
1085
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1086
                GetAlias:                s.aliasMgr.GetPeerAlias,
1087
                FindChannel:             s.findChannel,
1088
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1089
                ScidCloser:              scidCloserMan,
1090
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1091
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1092
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1093
                FilterConcurrency:       cfg.Gossip.FilterConcurrency,
1094
                BanThreshold:            cfg.Gossip.BanThreshold,
1095
                PeerMsgRateBytes:        cfg.Gossip.PeerMsgRateBytes,
1096
        }, nodeKeyDesc)
1097

1098
        accessCfg := &accessManConfig{
×
1099
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
1100
                        error) {
×
1101

×
1102
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
1103
                        return s.chanStateDB.FetchPermAndTempPeers(
×
1104
                                genesisHash[:],
×
1105
                        )
×
1106
                },
×
1107
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1108
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1109
        }
1110

1111
        peerAccessMan, err := newAccessMan(accessCfg)
×
1112
        if err != nil {
×
1113
                return nil, err
×
1114
        }
×
1115

1116
        s.peerAccessMan = peerAccessMan
×
1117

×
1118
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
1119
        //nolint:ll
×
1120
        s.localChanMgr = &localchans.Manager{
×
1121
                SelfPub:              nodeKeyDesc.PubKey,
×
1122
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
1123
                ForAllOutgoingChannels: func(ctx context.Context,
×
1124
                        cb func(*models.ChannelEdgeInfo,
×
1125
                                *models.ChannelEdgePolicy) error,
×
1126
                        reset func()) error {
×
1127

×
1128
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
1129
                                func(c *models.ChannelEdgeInfo,
×
1130
                                        e *models.ChannelEdgePolicy,
×
1131
                                        _ *models.ChannelEdgePolicy) error {
×
1132

×
1133
                                        // NOTE: The invoked callback here may
×
1134
                                        // receive a nil channel policy.
×
1135
                                        return cb(c, e)
×
1136
                                }, reset,
×
1137
                        )
1138
                },
1139
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1140
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1141
                FetchChannel:              s.chanStateDB.FetchChannel,
1142
                AddEdge: func(ctx context.Context,
1143
                        edge *models.ChannelEdgeInfo) error {
×
1144

×
1145
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1146
                },
×
1147
        }
1148

1149
        utxnStore, err := contractcourt.NewNurseryStore(
×
1150
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
1151
        )
×
1152
        if err != nil {
×
1153
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1154
                return nil, err
×
1155
        }
×
1156

1157
        sweeperStore, err := sweep.NewSweeperStore(
×
1158
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
1159
        )
×
1160
        if err != nil {
×
1161
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1162
                return nil, err
×
1163
        }
×
1164

1165
        aggregator := sweep.NewBudgetAggregator(
×
1166
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
1167
                s.implCfg.AuxSweeper,
×
1168
        )
×
1169

×
1170
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1171
                Signer:     cc.Wallet.Cfg.Signer,
×
1172
                Wallet:     cc.Wallet,
×
1173
                Estimator:  cc.FeeEstimator,
×
1174
                Notifier:   cc.ChainNotifier,
×
1175
                AuxSweeper: s.implCfg.AuxSweeper,
×
1176
        })
×
1177

×
1178
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
1179
                FeeEstimator: cc.FeeEstimator,
×
1180
                GenSweepScript: newSweepPkScriptGen(
×
1181
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1182
                ),
×
1183
                Signer:               cc.Wallet.Cfg.Signer,
×
1184
                Wallet:               newSweeperWallet(cc.Wallet),
×
1185
                Mempool:              cc.MempoolNotifier,
×
1186
                Notifier:             cc.ChainNotifier,
×
1187
                Store:                sweeperStore,
×
1188
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
1189
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
1190
                Aggregator:           aggregator,
×
1191
                Publisher:            s.txPublisher,
×
1192
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
1193
        })
×
1194

×
1195
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
1196
                ChainIO:             cc.ChainIO,
×
1197
                ConfDepth:           1,
×
1198
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
1199
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
1200
                Notifier:            cc.ChainNotifier,
×
1201
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
1202
                Store:               utxnStore,
×
1203
                SweepInput:          s.sweeper.SweepInput,
×
1204
                Budget:              s.cfg.Sweeper.Budget,
×
1205
        })
×
1206

×
1207
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
1208
        closeLink := func(chanPoint *wire.OutPoint,
×
1209
                closureType contractcourt.ChannelCloseType) {
×
1210
                // TODO(conner): Properly respect the update and error channels
×
1211
                // returned by CloseLink.
×
1212

×
1213
                // Instruct the switch to close the channel.  Provide no close out
×
1214
                // delivery script or target fee per kw because user input is not
×
1215
                // available when the remote peer closes the channel.
×
1216
                s.htlcSwitch.CloseLink(
×
1217
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
1218
                )
×
1219
        }
×
1220

1221
        // We will use the following channel to reliably hand off contract
1222
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1223
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
×
1224

×
1225
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
1226
                &contractcourt.BreachConfig{
×
1227
                        CloseLink: closeLink,
×
1228
                        DB:        s.chanStateDB,
×
1229
                        Estimator: s.cc.FeeEstimator,
×
1230
                        GenSweepScript: newSweepPkScriptGen(
×
1231
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1232
                        ),
×
1233
                        Notifier:           cc.ChainNotifier,
×
1234
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
1235
                        ContractBreaches:   contractBreaches,
×
1236
                        Signer:             cc.Wallet.Cfg.Signer,
×
1237
                        Store: contractcourt.NewRetributionStore(
×
1238
                                dbs.ChanStateDB,
×
1239
                        ),
×
1240
                        AuxSweeper: s.implCfg.AuxSweeper,
×
1241
                },
×
1242
        )
×
1243

×
1244
        //nolint:ll
×
1245
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
1246
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
1247
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
1248
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
1249
                NewSweepAddr: func() ([]byte, error) {
×
1250
                        addr, err := newSweepPkScriptGen(
×
1251
                                cc.Wallet, netParams,
×
1252
                        )().Unpack()
×
1253
                        if err != nil {
×
1254
                                return nil, err
×
1255
                        }
×
1256

1257
                        return addr.DeliveryAddress, nil
×
1258
                },
1259
                PublishTx: cc.Wallet.PublishTransaction,
1260
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
1261
                        for _, msg := range msgs {
×
1262
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
1263
                                if err != nil {
×
1264
                                        return err
×
1265
                                }
×
1266
                        }
1267
                        return nil
×
1268
                },
1269
                IncubateOutputs: func(chanPoint wire.OutPoint,
1270
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1271
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1272
                        broadcastHeight uint32,
1273
                        deadlineHeight fn.Option[int32]) error {
×
1274

×
1275
                        return s.utxoNursery.IncubateOutputs(
×
1276
                                chanPoint, outHtlcRes, inHtlcRes,
×
1277
                                broadcastHeight, deadlineHeight,
×
1278
                        )
×
1279
                },
×
1280
                PreimageDB:   s.witnessBeacon,
1281
                Notifier:     cc.ChainNotifier,
1282
                Mempool:      cc.MempoolNotifier,
1283
                Signer:       cc.Wallet.Cfg.Signer,
1284
                FeeEstimator: cc.FeeEstimator,
1285
                ChainIO:      cc.ChainIO,
1286
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
1287
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1288
                        s.htlcSwitch.RemoveLink(chanID)
×
1289
                        return nil
×
1290
                },
×
1291
                IsOurAddress: cc.Wallet.IsOurAddress,
1292
                ContractBreach: func(chanPoint wire.OutPoint,
1293
                        breachRet *lnwallet.BreachRetribution) error {
×
1294

×
1295
                        // processACK will handle the BreachArbitrator ACKing
×
1296
                        // the event.
×
1297
                        finalErr := make(chan error, 1)
×
1298
                        processACK := func(brarErr error) {
×
1299
                                if brarErr != nil {
×
1300
                                        finalErr <- brarErr
×
1301
                                        return
×
1302
                                }
×
1303

1304
                                // If the BreachArbitrator successfully handled
1305
                                // the event, we can signal that the handoff
1306
                                // was successful.
1307
                                finalErr <- nil
×
1308
                        }
1309

1310
                        event := &contractcourt.ContractBreachEvent{
×
1311
                                ChanPoint:         chanPoint,
×
1312
                                ProcessACK:        processACK,
×
1313
                                BreachRetribution: breachRet,
×
1314
                        }
×
1315

×
1316
                        // Send the contract breach event to the
×
1317
                        // BreachArbitrator.
×
1318
                        select {
×
1319
                        case contractBreaches <- event:
×
1320
                        case <-s.quit:
×
1321
                                return ErrServerShuttingDown
×
1322
                        }
1323

1324
                        // We'll wait for a final error to be available from
1325
                        // the BreachArbitrator.
1326
                        select {
×
1327
                        case err := <-finalErr:
×
1328
                                return err
×
1329
                        case <-s.quit:
×
1330
                                return ErrServerShuttingDown
×
1331
                        }
1332
                },
1333
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
1334
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
1335
                },
×
1336
                Sweeper:                       s.sweeper,
1337
                Registry:                      s.invoices,
1338
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1339
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1340
                OnionProcessor:                s.sphinx,
1341
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1342
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1343
                Clock:                         clock.NewDefaultClock(),
1344
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1345
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1346
                HtlcNotifier:                  s.htlcNotifier,
1347
                Budget:                        *s.cfg.Sweeper.Budget,
1348

1349
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1350
                QueryIncomingCircuit: func(
1351
                        circuit models.CircuitKey) *models.CircuitKey {
×
1352

×
1353
                        // Get the circuit map.
×
1354
                        circuits := s.htlcSwitch.CircuitLookup()
×
1355

×
1356
                        // Lookup the outgoing circuit.
×
1357
                        pc := circuits.LookupOpenCircuit(circuit)
×
1358
                        if pc == nil {
×
1359
                                return nil
×
1360
                        }
×
1361

1362
                        return &pc.Incoming
×
1363
                },
1364
                AuxLeafStore: implCfg.AuxLeafStore,
1365
                AuxSigner:    implCfg.AuxSigner,
1366
                AuxResolver:  implCfg.AuxContractResolver,
1367
        }, dbs.ChanStateDB)
1368

1369
        // Select the configuration and funding parameters for Bitcoin.
1370
        chainCfg := cfg.Bitcoin
×
1371
        minRemoteDelay := funding.MinBtcRemoteDelay
×
1372
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
1373

×
1374
        var chanIDSeed [32]byte
×
1375
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1376
                return nil, err
×
1377
        }
×
1378

1379
        // Wrap the DeleteChannelEdges method so that the funding manager can
1380
        // use it without depending on several layers of indirection.
1381
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
1382
                *models.ChannelEdgePolicy, error) {
×
1383

×
1384
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
1385
                        scid.ToUint64(),
×
1386
                )
×
1387
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1388
                        // This is unlikely but there is a slim chance of this
×
1389
                        // being hit if lnd was killed via SIGKILL and the
×
1390
                        // funding manager was stepping through the delete
×
1391
                        // alias edge logic.
×
1392
                        return nil, nil
×
1393
                } else if err != nil {
×
1394
                        return nil, err
×
1395
                }
×
1396

1397
                // Grab our key to find our policy.
1398
                var ourKey [33]byte
×
1399
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1400

×
1401
                var ourPolicy *models.ChannelEdgePolicy
×
1402
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1403
                        ourPolicy = e1
×
1404
                } else {
×
1405
                        ourPolicy = e2
×
1406
                }
×
1407

1408
                if ourPolicy == nil {
×
1409
                        // Something is wrong, so return an error.
×
1410
                        return nil, fmt.Errorf("we don't have an edge")
×
1411
                }
×
1412

1413
                err = s.graphDB.DeleteChannelEdges(
×
1414
                        false, false, scid.ToUint64(),
×
1415
                )
×
1416
                return ourPolicy, err
×
1417
        }
1418

1419
        // For the reservationTimeout and the zombieSweeperInterval different
1420
        // values are set in case we are in a dev environment so enhance test
1421
        // capacilities.
1422
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
1423
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
1424

×
1425
        // Get the development config for funding manager. If we are not in
×
1426
        // development mode, this would be nil.
×
1427
        var devCfg *funding.DevConfig
×
1428
        if lncfg.IsDevBuild() {
×
1429
                devCfg = &funding.DevConfig{
×
1430
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
1431
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
1432
                                GetMaxWaitNumBlocksFundingConf(),
×
1433
                }
×
1434

×
1435
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
1436
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
1437

×
1438
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1439
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1440
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
1441
        }
×
1442

1443
        //nolint:ll
1444
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
1445
                Dev:                devCfg,
×
1446
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
1447
                IDKey:              nodeKeyDesc.PubKey,
×
1448
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
1449
                Wallet:             cc.Wallet,
×
1450
                PublishTransaction: cc.Wallet.PublishTransaction,
×
1451
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
1452
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
1453
                },
×
1454
                Notifier:     cc.ChainNotifier,
1455
                ChannelDB:    s.chanStateDB,
1456
                FeeEstimator: cc.FeeEstimator,
1457
                SignMessage:  cc.MsgSigner.SignMessage,
1458
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement1,
1459
                        error) {
×
1460

×
1461
                        return s.genNodeAnnouncement(nil)
×
1462
                },
×
1463
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1464
                NotifyWhenOnline:     s.NotifyWhenOnline,
1465
                TempChanIDSeed:       chanIDSeed,
1466
                FindChannel:          s.findChannel,
1467
                DefaultRoutingPolicy: cc.RoutingPolicy,
1468
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1469
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1470
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
1471
                        // For large channels we increase the number
×
1472
                        // of confirmations we require for the
×
1473
                        // channel to be considered open. As it is
×
1474
                        // always the responder that gets to choose
×
1475
                        // value, the pushAmt is value being pushed
×
1476
                        // to us. This means we have more to lose
×
1477
                        // in the case this gets re-orged out, and
×
1478
                        // we will require more confirmations before
×
1479
                        // we consider it open.
×
1480

×
1481
                        // In case the user has explicitly specified
×
1482
                        // a default value for the number of
×
1483
                        // confirmations, we use it.
×
1484
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
1485
                        if defaultConf != 0 {
×
1486
                                return defaultConf
×
1487
                        }
×
1488

1489
                        minConf := uint64(3)
×
1490
                        maxConf := uint64(6)
×
1491

×
1492
                        // If this is a wumbo channel, then we'll require the
×
1493
                        // max amount of confirmations.
×
1494
                        if chanAmt > MaxFundingAmount {
×
1495
                                return uint16(maxConf)
×
1496
                        }
×
1497

1498
                        // If not we return a value scaled linearly
1499
                        // between 3 and 6, depending on channel size.
1500
                        // TODO(halseth): Use 1 as minimum?
1501
                        maxChannelSize := uint64(
×
1502
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1503
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1504
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1505
                        if conf < minConf {
×
1506
                                conf = minConf
×
1507
                        }
×
1508
                        if conf > maxConf {
×
1509
                                conf = maxConf
×
1510
                        }
×
1511
                        return uint16(conf)
×
1512
                },
1513
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
1514
                        // We scale the remote CSV delay (the time the
×
1515
                        // remote have to claim funds in case of a unilateral
×
1516
                        // close) linearly from minRemoteDelay blocks
×
1517
                        // for small channels, to maxRemoteDelay blocks
×
1518
                        // for channels of size MaxFundingAmount.
×
1519

×
1520
                        // In case the user has explicitly specified
×
1521
                        // a default value for the remote delay, we
×
1522
                        // use it.
×
1523
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
1524
                        if defaultDelay > 0 {
×
1525
                                return defaultDelay
×
1526
                        }
×
1527

1528
                        // If this is a wumbo channel, then we'll require the
1529
                        // max value.
1530
                        if chanAmt > MaxFundingAmount {
×
1531
                                return maxRemoteDelay
×
1532
                        }
×
1533

1534
                        // If not we scale according to channel size.
1535
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1536
                                chanAmt / MaxFundingAmount)
×
1537
                        if delay < minRemoteDelay {
×
1538
                                delay = minRemoteDelay
×
1539
                        }
×
1540
                        if delay > maxRemoteDelay {
×
1541
                                delay = maxRemoteDelay
×
1542
                        }
×
1543
                        return delay
×
1544
                },
1545
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1546
                        peerKey *btcec.PublicKey) error {
×
1547

×
1548
                        // First, we'll mark this new peer as a persistent peer
×
1549
                        // for re-connection purposes. If the peer is not yet
×
1550
                        // tracked or the user hasn't requested it to be perm,
×
1551
                        // we'll set false to prevent the server from continuing
×
1552
                        // to connect to this peer even if the number of
×
1553
                        // channels with this peer is zero.
×
1554
                        s.mu.Lock()
×
1555
                        pubStr := string(peerKey.SerializeCompressed())
×
1556
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
1557
                                s.persistentPeers[pubStr] = false
×
1558
                        }
×
1559
                        s.mu.Unlock()
×
1560

×
1561
                        // With that taken care of, we'll send this channel to
×
1562
                        // the chain arb so it can react to on-chain events.
×
1563
                        return s.chainArb.WatchNewChannel(channel)
×
1564
                },
1565
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
1566
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1567
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
1568
                },
×
1569
                RequiredRemoteChanReserve: func(chanAmt,
1570
                        dustLimit btcutil.Amount) btcutil.Amount {
×
1571

×
1572
                        // By default, we'll require the remote peer to maintain
×
1573
                        // at least 1% of the total channel capacity at all
×
1574
                        // times. If this value ends up dipping below the dust
×
1575
                        // limit, then we'll use the dust limit itself as the
×
1576
                        // reserve as required by BOLT #2.
×
1577
                        reserve := chanAmt / 100
×
1578
                        if reserve < dustLimit {
×
1579
                                reserve = dustLimit
×
1580
                        }
×
1581

1582
                        return reserve
×
1583
                },
1584
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
1585
                        // By default, we'll allow the remote peer to fully
×
1586
                        // utilize the full bandwidth of the channel, minus our
×
1587
                        // required reserve.
×
1588
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
1589
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
1590
                },
×
1591
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
1592
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
1593
                                return cfg.DefaultRemoteMaxHtlcs
×
1594
                        }
×
1595

1596
                        // By default, we'll permit them to utilize the full
1597
                        // channel bandwidth.
1598
                        return uint16(input.MaxHTLCNumber / 2)
×
1599
                },
1600
                ZombieSweeperInterval:         zombieSweeperInterval,
1601
                ReservationTimeout:            reservationTimeout,
1602
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1603
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1604
                MaxPendingChannels:            cfg.MaxPendingChannels,
1605
                RejectPush:                    cfg.RejectPush,
1606
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1607
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1608
                OpenChannelPredicate:          chanPredicate,
1609
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1610
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1611
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1612
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1613
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1614
                DeleteAliasEdge:      deleteAliasEdge,
1615
                AliasManager:         s.aliasMgr,
1616
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1617
                AuxFundingController: implCfg.AuxFundingController,
1618
                AuxSigner:            implCfg.AuxSigner,
1619
                AuxResolver:          implCfg.AuxContractResolver,
1620
                AuxChannelNegotiator: implCfg.AuxChannelNegotiator,
1621
        })
1622
        if err != nil {
×
1623
                return nil, err
×
1624
        }
×
1625

1626
        // Next, we'll assemble the sub-system that will maintain an on-disk
1627
        // static backup of the latest channel state.
1628
        chanNotifier := &channelNotifier{
×
1629
                chanNotifier: s.channelNotifier,
×
1630
                addrs:        s.addrSource,
×
1631
        }
×
1632
        backupFile := chanbackup.NewMultiFile(
×
1633
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
1634
        )
×
1635
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
1636
                ctx, s.chanStateDB, s.addrSource,
×
1637
        )
×
1638
        if err != nil {
×
1639
                return nil, err
×
1640
        }
×
1641
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
1642
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
1643
        )
×
1644
        if err != nil {
×
1645
                return nil, err
×
1646
        }
×
1647

1648
        // Assemble a peer notifier which will provide clients with subscriptions
1649
        // to peer online and offline events.
1650
        s.peerNotifier = peernotifier.New()
×
1651

×
1652
        // Create a channel event store which monitors all open channels.
×
1653
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
1654
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
1655
                        return s.channelNotifier.SubscribeChannelEvents()
×
1656
                },
×
1657
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
1658
                        return s.peerNotifier.SubscribePeerEvents()
×
1659
                },
×
1660
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1661
                Clock:           clock.NewDefaultClock(),
1662
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1663
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1664
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1665
        })
1666

1667
        if cfg.WtClient.Active {
×
1668
                policy := wtpolicy.DefaultPolicy()
×
1669
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
1670

×
1671
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1672
                // protocol operations on sat/kw.
×
1673
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
1674
                        1000 * cfg.WtClient.SweepFeeRate,
×
1675
                )
×
1676

×
1677
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1678

×
1679
                if err := policy.Validate(); err != nil {
×
1680
                        return nil, err
×
1681
                }
×
1682

1683
                // authDial is the wrapper around the btrontide.Dial for the
1684
                // watchtower.
1685
                authDial := func(localKey keychain.SingleKeyECDH,
×
1686
                        netAddr *lnwire.NetAddress,
×
1687
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
1688

×
1689
                        return brontide.Dial(
×
1690
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1691
                        )
×
1692
                }
×
1693

1694
                // buildBreachRetribution is a call-back that can be used to
1695
                // query the BreachRetribution info and channel type given a
1696
                // channel ID and commitment height.
1697
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
1698
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
1699
                        channeldb.ChannelType, error) {
×
1700

×
1701
                        channel, err := s.chanStateDB.FetchChannelByID(
×
1702
                                nil, chanID,
×
1703
                        )
×
1704
                        if err != nil {
×
1705
                                return nil, 0, err
×
1706
                        }
×
1707

1708
                        br, err := lnwallet.NewBreachRetribution(
×
1709
                                channel, commitHeight, 0, nil,
×
1710
                                implCfg.AuxLeafStore,
×
1711
                                implCfg.AuxContractResolver,
×
1712
                        )
×
1713
                        if err != nil {
×
1714
                                return nil, 0, err
×
1715
                        }
×
1716

1717
                        return br, channel.ChanType, nil
×
1718
                }
1719

1720
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
1721

×
1722
                // Copy the policy for legacy channels and set the blob flag
×
1723
                // signalling support for anchor channels.
×
1724
                anchorPolicy := policy
×
1725
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1726

×
1727
                // Copy the policy for legacy channels and set the blob flag
×
1728
                // signalling support for taproot channels.
×
1729
                taprootPolicy := policy
×
1730
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
1731
                        blob.FlagTaprootChannel,
×
1732
                )
×
1733

×
1734
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1735
                        FetchClosedChannel:     fetchClosedChannel,
×
1736
                        BuildBreachRetribution: buildBreachRetribution,
×
1737
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
1738
                        ChainNotifier:          s.cc.ChainNotifier,
×
1739
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
1740
                                error) {
×
1741

×
1742
                                return s.channelNotifier.
×
1743
                                        SubscribeChannelEvents()
×
1744
                        },
×
1745
                        Signer: cc.Wallet.Cfg.Signer,
1746
                        NewAddress: func() ([]byte, error) {
×
1747
                                addr, err := newSweepPkScriptGen(
×
1748
                                        cc.Wallet, netParams,
×
1749
                                )().Unpack()
×
1750
                                if err != nil {
×
1751
                                        return nil, err
×
1752
                                }
×
1753

1754
                                return addr.DeliveryAddress, nil
×
1755
                        },
1756
                        SecretKeyRing:      s.cc.KeyRing,
1757
                        Dial:               cfg.net.Dial,
1758
                        AuthDial:           authDial,
1759
                        DB:                 dbs.TowerClientDB,
1760
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1761
                        MinBackoff:         10 * time.Second,
1762
                        MaxBackoff:         5 * time.Minute,
1763
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1764
                }, policy, anchorPolicy, taprootPolicy)
1765
                if err != nil {
×
1766
                        return nil, err
×
1767
                }
×
1768
        }
1769

1770
        if len(cfg.ExternalHosts) != 0 {
×
1771
                advertisedIPs := make(map[string]struct{})
×
1772
                for _, addr := range s.currentNodeAnn.Addresses {
×
1773
                        advertisedIPs[addr.String()] = struct{}{}
×
1774
                }
×
1775

1776
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1777
                        Hosts:         cfg.ExternalHosts,
×
1778
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1779
                        LookupHost: func(host string) (net.Addr, error) {
×
1780
                                return lncfg.ParseAddressString(
×
1781
                                        host, strconv.Itoa(defaultPeerPort),
×
1782
                                        cfg.net.ResolveTCPAddr,
×
1783
                                )
×
1784
                        },
×
1785
                        AdvertisedIPs: advertisedIPs,
1786
                        AnnounceNewIPs: netann.IPAnnouncer(
1787
                                func(modifier ...netann.NodeAnnModifier) (
1788
                                        lnwire.NodeAnnouncement1, error) {
×
1789

×
1790
                                        return s.genNodeAnnouncement(
×
1791
                                                nil, modifier...,
×
1792
                                        )
×
1793
                                }),
×
1794
                })
1795
        }
1796

1797
        // Create liveness monitor.
1798
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1799

×
1800
        listeners := make([]net.Listener, len(listenAddrs))
×
1801
        for i, listenAddr := range listenAddrs {
×
1802
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
1803
                // doesn't need to call the general lndResolveTCP function
×
1804
                // since we are resolving a local address.
×
1805

×
1806
                // RESOLVE: We are actually partially accepting inbound
×
1807
                // connection requests when we call NewListener.
×
1808
                listeners[i], err = brontide.NewListener(
×
1809
                        nodeKeyECDH, listenAddr.String(),
×
1810
                        // TODO(yy): remove this check and unify the inbound
×
1811
                        // connection check inside `InboundPeerConnected`.
×
1812
                        s.peerAccessMan.checkAcceptIncomingConn,
×
1813
                )
×
1814
                if err != nil {
×
1815
                        return nil, err
×
1816
                }
×
1817
        }
1818

1819
        // Create the connection manager which will be responsible for
1820
        // maintaining persistent outbound connections and also accepting new
1821
        // incoming connections
1822
        cmgr, err := connmgr.New(&connmgr.Config{
×
1823
                Listeners:      listeners,
×
1824
                OnAccept:       s.InboundPeerConnected,
×
1825
                RetryDuration:  time.Second * 5,
×
1826
                TargetOutbound: 100,
×
1827
                Dial: noiseDial(
×
1828
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
1829
                ),
×
1830
                OnConnection: s.OutboundPeerConnected,
×
1831
        })
×
1832
        if err != nil {
×
1833
                return nil, err
×
1834
        }
×
1835
        s.connMgr = cmgr
×
1836

×
1837
        // Finally, register the subsystems in blockbeat.
×
1838
        s.registerBlockConsumers()
×
1839

×
1840
        return s, nil
×
1841
}
1842

1843
// UpdateRoutingConfig is a callback function to update the routing config
1844
// values in the main cfg.
1845
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1846
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
1847

×
1848
        switch c := cfg.Estimator.Config().(type) {
×
1849
        case routing.AprioriConfig:
×
1850
                routerCfg.ProbabilityEstimatorType =
×
1851
                        routing.AprioriEstimatorName
×
1852

×
1853
                targetCfg := routerCfg.AprioriConfig
×
1854
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
1855
                targetCfg.Weight = c.AprioriWeight
×
1856
                targetCfg.CapacityFraction = c.CapacityFraction
×
1857
                targetCfg.HopProbability = c.AprioriHopProbability
×
1858

1859
        case routing.BimodalConfig:
×
1860
                routerCfg.ProbabilityEstimatorType =
×
1861
                        routing.BimodalEstimatorName
×
1862

×
1863
                targetCfg := routerCfg.BimodalConfig
×
1864
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
1865
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
1866
                targetCfg.DecayTime = c.BimodalDecayTime
×
1867
        }
1868

1869
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1870
}
1871

1872
// registerBlockConsumers registers the subsystems that consume block events.
1873
// By calling `RegisterQueue`, a list of subsystems are registered in the
1874
// blockbeat for block notifications. When a new block arrives, the subsystems
1875
// in the same queue are notified sequentially, and different queues are
1876
// notified concurrently.
1877
//
1878
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1879
// a new `RegisterQueue` call.
1880
func (s *server) registerBlockConsumers() {
×
1881
        // In this queue, when a new block arrives, it will be received and
×
1882
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
1883
        consumers := []chainio.Consumer{
×
1884
                s.chainArb,
×
1885
                s.sweeper,
×
1886
                s.txPublisher,
×
1887
        }
×
1888
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
1889
}
×
1890

1891
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1892
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1893
// may differ from what is on disk.
1894
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1895
        error) {
×
1896

×
1897
        data, err := u.DataToSign()
×
1898
        if err != nil {
×
1899
                return nil, err
×
1900
        }
×
1901

1902
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1903
}
1904

1905
// createLivenessMonitor creates a set of health checks using our configured
1906
// values and uses these checks to create a liveness monitor. Available
1907
// health checks,
1908
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1909
//   - diskCheck
1910
//   - tlsHealthCheck
1911
//   - torController, only created when tor is enabled.
1912
//
1913
// If a health check has been disabled by setting attempts to 0, our monitor
1914
// will not run it.
1915
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1916
        leaderElector cluster.LeaderElector) {
×
1917

×
1918
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
1919
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1920
                srvrLog.Info("Disabling chain backend checks for " +
×
1921
                        "nochainbackend mode")
×
1922

×
1923
                chainBackendAttempts = 0
×
1924
        }
×
1925

1926
        chainHealthCheck := healthcheck.NewObservation(
×
1927
                "chain backend",
×
1928
                cc.HealthCheck,
×
1929
                cfg.HealthChecks.ChainCheck.Interval,
×
1930
                cfg.HealthChecks.ChainCheck.Timeout,
×
1931
                cfg.HealthChecks.ChainCheck.Backoff,
×
1932
                chainBackendAttempts,
×
1933
        )
×
1934

×
1935
        diskCheck := healthcheck.NewObservation(
×
1936
                "disk space",
×
1937
                func() error {
×
1938
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1939
                                cfg.LndDir,
×
1940
                        )
×
1941
                        if err != nil {
×
1942
                                return err
×
1943
                        }
×
1944

1945
                        // If we have more free space than we require,
1946
                        // we return a nil error.
1947
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1948
                                return nil
×
1949
                        }
×
1950

1951
                        return fmt.Errorf("require: %v free space, got: %v",
×
1952
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1953
                                free)
×
1954
                },
1955
                cfg.HealthChecks.DiskCheck.Interval,
1956
                cfg.HealthChecks.DiskCheck.Timeout,
1957
                cfg.HealthChecks.DiskCheck.Backoff,
1958
                cfg.HealthChecks.DiskCheck.Attempts,
1959
        )
1960

1961
        tlsHealthCheck := healthcheck.NewObservation(
×
1962
                "tls",
×
1963
                func() error {
×
1964
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1965
                                s.cc.KeyRing,
×
1966
                        )
×
1967
                        if err != nil {
×
1968
                                return err
×
1969
                        }
×
1970
                        if expired {
×
1971
                                return fmt.Errorf("TLS certificate is "+
×
1972
                                        "expired as of %v", expTime)
×
1973
                        }
×
1974

1975
                        // If the certificate is not outdated, no error needs
1976
                        // to be returned
1977
                        return nil
×
1978
                },
1979
                cfg.HealthChecks.TLSCheck.Interval,
1980
                cfg.HealthChecks.TLSCheck.Timeout,
1981
                cfg.HealthChecks.TLSCheck.Backoff,
1982
                cfg.HealthChecks.TLSCheck.Attempts,
1983
        )
1984

1985
        checks := []*healthcheck.Observation{
×
1986
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
1987
        }
×
1988

×
1989
        // If Tor is enabled, add the healthcheck for tor connection.
×
1990
        if s.torController != nil {
×
1991
                torConnectionCheck := healthcheck.NewObservation(
×
1992
                        "tor connection",
×
1993
                        func() error {
×
1994
                                return healthcheck.CheckTorServiceStatus(
×
1995
                                        s.torController,
×
1996
                                        func() error {
×
1997
                                                return s.createNewHiddenService(
×
1998
                                                        context.TODO(),
×
1999
                                                )
×
2000
                                        },
×
2001
                                )
2002
                        },
2003
                        cfg.HealthChecks.TorConnection.Interval,
2004
                        cfg.HealthChecks.TorConnection.Timeout,
2005
                        cfg.HealthChecks.TorConnection.Backoff,
2006
                        cfg.HealthChecks.TorConnection.Attempts,
2007
                )
2008
                checks = append(checks, torConnectionCheck)
×
2009
        }
2010

2011
        // If remote signing is enabled, add the healthcheck for the remote
2012
        // signing RPC interface.
2013
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
2014
                // Because we have two cascading timeouts here, we need to add
×
2015
                // some slack to the "outer" one of them in case the "inner"
×
2016
                // returns exactly on time.
×
2017
                overhead := time.Millisecond * 10
×
2018

×
2019
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2020
                        "remote signer connection",
×
2021
                        rpcwallet.HealthCheck(
×
2022
                                s.cfg.RemoteSigner,
×
2023

×
2024
                                // For the health check we might to be even
×
2025
                                // stricter than the initial/normal connect, so
×
2026
                                // we use the health check timeout here.
×
2027
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
2028
                        ),
×
2029
                        cfg.HealthChecks.RemoteSigner.Interval,
×
2030
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
2031
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
2032
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
2033
                )
×
2034
                checks = append(checks, remoteSignerConnectionCheck)
×
2035
        }
×
2036

2037
        // If we have a leader elector, we add a health check to ensure we are
2038
        // still the leader. During normal operation, we should always be the
2039
        // leader, but there are circumstances where this may change, such as
2040
        // when we lose network connectivity for long enough expiring out lease.
2041
        if leaderElector != nil {
×
2042
                leaderCheck := healthcheck.NewObservation(
×
2043
                        "leader status",
×
2044
                        func() error {
×
2045
                                // Check if we are still the leader. Note that
×
2046
                                // we don't need to use a timeout context here
×
2047
                                // as the healthcheck observer will handle the
×
2048
                                // timeout case for us.
×
2049
                                timeoutCtx, cancel := context.WithTimeout(
×
2050
                                        context.Background(),
×
2051
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2052
                                )
×
2053
                                defer cancel()
×
2054

×
2055
                                leader, err := leaderElector.IsLeader(
×
2056
                                        timeoutCtx,
×
2057
                                )
×
2058
                                if err != nil {
×
2059
                                        return fmt.Errorf("unable to check if "+
×
2060
                                                "still leader: %v", err)
×
2061
                                }
×
2062

2063
                                if !leader {
×
2064
                                        srvrLog.Debug("Not the current leader")
×
2065
                                        return fmt.Errorf("not the current " +
×
2066
                                                "leader")
×
2067
                                }
×
2068

2069
                                return nil
×
2070
                        },
2071
                        cfg.HealthChecks.LeaderCheck.Interval,
2072
                        cfg.HealthChecks.LeaderCheck.Timeout,
2073
                        cfg.HealthChecks.LeaderCheck.Backoff,
2074
                        cfg.HealthChecks.LeaderCheck.Attempts,
2075
                )
2076

2077
                checks = append(checks, leaderCheck)
×
2078
        }
2079

2080
        // If we have not disabled all of our health checks, we create a
2081
        // liveness monitor with our configured checks.
2082
        s.livenessMonitor = healthcheck.NewMonitor(
×
2083
                &healthcheck.Config{
×
2084
                        Checks:   checks,
×
2085
                        Shutdown: srvrLog.Criticalf,
×
2086
                },
×
2087
        )
×
2088
}
2089

2090
// Started returns true if the server has been started, and false otherwise.
2091
// NOTE: This function is safe for concurrent access.
2092
func (s *server) Started() bool {
×
2093
        return atomic.LoadInt32(&s.active) != 0
×
2094
}
×
2095

2096
// cleaner is used to aggregate "cleanup" functions during an operation that
2097
// starts several subsystems. In case one of the subsystem fails to start
2098
// and a proper resource cleanup is required, the "run" method achieves this
2099
// by running all these added "cleanup" functions.
2100
type cleaner []func() error
2101

2102
// add is used to add a cleanup function to be called when
2103
// the run function is executed.
2104
func (c cleaner) add(cleanup func() error) cleaner {
×
2105
        return append(c, cleanup)
×
2106
}
×
2107

2108
// run is used to run all the previousely added cleanup functions.
2109
func (c cleaner) run() {
×
2110
        for i := len(c) - 1; i >= 0; i-- {
×
2111
                if err := c[i](); err != nil {
×
2112
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2113
                }
×
2114
        }
2115
}
2116

2117
// Start starts the main daemon server, all requested listeners, and any helper
2118
// goroutines.
2119
// NOTE: This function is safe for concurrent access.
2120
//
2121
//nolint:funlen
2122
func (s *server) Start(ctx context.Context) error {
×
2123
        var startErr error
×
2124

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

×
2130
        s.start.Do(func() {
×
2131
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
2132
                if err := s.customMessageServer.Start(); err != nil {
×
2133
                        startErr = err
×
2134
                        return
×
2135
                }
×
2136

2137
                if s.hostAnn != nil {
×
2138
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2139
                        if err := s.hostAnn.Start(); err != nil {
×
2140
                                startErr = err
×
2141
                                return
×
2142
                        }
×
2143
                }
2144

2145
                if s.livenessMonitor != nil {
×
2146
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
2147
                        if err := s.livenessMonitor.Start(); err != nil {
×
2148
                                startErr = err
×
2149
                                return
×
2150
                        }
×
2151
                }
2152

2153
                // Start the notification server. This is used so channel
2154
                // management goroutines can be notified when a funding
2155
                // transaction reaches a sufficient number of confirmations, or
2156
                // when the input for the funding transaction is spent in an
2157
                // attempt at an uncooperative close by the counterparty.
2158
                cleanup = cleanup.add(s.sigPool.Stop)
×
2159
                if err := s.sigPool.Start(); err != nil {
×
2160
                        startErr = err
×
2161
                        return
×
2162
                }
×
2163

2164
                cleanup = cleanup.add(s.writePool.Stop)
×
2165
                if err := s.writePool.Start(); err != nil {
×
2166
                        startErr = err
×
2167
                        return
×
2168
                }
×
2169

2170
                cleanup = cleanup.add(s.readPool.Stop)
×
2171
                if err := s.readPool.Start(); err != nil {
×
2172
                        startErr = err
×
2173
                        return
×
2174
                }
×
2175

2176
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2177
                if err := s.cc.ChainNotifier.Start(); err != nil {
×
2178
                        startErr = err
×
2179
                        return
×
2180
                }
×
2181

2182
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
2183
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2184
                        startErr = err
×
2185
                        return
×
2186
                }
×
2187

2188
                cleanup = cleanup.add(s.channelNotifier.Stop)
×
2189
                if err := s.channelNotifier.Start(); err != nil {
×
2190
                        startErr = err
×
2191
                        return
×
2192
                }
×
2193

2194
                cleanup = cleanup.add(func() error {
×
2195
                        return s.peerNotifier.Stop()
×
2196
                })
×
2197
                if err := s.peerNotifier.Start(); err != nil {
×
2198
                        startErr = err
×
2199
                        return
×
2200
                }
×
2201

2202
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
2203
                if err := s.htlcNotifier.Start(); err != nil {
×
2204
                        startErr = err
×
2205
                        return
×
2206
                }
×
2207

2208
                if s.towerClientMgr != nil {
×
2209
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
2210
                        if err := s.towerClientMgr.Start(); err != nil {
×
2211
                                startErr = err
×
2212
                                return
×
2213
                        }
×
2214
                }
2215

2216
                beat, err := s.getStartingBeat()
×
2217
                if err != nil {
×
2218
                        startErr = err
×
2219
                        return
×
2220
                }
×
2221

2222
                cleanup = cleanup.add(s.txPublisher.Stop)
×
2223
                if err := s.txPublisher.Start(beat); err != nil {
×
2224
                        startErr = err
×
2225
                        return
×
2226
                }
×
2227

2228
                cleanup = cleanup.add(s.sweeper.Stop)
×
2229
                if err := s.sweeper.Start(beat); err != nil {
×
2230
                        startErr = err
×
2231
                        return
×
2232
                }
×
2233

2234
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
2235
                if err := s.utxoNursery.Start(); err != nil {
×
2236
                        startErr = err
×
2237
                        return
×
2238
                }
×
2239

2240
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
2241
                if err := s.breachArbitrator.Start(); err != nil {
×
2242
                        startErr = err
×
2243
                        return
×
2244
                }
×
2245

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

2252
                // htlcSwitch must be started before chainArb since the latter
2253
                // relies on htlcSwitch to deliver resolution message upon
2254
                // start.
2255
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2256
                if err := s.htlcSwitch.Start(); err != nil {
×
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

2261
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
2262
                if err := s.interceptableSwitch.Start(); err != nil {
×
2263
                        startErr = err
×
2264
                        return
×
2265
                }
×
2266

2267
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
×
2268
                if err := s.invoiceHtlcModifier.Start(); err != nil {
×
2269
                        startErr = err
×
2270
                        return
×
2271
                }
×
2272

2273
                cleanup = cleanup.add(s.chainArb.Stop)
×
2274
                if err := s.chainArb.Start(beat); err != nil {
×
2275
                        startErr = err
×
2276
                        return
×
2277
                }
×
2278

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

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

2291
                cleanup = cleanup.add(s.chanRouter.Stop)
×
2292
                if err := s.chanRouter.Start(); err != nil {
×
2293
                        startErr = err
×
2294
                        return
×
2295
                }
×
2296
                // The authGossiper depends on the chanRouter and therefore
2297
                // should be started after it.
2298
                cleanup = cleanup.add(s.authGossiper.Stop)
×
2299
                if err := s.authGossiper.Start(); err != nil {
×
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

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

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

2316
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
×
2317
                if err := s.chanStatusMgr.Start(); err != nil {
×
2318
                        startErr = err
×
2319
                        return
×
2320
                }
×
2321

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

2328
                cleanup.add(func() error {
×
2329
                        s.missionController.StopStoreTickers()
×
2330
                        return nil
×
2331
                })
×
2332
                s.missionController.RunStoreTickers()
×
2333

×
2334
                // Before we start the connMgr, we'll check to see if we have
×
2335
                // any backups to recover. We do this now as we want to ensure
×
2336
                // that have all the information we need to handle channel
×
2337
                // recovery _before_ we even accept connections from any peers.
×
2338
                chanRestorer := &chanDBRestorer{
×
2339
                        db:         s.chanStateDB,
×
2340
                        secretKeys: s.cc.KeyRing,
×
2341
                        chainArb:   s.chainArb,
×
2342
                }
×
2343
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2344
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2345
                                s.chansToRestore.PackedSingleChanBackups,
×
2346
                                s.cc.KeyRing, chanRestorer, s,
×
2347
                        )
×
2348
                        if err != nil {
×
2349
                                startErr = fmt.Errorf("unable to unpack single "+
×
2350
                                        "backups: %v", err)
×
2351
                                return
×
2352
                        }
×
2353
                }
2354
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
2355
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
2356
                                s.chansToRestore.PackedMultiChanBackup,
×
2357
                                s.cc.KeyRing, chanRestorer, s,
×
2358
                        )
×
2359
                        if err != nil {
×
2360
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2361
                                        "backup: %v", err)
×
2362
                                return
×
2363
                        }
×
2364
                }
2365

2366
                // chanSubSwapper must be started after the `channelNotifier`
2367
                // because it depends on channel events as a synchronization
2368
                // point.
2369
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
2370
                if err := s.chanSubSwapper.Start(); err != nil {
×
2371
                        startErr = err
×
2372
                        return
×
2373
                }
×
2374

2375
                if s.torController != nil {
×
2376
                        cleanup = cleanup.add(s.torController.Stop)
×
2377
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2378
                                startErr = err
×
2379
                                return
×
2380
                        }
×
2381
                }
2382

2383
                if s.natTraversal != nil {
×
2384
                        s.wg.Add(1)
×
2385
                        go s.watchExternalIP()
×
2386
                }
×
2387

2388
                // Start connmgr last to prevent connections before init.
2389
                cleanup = cleanup.add(func() error {
×
2390
                        s.connMgr.Stop()
×
2391
                        return nil
×
2392
                })
×
2393

2394
                // RESOLVE: s.connMgr.Start() is called here, but
2395
                // brontide.NewListener() is called in newServer. This means
2396
                // that we are actually listening and partially accepting
2397
                // inbound connections even before the connMgr starts.
2398
                //
2399
                // TODO(yy): move the log into the connMgr's `Start` method.
2400
                srvrLog.Info("connMgr starting...")
×
2401
                s.connMgr.Start()
×
2402
                srvrLog.Debug("connMgr started")
×
2403

×
2404
                // If peers are specified as a config option, we'll add those
×
2405
                // peers first.
×
2406
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
2407
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
2408
                                peerAddrCfg,
×
2409
                        )
×
2410
                        if err != nil {
×
2411
                                startErr = fmt.Errorf("unable to parse peer "+
×
2412
                                        "pubkey from config: %v", err)
×
2413
                                return
×
2414
                        }
×
2415
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
2416
                        if err != nil {
×
2417
                                startErr = fmt.Errorf("unable to parse peer "+
×
2418
                                        "address provided as a config option: "+
×
2419
                                        "%v", err)
×
2420
                                return
×
2421
                        }
×
2422

2423
                        peerAddr := &lnwire.NetAddress{
×
2424
                                IdentityKey: parsedPubkey,
×
2425
                                Address:     addr,
×
2426
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2427
                        }
×
2428

×
2429
                        err = s.ConnectToPeer(
×
2430
                                peerAddr, true,
×
2431
                                s.cfg.ConnectionTimeout,
×
2432
                        )
×
2433
                        if err != nil {
×
2434
                                startErr = fmt.Errorf("unable to connect to "+
×
2435
                                        "peer address provided as a config "+
×
2436
                                        "option: %v", err)
×
2437
                                return
×
2438
                        }
×
2439
                }
2440

2441
                // Subscribe to NodeAnnouncements that advertise new addresses
2442
                // our persistent peers.
2443
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2444
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2445
                                "addr: %v", err)
×
2446

×
2447
                        startErr = err
×
2448
                        return
×
2449
                }
×
2450

2451
                // With all the relevant sub-systems started, we'll now attempt
2452
                // to establish persistent connections to our direct channel
2453
                // collaborators within the network. Before doing so however,
2454
                // we'll prune our set of link nodes found within the database
2455
                // to ensure we don't reconnect to any nodes we no longer have
2456
                // open channels with.
2457
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2458
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2459

×
2460
                        startErr = err
×
2461
                        return
×
2462
                }
×
2463

2464
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2465
                        srvrLog.Errorf("Failed to establish persistent "+
×
2466
                                "connections: %v", err)
×
2467
                }
×
2468

2469
                // setSeedList is a helper function that turns multiple DNS seed
2470
                // server tuples from the command line or config file into the
2471
                // data structure we need and does a basic formal sanity check
2472
                // in the process.
2473
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2474
                        if len(tuples) == 0 {
×
2475
                                return
×
2476
                        }
×
2477

2478
                        result := make([][2]string, len(tuples))
×
2479
                        for idx, tuple := range tuples {
×
2480
                                tuple = strings.TrimSpace(tuple)
×
2481
                                if len(tuple) == 0 {
×
2482
                                        return
×
2483
                                }
×
2484

2485
                                servers := strings.Split(tuple, ",")
×
2486
                                if len(servers) > 2 || len(servers) == 0 {
×
2487
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2488
                                                "seed tuple: %v", servers)
×
2489
                                        return
×
2490
                                }
×
2491

2492
                                copy(result[idx][:], servers)
×
2493
                        }
2494

2495
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2496
                }
2497

2498
                // Let users overwrite the DNS seed nodes. We only allow them
2499
                // for bitcoin mainnet/testnet/signet.
2500
                if s.cfg.Bitcoin.MainNet {
×
2501
                        setSeedList(
×
2502
                                s.cfg.Bitcoin.DNSSeeds,
×
2503
                                chainreg.BitcoinMainnetGenesis,
×
2504
                        )
×
2505
                }
×
2506
                if s.cfg.Bitcoin.TestNet3 {
×
2507
                        setSeedList(
×
2508
                                s.cfg.Bitcoin.DNSSeeds,
×
2509
                                chainreg.BitcoinTestnetGenesis,
×
2510
                        )
×
2511
                }
×
2512
                if s.cfg.Bitcoin.TestNet4 {
×
2513
                        setSeedList(
×
2514
                                s.cfg.Bitcoin.DNSSeeds,
×
2515
                                chainreg.BitcoinTestnet4Genesis,
×
2516
                        )
×
2517
                }
×
2518
                if s.cfg.Bitcoin.SigNet {
×
2519
                        setSeedList(
×
2520
                                s.cfg.Bitcoin.DNSSeeds,
×
2521
                                chainreg.BitcoinSignetGenesis,
×
2522
                        )
×
2523
                }
×
2524

2525
                // If network bootstrapping hasn't been disabled, then we'll
2526
                // configure the set of active bootstrappers, and launch a
2527
                // dedicated goroutine to maintain a set of persistent
2528
                // connections.
2529
                if !s.cfg.NoNetBootstrap {
×
2530
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2531
                        if err != nil {
×
2532
                                startErr = err
×
2533
                                return
×
2534
                        }
×
2535

2536
                        s.wg.Add(1)
×
2537
                        go s.peerBootstrapper(
×
2538
                                ctx, defaultMinPeers, bootstrappers,
×
2539
                        )
×
2540
                } else {
×
2541
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2542
                }
×
2543

2544
                // Start the blockbeat after all other subsystems have been
2545
                // started so they are ready to receive new blocks.
2546
                cleanup = cleanup.add(func() error {
×
2547
                        s.blockbeatDispatcher.Stop()
×
2548
                        return nil
×
2549
                })
×
2550
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2551
                        startErr = err
×
2552
                        return
×
2553
                }
×
2554

2555
                // Set the active flag now that we've completed the full
2556
                // startup.
2557
                atomic.StoreInt32(&s.active, 1)
×
2558
        })
2559

2560
        if startErr != nil {
×
2561
                cleanup.run()
×
2562
        }
×
2563
        return startErr
×
2564
}
2565

2566
// Stop gracefully shutsdown the main daemon server. This function will signal
2567
// any active goroutines, or helper objects to exit, then blocks until they've
2568
// all successfully exited. Additionally, any/all listeners are closed.
2569
// NOTE: This function is safe for concurrent access.
2570
func (s *server) Stop() error {
×
2571
        s.stop.Do(func() {
×
2572
                atomic.StoreInt32(&s.stopping, 1)
×
2573

×
2574
                ctx := context.Background()
×
2575

×
2576
                close(s.quit)
×
2577

×
2578
                // Shutdown connMgr first to prevent conns during shutdown.
×
2579
                s.connMgr.Stop()
×
2580

×
2581
                // Stop dispatching blocks to other systems immediately.
×
2582
                s.blockbeatDispatcher.Stop()
×
2583

×
2584
                // Shutdown the wallet, funding manager, and the rpc server.
×
2585
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2586
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2587
                }
×
2588
                if err := s.htlcSwitch.Stop(); err != nil {
×
2589
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2590
                }
×
2591
                if err := s.sphinx.Stop(); err != nil {
×
2592
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2593
                }
×
2594
                if err := s.invoices.Stop(); err != nil {
×
2595
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2596
                }
×
2597
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2598
                        srvrLog.Warnf("failed to stop interceptable "+
×
2599
                                "switch: %v", err)
×
2600
                }
×
2601
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2602
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2603
                                "modifier: %v", err)
×
2604
                }
×
2605
                if err := s.chanRouter.Stop(); err != nil {
×
2606
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2607
                }
×
2608
                if err := s.graphBuilder.Stop(); err != nil {
×
2609
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2610
                }
×
2611
                if err := s.graphDB.Stop(); err != nil {
×
2612
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2613
                }
×
2614
                if err := s.chainArb.Stop(); err != nil {
×
2615
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2616
                }
×
2617
                if err := s.fundingMgr.Stop(); err != nil {
×
2618
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2619
                }
×
2620
                if err := s.breachArbitrator.Stop(); err != nil {
×
2621
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2622
                                err)
×
2623
                }
×
2624
                if err := s.utxoNursery.Stop(); err != nil {
×
2625
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2626
                }
×
2627
                if err := s.authGossiper.Stop(); err != nil {
×
2628
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2629
                }
×
2630
                if err := s.sweeper.Stop(); err != nil {
×
2631
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2632
                }
×
2633
                if err := s.txPublisher.Stop(); err != nil {
×
2634
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2635
                }
×
2636
                if err := s.channelNotifier.Stop(); err != nil {
×
2637
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2638
                }
×
2639
                if err := s.peerNotifier.Stop(); err != nil {
×
2640
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2641
                }
×
2642
                if err := s.htlcNotifier.Stop(); err != nil {
×
2643
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2644
                }
×
2645

2646
                // Update channel.backup file. Make sure to do it before
2647
                // stopping chanSubSwapper.
2648
                singles, err := chanbackup.FetchStaticChanBackups(
×
2649
                        ctx, s.chanStateDB, s.addrSource,
×
2650
                )
×
2651
                if err != nil {
×
2652
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2653
                                err)
×
2654
                } else {
×
2655
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
2656
                        if err != nil {
×
2657
                                srvrLog.Warnf("Manual update of channel "+
×
2658
                                        "backup failed: %v", err)
×
2659
                        }
×
2660
                }
2661

2662
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2663
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2664
                }
×
2665
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2666
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2667
                }
×
2668
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2669
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2670
                                err)
×
2671
                }
×
2672
                if err := s.chanEventStore.Stop(); err != nil {
×
2673
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2674
                                err)
×
2675
                }
×
2676
                s.missionController.StopStoreTickers()
×
2677

×
2678
                // Disconnect from each active peers to ensure that
×
2679
                // peerTerminationWatchers signal completion to each peer.
×
2680
                for _, peer := range s.Peers() {
×
2681
                        err := s.DisconnectPeer(peer.IdentityKey())
×
2682
                        if err != nil {
×
2683
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2684
                                        "received error: %v", peer.IdentityKey(),
×
2685
                                        err,
×
2686
                                )
×
2687
                        }
×
2688
                }
2689

2690
                // Now that all connections have been torn down, stop the tower
2691
                // client which will reliably flush all queued states to the
2692
                // tower. If this is halted for any reason, the force quit timer
2693
                // will kick in and abort to allow this method to return.
2694
                if s.towerClientMgr != nil {
×
2695
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2696
                                srvrLog.Warnf("Unable to shut down tower "+
×
2697
                                        "client manager: %v", err)
×
2698
                        }
×
2699
                }
2700

2701
                if s.hostAnn != nil {
×
2702
                        if err := s.hostAnn.Stop(); err != nil {
×
2703
                                srvrLog.Warnf("unable to shut down host "+
×
2704
                                        "annoucner: %v", err)
×
2705
                        }
×
2706
                }
2707

2708
                if s.livenessMonitor != nil {
×
2709
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2710
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2711
                                        "monitor: %v", err)
×
2712
                        }
×
2713
                }
2714

2715
                // Wait for all lingering goroutines to quit.
2716
                srvrLog.Debug("Waiting for server to shutdown...")
×
2717
                s.wg.Wait()
×
2718

×
2719
                srvrLog.Debug("Stopping buffer pools...")
×
2720
                s.sigPool.Stop()
×
2721
                s.writePool.Stop()
×
2722
                s.readPool.Stop()
×
2723
        })
2724

2725
        return nil
×
2726
}
2727

2728
// Stopped returns true if the server has been instructed to shutdown.
2729
// NOTE: This function is safe for concurrent access.
2730
func (s *server) Stopped() bool {
×
2731
        return atomic.LoadInt32(&s.stopping) != 0
×
2732
}
×
2733

2734
// configurePortForwarding attempts to set up port forwarding for the different
2735
// ports that the server will be listening on.
2736
//
2737
// NOTE: This should only be used when using some kind of NAT traversal to
2738
// automatically set up forwarding rules.
2739
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2740
        ip, err := s.natTraversal.ExternalIP()
×
2741
        if err != nil {
×
2742
                return nil, err
×
2743
        }
×
2744
        s.lastDetectedIP = ip
×
2745

×
2746
        externalIPs := make([]string, 0, len(ports))
×
2747
        for _, port := range ports {
×
2748
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2749
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2750
                        continue
×
2751
                }
2752

2753
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2754
                externalIPs = append(externalIPs, hostIP)
×
2755
        }
2756

2757
        return externalIPs, nil
×
2758
}
2759

2760
// removePortForwarding attempts to clear the forwarding rules for the different
2761
// ports the server is currently listening on.
2762
//
2763
// NOTE: This should only be used when using some kind of NAT traversal to
2764
// automatically set up forwarding rules.
2765
func (s *server) removePortForwarding() {
×
2766
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2767
        for _, port := range forwardedPorts {
×
2768
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2769
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2770
                                "port %d: %v", port, err)
×
2771
                }
×
2772
        }
2773
}
2774

2775
// watchExternalIP continuously checks for an updated external IP address every
2776
// 15 minutes. Once a new IP address has been detected, it will automatically
2777
// handle port forwarding rules and send updated node announcements to the
2778
// currently connected peers.
2779
//
2780
// NOTE: This MUST be run as a goroutine.
2781
func (s *server) watchExternalIP() {
×
2782
        defer s.wg.Done()
×
2783

×
2784
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2785
        // up by the server.
×
2786
        defer s.removePortForwarding()
×
2787

×
2788
        // Keep track of the external IPs set by the user to avoid replacing
×
2789
        // them when detecting a new IP.
×
2790
        ipsSetByUser := make(map[string]struct{})
×
2791
        for _, ip := range s.cfg.ExternalIPs {
×
2792
                ipsSetByUser[ip.String()] = struct{}{}
×
2793
        }
×
2794

2795
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2796

×
2797
        ticker := time.NewTicker(15 * time.Minute)
×
2798
        defer ticker.Stop()
×
2799
out:
×
2800
        for {
×
2801
                select {
×
2802
                case <-ticker.C:
×
2803
                        // We'll start off by making sure a new IP address has
×
2804
                        // been detected.
×
2805
                        ip, err := s.natTraversal.ExternalIP()
×
2806
                        if err != nil {
×
2807
                                srvrLog.Debugf("Unable to retrieve the "+
×
2808
                                        "external IP address: %v", err)
×
2809
                                continue
×
2810
                        }
2811

2812
                        // Periodically renew the NAT port forwarding.
2813
                        for _, port := range forwardedPorts {
×
2814
                                err := s.natTraversal.AddPortMapping(port)
×
2815
                                if err != nil {
×
2816
                                        srvrLog.Warnf("Unable to automatically "+
×
2817
                                                "re-create port forwarding using %s: %v",
×
2818
                                                s.natTraversal.Name(), err)
×
2819
                                } else {
×
2820
                                        srvrLog.Debugf("Automatically re-created "+
×
2821
                                                "forwarding for port %d using %s to "+
×
2822
                                                "advertise external IP",
×
2823
                                                port, s.natTraversal.Name())
×
2824
                                }
×
2825
                        }
2826

2827
                        if ip.Equal(s.lastDetectedIP) {
×
2828
                                continue
×
2829
                        }
2830

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

×
2833
                        // Next, we'll craft the new addresses that will be
×
2834
                        // included in the new node announcement and advertised
×
2835
                        // to the network. Each address will consist of the new
×
2836
                        // IP detected and one of the currently advertised
×
2837
                        // ports.
×
2838
                        var newAddrs []net.Addr
×
2839
                        for _, port := range forwardedPorts {
×
2840
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2841
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2842
                                if err != nil {
×
2843
                                        srvrLog.Debugf("Unable to resolve "+
×
2844
                                                "host %v: %v", addr, err)
×
2845
                                        continue
×
2846
                                }
2847

2848
                                newAddrs = append(newAddrs, addr)
×
2849
                        }
2850

2851
                        // Skip the update if we weren't able to resolve any of
2852
                        // the new addresses.
2853
                        if len(newAddrs) == 0 {
×
2854
                                srvrLog.Debug("Skipping node announcement " +
×
2855
                                        "update due to not being able to " +
×
2856
                                        "resolve any new addresses")
×
2857
                                continue
×
2858
                        }
2859

2860
                        // Now, we'll need to update the addresses in our node's
2861
                        // announcement in order to propagate the update
2862
                        // throughout the network. We'll only include addresses
2863
                        // that have a different IP from the previous one, as
2864
                        // the previous IP is no longer valid.
2865
                        currentNodeAnn := s.getNodeAnnouncement()
×
2866

×
2867
                        for _, addr := range currentNodeAnn.Addresses {
×
2868
                                host, _, err := net.SplitHostPort(addr.String())
×
2869
                                if err != nil {
×
2870
                                        srvrLog.Debugf("Unable to determine "+
×
2871
                                                "host from address %v: %v",
×
2872
                                                addr, err)
×
2873
                                        continue
×
2874
                                }
2875

2876
                                // We'll also make sure to include external IPs
2877
                                // set manually by the user.
2878
                                _, setByUser := ipsSetByUser[addr.String()]
×
2879
                                if setByUser || host != s.lastDetectedIP.String() {
×
2880
                                        newAddrs = append(newAddrs, addr)
×
2881
                                }
×
2882
                        }
2883

2884
                        // Then, we'll generate a new timestamped node
2885
                        // announcement with the updated addresses and broadcast
2886
                        // it to our peers.
2887
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2888
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2889
                        )
×
2890
                        if err != nil {
×
2891
                                srvrLog.Debugf("Unable to generate new node "+
×
2892
                                        "announcement: %v", err)
×
2893
                                continue
×
2894
                        }
2895

2896
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2897
                        if err != nil {
×
2898
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2899
                                        "announcement to peers: %v", err)
×
2900
                                continue
×
2901
                        }
2902

2903
                        // Finally, update the last IP seen to the current one.
2904
                        s.lastDetectedIP = ip
×
2905
                case <-s.quit:
×
2906
                        break out
×
2907
                }
2908
        }
2909
}
2910

2911
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2912
// based on the server, and currently active bootstrap mechanisms as defined
2913
// within the current configuration.
2914
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2915
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2916

×
2917
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2918

×
2919
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2920
        // this can be used by default if we've already partially seeded the
×
2921
        // network.
×
2922
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2923
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
×
2924
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
×
2925
        )
×
2926
        if err != nil {
×
2927
                return nil, err
×
2928
        }
×
2929
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2930

×
2931
        // If this isn't using simnet or regtest mode, then one of our
×
2932
        // additional bootstrapping sources will be the set of running DNS
×
2933
        // seeds.
×
2934
        if !s.cfg.Bitcoin.IsLocalNetwork() {
×
2935
                //nolint:ll
×
2936
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2937

×
2938
                // If we have a set of DNS seeds for this chain, then we'll add
×
2939
                // it as an additional bootstrapping source.
×
2940
                if ok {
×
2941
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2942
                                "seeds: %v", dnsSeeds)
×
2943

×
2944
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2945
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2946
                        )
×
2947
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2948
                }
×
2949
        }
2950

2951
        return bootStrappers, nil
×
2952
}
2953

2954
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2955
// needs to ignore, which is made of three parts,
2956
//   - the node itself needs to be skipped as it doesn't make sense to connect
2957
//     to itself.
2958
//   - the peers that already have connections with, as in s.peersByPub.
2959
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2960
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2961
        s.mu.RLock()
×
2962
        defer s.mu.RUnlock()
×
2963

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

×
2966
        // We should ignore ourselves from bootstrapping.
×
2967
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2968
        ignore[selfKey] = struct{}{}
×
2969

×
2970
        // Ignore all connected peers.
×
2971
        for _, peer := range s.peersByPub {
×
2972
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2973
                ignore[nID] = struct{}{}
×
2974
        }
×
2975

2976
        // Ignore all persistent peers as they have a dedicated reconnecting
2977
        // process.
2978
        for pubKeyStr := range s.persistentPeers {
×
2979
                var nID autopilot.NodeID
×
2980
                copy(nID[:], []byte(pubKeyStr))
×
2981
                ignore[nID] = struct{}{}
×
2982
        }
×
2983

2984
        return ignore
×
2985
}
2986

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

×
2995
        defer s.wg.Done()
×
2996

×
2997
        // Before we continue, init the ignore peers map.
×
2998
        ignoreList := s.createBootstrapIgnorePeers()
×
2999

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

×
3004
        // Once done, we'll attempt to maintain our target minimum number of
×
3005
        // peers.
×
3006
        //
×
3007
        // We'll use a 15 second backoff, and double the time every time an
×
3008
        // epoch fails up to a ceiling.
×
3009
        backOff := time.Second * 15
×
3010

×
3011
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3012
        // see if we've reached our minimum number of peers.
×
3013
        sampleTicker := time.NewTicker(backOff)
×
3014
        defer sampleTicker.Stop()
×
3015

×
3016
        // We'll use the number of attempts and errors to determine if we need
×
3017
        // to increase the time between discovery epochs.
×
3018
        var epochErrors uint32 // To be used atomically.
×
3019
        var epochAttempts uint32
×
3020

×
3021
        for {
×
3022
                select {
×
3023
                // The ticker has just woken us up, so we'll need to check if
3024
                // we need to attempt to connect our to any more peers.
3025
                case <-sampleTicker.C:
×
3026
                        // Obtain the current number of peers, so we can gauge
×
3027
                        // if we need to sample more peers or not.
×
3028
                        s.mu.RLock()
×
3029
                        numActivePeers := uint32(len(s.peersByPub))
×
3030
                        s.mu.RUnlock()
×
3031

×
3032
                        // If we have enough peers, then we can loop back
×
3033
                        // around to the next round as we're done here.
×
3034
                        if numActivePeers >= numTargetPeers {
×
3035
                                continue
×
3036
                        }
3037

3038
                        // If all of our attempts failed during this last back
3039
                        // off period, then will increase our backoff to 5
3040
                        // minute ceiling to avoid an excessive number of
3041
                        // queries
3042
                        //
3043
                        // TODO(roasbeef): add reverse policy too?
3044

3045
                        if epochAttempts > 0 &&
×
3046
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3047

×
3048
                                sampleTicker.Stop()
×
3049

×
3050
                                backOff *= 2
×
3051
                                if backOff > bootstrapBackOffCeiling {
×
3052
                                        backOff = bootstrapBackOffCeiling
×
3053
                                }
×
3054

3055
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3056
                                        "%v", backOff)
×
3057
                                sampleTicker = time.NewTicker(backOff)
×
3058
                                continue
×
3059
                        }
3060

3061
                        atomic.StoreUint32(&epochErrors, 0)
×
3062
                        epochAttempts = 0
×
3063

×
3064
                        // Since we know need more peers, we'll compute the
×
3065
                        // exact number we need to reach our threshold.
×
3066
                        numNeeded := numTargetPeers - numActivePeers
×
3067

×
3068
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3069
                                "peers", numNeeded)
×
3070

×
3071
                        // With the number of peers we need calculated, we'll
×
3072
                        // query the network bootstrappers to sample a set of
×
3073
                        // random addrs for us.
×
3074
                        //
×
3075
                        // Before we continue, get a copy of the ignore peers
×
3076
                        // map.
×
3077
                        ignoreList = s.createBootstrapIgnorePeers()
×
3078

×
3079
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3080
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3081
                        )
×
3082
                        if err != nil {
×
3083
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3084
                                        "peers: %v", err)
×
3085
                                continue
×
3086
                        }
3087

3088
                        // Finally, we'll launch a new goroutine for each
3089
                        // prospective peer candidates.
3090
                        for _, addr := range peerAddrs {
×
3091
                                epochAttempts++
×
3092

×
3093
                                go func(a *lnwire.NetAddress) {
×
3094
                                        // TODO(roasbeef): can do AS, subnet,
×
3095
                                        // country diversity, etc
×
3096
                                        errChan := make(chan error, 1)
×
3097
                                        s.connectToPeer(
×
3098
                                                a, errChan,
×
3099
                                                s.cfg.ConnectionTimeout,
×
3100
                                        )
×
3101
                                        select {
×
3102
                                        case err := <-errChan:
×
3103
                                                if err == nil {
×
3104
                                                        return
×
3105
                                                }
×
3106

3107
                                                srvrLog.Errorf("Unable to "+
×
3108
                                                        "connect to %v: %v",
×
3109
                                                        a, err)
×
3110
                                                atomic.AddUint32(&epochErrors, 1)
×
3111
                                        case <-s.quit:
×
3112
                                        }
3113
                                }(addr)
3114
                        }
3115
                case <-s.quit:
×
3116
                        return
×
3117
                }
3118
        }
3119
}
3120

3121
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3122
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3123
// query back off each time we encounter a failure.
3124
const bootstrapBackOffCeiling = time.Minute * 5
3125

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

×
3133
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3134
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3135

×
3136
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3137
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3138
        var delaySignal <-chan time.Time
×
3139
        delayTime := time.Second * 2
×
3140

×
3141
        // As want to be more aggressive, we'll use a lower back off celling
×
3142
        // then the main peer bootstrap logic.
×
3143
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3144

×
3145
        for attempts := 0; ; attempts++ {
×
3146
                // Check if the server has been requested to shut down in order
×
3147
                // to prevent blocking.
×
3148
                if s.Stopped() {
×
3149
                        return
×
3150
                }
×
3151

3152
                // We can exit our aggressive initial peer bootstrapping stage
3153
                // if we've reached out target number of peers.
3154
                s.mu.RLock()
×
3155
                numActivePeers := uint32(len(s.peersByPub))
×
3156
                s.mu.RUnlock()
×
3157

×
3158
                if numActivePeers >= numTargetPeers {
×
3159
                        return
×
3160
                }
×
3161

3162
                if attempts > 0 {
×
3163
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3164
                                "bootstrap peers (attempt #%v)", delayTime,
×
3165
                                attempts)
×
3166

×
3167
                        // We've completed at least one iterating and haven't
×
3168
                        // finished, so we'll start to insert a delay period
×
3169
                        // between each attempt.
×
3170
                        delaySignal = time.After(delayTime)
×
3171
                        select {
×
3172
                        case <-delaySignal:
×
3173
                        case <-s.quit:
×
3174
                                return
×
3175
                        }
3176

3177
                        // After our delay, we'll double the time we wait up to
3178
                        // the max back off period.
3179
                        delayTime *= 2
×
3180
                        if delayTime > backOffCeiling {
×
3181
                                delayTime = backOffCeiling
×
3182
                        }
×
3183
                }
3184

3185
                // Otherwise, we'll request for the remaining number of peers
3186
                // in order to reach our target.
3187
                peersNeeded := numTargetPeers - numActivePeers
×
3188
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3189
                        ctx, ignore, peersNeeded, bootstrappers...,
×
3190
                )
×
3191
                if err != nil {
×
3192
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3193
                                "peers: %v", err)
×
3194
                        continue
×
3195
                }
3196

3197
                // Then, we'll attempt to establish a connection to the
3198
                // different peer addresses retrieved by our bootstrappers.
3199
                var wg sync.WaitGroup
×
3200
                for _, bootstrapAddr := range bootstrapAddrs {
×
3201
                        wg.Add(1)
×
3202
                        go func(addr *lnwire.NetAddress) {
×
3203
                                defer wg.Done()
×
3204

×
3205
                                errChan := make(chan error, 1)
×
3206
                                go s.connectToPeer(
×
3207
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3208
                                )
×
3209

×
3210
                                // We'll only allow this connection attempt to
×
3211
                                // take up to 3 seconds. This allows us to move
×
3212
                                // quickly by discarding peers that are slowing
×
3213
                                // us down.
×
3214
                                select {
×
3215
                                case err := <-errChan:
×
3216
                                        if err == nil {
×
3217
                                                return
×
3218
                                        }
×
3219
                                        srvrLog.Errorf("Unable to connect to "+
×
3220
                                                "%v: %v", addr, err)
×
3221
                                // TODO: tune timeout? 3 seconds might be *too*
3222
                                // aggressive but works well.
3223
                                case <-time.After(3 * time.Second):
×
3224
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3225
                                                "to not establishing a "+
×
3226
                                                "connection within 3 seconds",
×
3227
                                                addr)
×
3228
                                case <-s.quit:
×
3229
                                }
3230
                        }(bootstrapAddr)
3231
                }
3232

3233
                wg.Wait()
×
3234
        }
3235
}
3236

3237
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3238
// order to listen for inbound connections over Tor.
3239
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3240
        // Determine the different ports the server is listening on. The onion
×
3241
        // service's virtual port will map to these ports and one will be picked
×
3242
        // at random when the onion service is being accessed.
×
3243
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3244
        for _, listenAddr := range s.listenAddrs {
×
3245
                port := listenAddr.(*net.TCPAddr).Port
×
3246
                listenPorts = append(listenPorts, port)
×
3247
        }
×
3248

3249
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3250
        if err != nil {
×
3251
                return err
×
3252
        }
×
3253

3254
        // Once the port mapping has been set, we can go ahead and automatically
3255
        // create our onion service. The service's private key will be saved to
3256
        // disk in order to regain access to this service when restarting `lnd`.
3257
        onionCfg := tor.AddOnionConfig{
×
3258
                VirtualPort: defaultPeerPort,
×
3259
                TargetPorts: listenPorts,
×
3260
                Store: tor.NewOnionFile(
×
3261
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3262
                        encrypter,
×
3263
                ),
×
3264
        }
×
3265

×
3266
        switch {
×
3267
        case s.cfg.Tor.V2:
×
3268
                onionCfg.Type = tor.V2
×
3269
        case s.cfg.Tor.V3:
×
3270
                onionCfg.Type = tor.V3
×
3271
        }
3272

3273
        addr, err := s.torController.AddOnion(onionCfg)
×
3274
        if err != nil {
×
3275
                return err
×
3276
        }
×
3277

3278
        // Now that the onion service has been created, we'll add the onion
3279
        // address it can be reached at to our list of advertised addresses.
3280
        newNodeAnn, err := s.genNodeAnnouncement(
×
3281
                nil, func(currentAnn *lnwire.NodeAnnouncement1) {
×
3282
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3283
                },
×
3284
        )
3285
        if err != nil {
×
3286
                return fmt.Errorf("unable to generate new node "+
×
3287
                        "announcement: %v", err)
×
3288
        }
×
3289

3290
        // Finally, we'll update the on-disk version of our announcement so it
3291
        // will eventually propagate to nodes in the network.
3292
        selfNode := &models.Node{
×
3293
                HaveNodeAnnouncement: true,
×
3294
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3295
                Addresses:            newNodeAnn.Addresses,
×
3296
                Alias:                newNodeAnn.Alias.String(),
×
3297
                Features: lnwire.NewFeatureVector(
×
3298
                        newNodeAnn.Features, lnwire.Features,
×
3299
                ),
×
3300
                Color:        newNodeAnn.RGBColor,
×
3301
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3302
        }
×
3303
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3304
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3305
                return fmt.Errorf("can't set self node: %w", err)
×
3306
        }
×
3307

3308
        return nil
×
3309
}
3310

3311
// findChannel finds a channel given a public key and ChannelID. It is an
3312
// optimization that is quicker than seeking for a channel given only the
3313
// ChannelID.
3314
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3315
        *channeldb.OpenChannel, error) {
×
3316

×
3317
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3318
        if err != nil {
×
3319
                return nil, err
×
3320
        }
×
3321

3322
        for _, channel := range nodeChans {
×
3323
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3324
                        return channel, nil
×
3325
                }
×
3326
        }
3327

3328
        return nil, fmt.Errorf("unable to find channel")
×
3329
}
3330

3331
// getNodeAnnouncement fetches the current, fully signed node announcement.
3332
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
×
3333
        s.mu.Lock()
×
3334
        defer s.mu.Unlock()
×
3335

×
3336
        return *s.currentNodeAnn
×
3337
}
×
3338

3339
// genNodeAnnouncement generates and returns the current fully signed node
3340
// announcement. The time stamp of the announcement will be updated in order
3341
// to ensure it propagates through the network.
3342
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3343
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
×
3344

×
3345
        s.mu.Lock()
×
3346
        defer s.mu.Unlock()
×
3347

×
3348
        // Create a shallow copy of the current node announcement to work on.
×
3349
        // This ensures the original announcement remains unchanged
×
3350
        // until the new announcement is fully signed and valid.
×
3351
        newNodeAnn := *s.currentNodeAnn
×
3352

×
3353
        // First, try to update our feature manager with the updated set of
×
3354
        // features.
×
3355
        if features != nil {
×
3356
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
3357
                        feature.SetNodeAnn: features,
×
3358
                }
×
3359
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
3360
                if err != nil {
×
3361
                        return lnwire.NodeAnnouncement1{}, err
×
3362
                }
×
3363

3364
                // If we could successfully update our feature manager, add
3365
                // an update modifier to include these new features to our
3366
                // set.
3367
                modifiers = append(
×
3368
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3369
                )
×
3370
        }
3371

3372
        // Always update the timestamp when refreshing to ensure the update
3373
        // propagates.
3374
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3375

×
3376
        // Apply the requested changes to the node announcement.
×
3377
        for _, modifier := range modifiers {
×
3378
                modifier(&newNodeAnn)
×
3379
        }
×
3380

3381
        // Sign a new update after applying all of the passed modifiers.
3382
        err := netann.SignNodeAnnouncement(
×
3383
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
3384
        )
×
3385
        if err != nil {
×
3386
                return lnwire.NodeAnnouncement1{}, err
×
3387
        }
×
3388

3389
        // If signing succeeds, update the current announcement.
3390
        *s.currentNodeAnn = newNodeAnn
×
3391

×
3392
        return *s.currentNodeAnn, nil
×
3393
}
3394

3395
// updateAndBroadcastSelfNode generates a new node announcement
3396
// applying the giving modifiers and updating the time stamp
3397
// to ensure it propagates through the network. Then it broadcasts
3398
// it to the network.
3399
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3400
        features *lnwire.RawFeatureVector,
3401
        modifiers ...netann.NodeAnnModifier) error {
×
3402

×
3403
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
3404
        if err != nil {
×
3405
                return fmt.Errorf("unable to generate new node "+
×
3406
                        "announcement: %v", err)
×
3407
        }
×
3408

3409
        // Update the on-disk version of our announcement.
3410
        // Load and modify self node istead of creating anew instance so we
3411
        // don't risk overwriting any existing values.
3412
        selfNode, err := s.graphDB.SourceNode(ctx)
×
3413
        if err != nil {
×
3414
                return fmt.Errorf("unable to get current source node: %w", err)
×
3415
        }
×
3416

3417
        selfNode.HaveNodeAnnouncement = true
×
3418
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
3419
        selfNode.Addresses = newNodeAnn.Addresses
×
3420
        selfNode.Alias = newNodeAnn.Alias.String()
×
3421
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
3422
        selfNode.Color = newNodeAnn.RGBColor
×
3423
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
3424

×
3425
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3426

×
3427
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3428
                return fmt.Errorf("can't set self node: %w", err)
×
3429
        }
×
3430

3431
        // Finally, propagate it to the nodes in the network.
3432
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3433
        if err != nil {
×
3434
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3435
                        "announcement to peers: %v", err)
×
3436
                return err
×
3437
        }
×
3438

3439
        return nil
×
3440
}
3441

3442
type nodeAddresses struct {
3443
        pubKey    *btcec.PublicKey
3444
        addresses []net.Addr
3445
}
3446

3447
// establishPersistentConnections attempts to establish persistent connections
3448
// to all our direct channel collaborators. In order to promote liveness of our
3449
// active channels, we instruct the connection manager to attempt to establish
3450
// and maintain persistent connections to all our direct channel counterparties.
3451
func (s *server) establishPersistentConnections(ctx context.Context) error {
×
3452
        // nodeAddrsMap stores the combination of node public keys and addresses
×
3453
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
3454
        // since other PubKey forms can't be compared.
×
3455
        nodeAddrsMap := make(map[string]*nodeAddresses)
×
3456

×
3457
        // Iterate through the list of LinkNodes to find addresses we should
×
3458
        // attempt to connect to based on our set of previous connections. Set
×
3459
        // the reconnection port to the default peer port.
×
3460
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
3461
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
×
3462
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3463
        }
×
3464

3465
        for _, node := range linkNodes {
×
3466
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
3467
                nodeAddrs := &nodeAddresses{
×
3468
                        pubKey:    node.IdentityPub,
×
3469
                        addresses: node.Addresses,
×
3470
                }
×
3471
                nodeAddrsMap[pubStr] = nodeAddrs
×
3472
        }
×
3473

3474
        // After checking our previous connections for addresses to connect to,
3475
        // iterate through the nodes in our channel graph to find addresses
3476
        // that have been added via NodeAnnouncement1 messages.
3477
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3478
        // each of the nodes.
3479
        graphAddrs := make(map[string]*nodeAddresses)
×
3480
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
×
3481
                havePolicy bool, channelPeer *models.Node) error {
×
3482

×
3483
                // If the remote party has announced the channel to us, but we
×
3484
                // haven't yet, then we won't have a policy. However, we don't
×
3485
                // need this to connect to the peer, so we'll log it and move on.
×
3486
                if !havePolicy {
×
3487
                        srvrLog.Warnf("No channel policy found for "+
×
3488
                                "ChannelPoint(%v): ", chanPoint)
×
3489
                }
×
3490

3491
                pubStr := string(channelPeer.PubKeyBytes[:])
×
3492

×
3493
                // Add all unique addresses from channel
×
3494
                // graph/NodeAnnouncements to the list of addresses we'll
×
3495
                // connect to for this peer.
×
3496
                addrSet := make(map[string]net.Addr)
×
3497
                for _, addr := range channelPeer.Addresses {
×
3498
                        switch addr.(type) {
×
3499
                        case *net.TCPAddr:
×
3500
                                addrSet[addr.String()] = addr
×
3501

3502
                        // We'll only attempt to connect to Tor addresses if Tor
3503
                        // outbound support is enabled.
3504
                        case *tor.OnionAddr:
×
3505
                                if s.cfg.Tor.Active {
×
3506
                                        addrSet[addr.String()] = addr
×
3507
                                }
×
3508
                        }
3509
                }
3510

3511
                // If this peer is also recorded as a link node, we'll add any
3512
                // additional addresses that have not already been selected.
3513
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
3514
                if ok {
×
3515
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
3516
                                switch lnAddress.(type) {
×
3517
                                case *net.TCPAddr:
×
3518
                                        addrSet[lnAddress.String()] = lnAddress
×
3519

3520
                                // We'll only attempt to connect to Tor
3521
                                // addresses if Tor outbound support is enabled.
3522
                                case *tor.OnionAddr:
×
3523
                                        if s.cfg.Tor.Active {
×
3524
                                                //nolint:ll
×
3525
                                                addrSet[lnAddress.String()] = lnAddress
×
3526
                                        }
×
3527
                                }
3528
                        }
3529
                }
3530

3531
                // Construct a slice of the deduped addresses.
3532
                var addrs []net.Addr
×
3533
                for _, addr := range addrSet {
×
3534
                        addrs = append(addrs, addr)
×
3535
                }
×
3536

3537
                n := &nodeAddresses{
×
3538
                        addresses: addrs,
×
3539
                }
×
3540
                n.pubKey, err = channelPeer.PubKey()
×
3541
                if err != nil {
×
3542
                        return err
×
3543
                }
×
3544

3545
                graphAddrs[pubStr] = n
×
3546
                return nil
×
3547
        }
3548
        err = s.graphDB.ForEachSourceNodeChannel(
×
3549
                ctx, forEachSrcNodeChan, func() {
×
3550
                        clear(graphAddrs)
×
3551
                },
×
3552
        )
3553
        if err != nil {
×
3554
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3555
                        "%v", err)
×
3556

×
3557
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3558
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3559

×
3560
                        return err
×
3561
                }
×
3562
        }
3563

3564
        // Combine the addresses from the link nodes and the channel graph.
3565
        for pubStr, nodeAddr := range graphAddrs {
×
3566
                nodeAddrsMap[pubStr] = nodeAddr
×
3567
        }
×
3568

3569
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3570
                len(nodeAddrsMap))
×
3571

×
3572
        // Acquire and hold server lock until all persistent connection requests
×
3573
        // have been recorded and sent to the connection manager.
×
3574
        s.mu.Lock()
×
3575
        defer s.mu.Unlock()
×
3576

×
3577
        // Iterate through the combined list of addresses from prior links and
×
3578
        // node announcements and attempt to reconnect to each node.
×
3579
        var numOutboundConns int
×
3580
        for pubStr, nodeAddr := range nodeAddrsMap {
×
3581
                // Add this peer to the set of peers we should maintain a
×
3582
                // persistent connection with. We set the value to false to
×
3583
                // indicate that we should not continue to reconnect if the
×
3584
                // number of channels returns to zero, since this peer has not
×
3585
                // been requested as perm by the user.
×
3586
                s.persistentPeers[pubStr] = false
×
3587
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
3588
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
3589
                }
×
3590

3591
                for _, address := range nodeAddr.addresses {
×
3592
                        // Create a wrapper address which couples the IP and
×
3593
                        // the pubkey so the brontide authenticated connection
×
3594
                        // can be established.
×
3595
                        lnAddr := &lnwire.NetAddress{
×
3596
                                IdentityKey: nodeAddr.pubKey,
×
3597
                                Address:     address,
×
3598
                        }
×
3599

×
3600
                        s.persistentPeerAddrs[pubStr] = append(
×
3601
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3602
                }
×
3603

3604
                // We'll connect to the first 10 peers immediately, then
3605
                // randomly stagger any remaining connections if the
3606
                // stagger initial reconnect flag is set. This ensures
3607
                // that mobile nodes or nodes with a small number of
3608
                // channels obtain connectivity quickly, but larger
3609
                // nodes are able to disperse the costs of connecting to
3610
                // all peers at once.
3611
                if numOutboundConns < numInstantInitReconnect ||
×
3612
                        !s.cfg.StaggerInitialReconnect {
×
3613

×
3614
                        go s.connectToPersistentPeer(pubStr)
×
3615
                } else {
×
3616
                        go s.delayInitialReconnect(pubStr)
×
3617
                }
×
3618

3619
                numOutboundConns++
×
3620
        }
3621

3622
        return nil
×
3623
}
3624

3625
// delayInitialReconnect will attempt a reconnection to the given peer after
3626
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3627
//
3628
// NOTE: This method MUST be run as a goroutine.
3629
func (s *server) delayInitialReconnect(pubStr string) {
×
3630
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3631
        select {
×
3632
        case <-time.After(delay):
×
3633
                s.connectToPersistentPeer(pubStr)
×
3634
        case <-s.quit:
×
3635
        }
3636
}
3637

3638
// prunePersistentPeerConnection removes all internal state related to
3639
// persistent connections to a peer within the server. This is used to avoid
3640
// persistent connection retries to peers we do not have any open channels with.
3641
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
×
3642
        pubKeyStr := string(compressedPubKey[:])
×
3643

×
3644
        s.mu.Lock()
×
3645
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3646
                delete(s.persistentPeers, pubKeyStr)
×
3647
                delete(s.persistentPeersBackoff, pubKeyStr)
×
3648
                delete(s.persistentPeerAddrs, pubKeyStr)
×
3649
                s.cancelConnReqs(pubKeyStr, nil)
×
3650
                s.mu.Unlock()
×
3651

×
3652
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3653
                        "peer has no open channels", compressedPubKey)
×
3654

×
3655
                return
×
3656
        }
×
3657
        s.mu.Unlock()
×
3658
}
3659

3660
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3661
// is instead used to remove persistent peer state for a peer that has been
3662
// disconnected for good cause by the server. Currently, a gossip ban from
3663
// sending garbage and the server running out of restricted-access
3664
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3665
// future, this function may expand when more ban criteria is added.
3666
//
3667
// NOTE: The server's write lock MUST be held when this is called.
3668
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3669
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3670
                delete(s.persistentPeers, remotePub)
×
3671
                delete(s.persistentPeersBackoff, remotePub)
×
3672
                delete(s.persistentPeerAddrs, remotePub)
×
3673
                s.cancelConnReqs(remotePub, nil)
×
3674
        }
×
3675
}
3676

3677
// BroadcastMessage sends a request to the server to broadcast a set of
3678
// messages to all peers other than the one specified by the `skips` parameter.
3679
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3680
// the target peers.
3681
//
3682
// NOTE: This function is safe for concurrent access.
3683
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3684
        msgs ...lnwire.Message) error {
×
3685

×
3686
        // Filter out peers found in the skips map. We synchronize access to
×
3687
        // peersByPub throughout this process to ensure we deliver messages to
×
3688
        // exact set of peers present at the time of invocation.
×
3689
        s.mu.RLock()
×
3690
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
3691
        for pubStr, sPeer := range s.peersByPub {
×
3692
                if skips != nil {
×
3693
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
3694
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
3695
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
3696
                                continue
×
3697
                        }
3698
                }
3699

3700
                peers = append(peers, sPeer)
×
3701
        }
3702
        s.mu.RUnlock()
×
3703

×
3704
        // Iterate over all known peers, dispatching a go routine to enqueue
×
3705
        // all messages to each of peers.
×
3706
        var wg sync.WaitGroup
×
3707
        for _, sPeer := range peers {
×
3708
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
3709
                        sPeer.PubKey())
×
3710

×
3711
                // Dispatch a go routine to enqueue all messages to this peer.
×
3712
                wg.Add(1)
×
3713
                s.wg.Add(1)
×
3714
                go func(p lnpeer.Peer) {
×
3715
                        defer s.wg.Done()
×
3716
                        defer wg.Done()
×
3717

×
3718
                        p.SendMessageLazy(false, msgs...)
×
3719
                }(sPeer)
×
3720
        }
3721

3722
        // Wait for all messages to have been dispatched before returning to
3723
        // caller.
3724
        wg.Wait()
×
3725

×
3726
        return nil
×
3727
}
3728

3729
// NotifyWhenOnline can be called by other subsystems to get notified when a
3730
// particular peer comes online. The peer itself is sent across the peerChan.
3731
//
3732
// NOTE: This function is safe for concurrent access.
3733
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3734
        peerChan chan<- lnpeer.Peer) {
×
3735

×
3736
        s.mu.Lock()
×
3737

×
3738
        // Compute the target peer's identifier.
×
3739
        pubStr := string(peerKey[:])
×
3740

×
3741
        // Check if peer is connected.
×
3742
        peer, ok := s.peersByPub[pubStr]
×
3743
        if ok {
×
3744
                // Unlock here so that the mutex isn't held while we are
×
3745
                // waiting for the peer to become active.
×
3746
                s.mu.Unlock()
×
3747

×
3748
                // Wait until the peer signals that it is actually active
×
3749
                // rather than only in the server's maps.
×
3750
                select {
×
3751
                case <-peer.ActiveSignal():
×
3752
                case <-peer.QuitSignal():
×
3753
                        // The peer quit, so we'll add the channel to the slice
×
3754
                        // and return.
×
3755
                        s.mu.Lock()
×
3756
                        s.peerConnectedListeners[pubStr] = append(
×
3757
                                s.peerConnectedListeners[pubStr], peerChan,
×
3758
                        )
×
3759
                        s.mu.Unlock()
×
3760
                        return
×
3761
                }
3762

3763
                // Connected, can return early.
3764
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
3765

×
3766
                select {
×
3767
                case peerChan <- peer:
×
3768
                case <-s.quit:
×
3769
                }
3770

3771
                return
×
3772
        }
3773

3774
        // Not connected, store this listener such that it can be notified when
3775
        // the peer comes online.
3776
        s.peerConnectedListeners[pubStr] = append(
×
3777
                s.peerConnectedListeners[pubStr], peerChan,
×
3778
        )
×
3779
        s.mu.Unlock()
×
3780
}
3781

3782
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3783
// the given public key has been disconnected. The notification is signaled by
3784
// closing the channel returned.
3785
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
3786
        s.mu.Lock()
×
3787
        defer s.mu.Unlock()
×
3788

×
3789
        c := make(chan struct{})
×
3790

×
3791
        // If the peer is already offline, we can immediately trigger the
×
3792
        // notification.
×
3793
        peerPubKeyStr := string(peerPubKey[:])
×
3794
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3795
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3796
                close(c)
×
3797
                return c
×
3798
        }
×
3799

3800
        // Otherwise, the peer is online, so we'll keep track of the channel to
3801
        // trigger the notification once the server detects the peer
3802
        // disconnects.
3803
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
3804
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
3805
        )
×
3806

×
3807
        return c
×
3808
}
3809

3810
// FindPeer will return the peer that corresponds to the passed in public key.
3811
// This function is used by the funding manager, allowing it to update the
3812
// daemon's local representation of the remote peer.
3813
//
3814
// NOTE: This function is safe for concurrent access.
3815
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
3816
        s.mu.RLock()
×
3817
        defer s.mu.RUnlock()
×
3818

×
3819
        pubStr := string(peerKey.SerializeCompressed())
×
3820

×
3821
        return s.findPeerByPubStr(pubStr)
×
3822
}
×
3823

3824
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3825
// which should be a string representation of the peer's serialized, compressed
3826
// public key.
3827
//
3828
// NOTE: This function is safe for concurrent access.
3829
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3830
        s.mu.RLock()
×
3831
        defer s.mu.RUnlock()
×
3832

×
3833
        return s.findPeerByPubStr(pubStr)
×
3834
}
×
3835

3836
// findPeerByPubStr is an internal method that retrieves the specified peer from
3837
// the server's internal state using.
3838
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3839
        peer, ok := s.peersByPub[pubStr]
×
3840
        if !ok {
×
3841
                return nil, ErrPeerNotConnected
×
3842
        }
×
3843

3844
        return peer, nil
×
3845
}
3846

3847
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3848
// exponential backoff. If no previous backoff was known, the default is
3849
// returned.
3850
func (s *server) nextPeerBackoff(pubStr string,
3851
        startTime time.Time) time.Duration {
×
3852

×
3853
        // Now, determine the appropriate backoff to use for the retry.
×
3854
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
3855
        if !ok {
×
3856
                // If an existing backoff was unknown, use the default.
×
3857
                return s.cfg.MinBackoff
×
3858
        }
×
3859

3860
        // If the peer failed to start properly, we'll just use the previous
3861
        // backoff to compute the subsequent randomized exponential backoff
3862
        // duration. This will roughly double on average.
3863
        if startTime.IsZero() {
×
3864
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3865
        }
×
3866

3867
        // The peer succeeded in starting. If the connection didn't last long
3868
        // enough to be considered stable, we'll continue to back off retries
3869
        // with this peer.
3870
        connDuration := time.Since(startTime)
×
3871
        if connDuration < defaultStableConnDuration {
×
3872
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3873
        }
×
3874

3875
        // The peer succeed in starting and this was stable peer, so we'll
3876
        // reduce the timeout duration by the length of the connection after
3877
        // applying randomized exponential backoff. We'll only apply this in the
3878
        // case that:
3879
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3880
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3881
        if relaxedBackoff > s.cfg.MinBackoff {
×
3882
                return relaxedBackoff
×
3883
        }
×
3884

3885
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3886
        // the stable connection lasted much longer than our previous backoff.
3887
        // To reward such good behavior, we'll reconnect after the default
3888
        // timeout.
3889
        return s.cfg.MinBackoff
×
3890
}
3891

3892
// shouldDropLocalConnection determines if our local connection to a remote peer
3893
// should be dropped in the case of concurrent connection establishment. In
3894
// order to deterministically decide which connection should be dropped, we'll
3895
// utilize the ordering of the local and remote public key. If we didn't use
3896
// such a tie breaker, then we risk _both_ connections erroneously being
3897
// dropped.
3898
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3899
        localPubBytes := local.SerializeCompressed()
×
3900
        remotePubPbytes := remote.SerializeCompressed()
×
3901

×
3902
        // The connection that comes from the node with a "smaller" pubkey
×
3903
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3904
        // should drop our established connection.
×
3905
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3906
}
×
3907

3908
// InboundPeerConnected initializes a new peer in response to a new inbound
3909
// connection.
3910
//
3911
// NOTE: This function is safe for concurrent access.
3912
func (s *server) InboundPeerConnected(conn net.Conn) {
×
3913
        // Exit early if we have already been instructed to shutdown, this
×
3914
        // prevents any delayed callbacks from accidentally registering peers.
×
3915
        if s.Stopped() {
×
3916
                return
×
3917
        }
×
3918

3919
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3920
        pubSer := nodePub.SerializeCompressed()
×
3921
        pubStr := string(pubSer)
×
3922

×
3923
        var pubBytes [33]byte
×
3924
        copy(pubBytes[:], pubSer)
×
3925

×
3926
        s.mu.Lock()
×
3927
        defer s.mu.Unlock()
×
3928

×
3929
        // If we already have an outbound connection to this peer, then ignore
×
3930
        // this new connection.
×
3931
        if p, ok := s.outboundPeers[pubStr]; ok {
×
3932
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
3933
                        "ignoring inbound connection from local=%v, remote=%v",
×
3934
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
3935

×
3936
                conn.Close()
×
3937
                return
×
3938
        }
×
3939

3940
        // If we already have a valid connection that is scheduled to take
3941
        // precedence once the prior peer has finished disconnecting, we'll
3942
        // ignore this connection.
3943
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3944
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3945
                        "scheduled", conn.RemoteAddr(), p)
×
3946
                conn.Close()
×
3947
                return
×
3948
        }
×
3949

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

×
3952
        // Check to see if we already have a connection with this peer. If so,
×
3953
        // we may need to drop our existing connection. This prevents us from
×
3954
        // having duplicate connections to the same peer. We forgo adding a
×
3955
        // default case as we expect these to be the only error values returned
×
3956
        // from findPeerByPubStr.
×
3957
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
3958
        switch err {
×
3959
        case ErrPeerNotConnected:
×
3960
                // We were unable to locate an existing connection with the
×
3961
                // target peer, proceed to connect.
×
3962
                s.cancelConnReqs(pubStr, nil)
×
3963
                s.peerConnected(conn, nil, true)
×
3964

3965
        case nil:
×
3966
                ctx := btclog.WithCtx(
×
3967
                        context.TODO(),
×
3968
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
3969
                )
×
3970

×
3971
                // We already have a connection with the incoming peer. If the
×
3972
                // connection we've already established should be kept and is
×
3973
                // not of the same type of the new connection (inbound), then
×
3974
                // we'll close out the new connection s.t there's only a single
×
3975
                // connection between us.
×
3976
                localPub := s.identityECDH.PubKey()
×
3977
                if !connectedPeer.Inbound() &&
×
3978
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3979

×
3980
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
3981
                                "peer, but already have outbound "+
×
3982
                                "connection, dropping conn",
×
3983
                                fmt.Errorf("already have outbound conn"))
×
3984
                        conn.Close()
×
3985
                        return
×
3986
                }
×
3987

3988
                // Otherwise, if we should drop the connection, then we'll
3989
                // disconnect our already connected peer.
3990
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
3991

×
3992
                s.cancelConnReqs(pubStr, nil)
×
3993

×
3994
                // Remove the current peer from the server's internal state and
×
3995
                // signal that the peer termination watcher does not need to
×
3996
                // execute for this peer.
×
3997
                s.removePeerUnsafe(ctx, connectedPeer)
×
3998
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3999
                s.scheduledPeerConnection[pubStr] = func() {
×
4000
                        s.peerConnected(conn, nil, true)
×
4001
                }
×
4002
        }
4003
}
4004

4005
// OutboundPeerConnected initializes a new peer in response to a new outbound
4006
// connection.
4007
// NOTE: This function is safe for concurrent access.
4008
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
4009
        // Exit early if we have already been instructed to shutdown, this
×
4010
        // prevents any delayed callbacks from accidentally registering peers.
×
4011
        if s.Stopped() {
×
4012
                return
×
4013
        }
×
4014

4015
        nodePub := conn.(*brontide.Conn).RemotePub()
×
4016
        pubSer := nodePub.SerializeCompressed()
×
4017
        pubStr := string(pubSer)
×
4018

×
4019
        var pubBytes [33]byte
×
4020
        copy(pubBytes[:], pubSer)
×
4021

×
4022
        s.mu.Lock()
×
4023
        defer s.mu.Unlock()
×
4024

×
4025
        // If we already have an inbound connection to this peer, then ignore
×
4026
        // this new connection.
×
4027
        if p, ok := s.inboundPeers[pubStr]; ok {
×
4028
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
4029
                        "ignoring outbound connection from local=%v, remote=%v",
×
4030
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
4031

×
4032
                if connReq != nil {
×
4033
                        s.connMgr.Remove(connReq.ID())
×
4034
                }
×
4035
                conn.Close()
×
4036
                return
×
4037
        }
4038
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4039
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4040
                s.connMgr.Remove(connReq.ID())
×
4041
                conn.Close()
×
4042
                return
×
4043
        }
×
4044

4045
        // If we already have a valid connection that is scheduled to take
4046
        // precedence once the prior peer has finished disconnecting, we'll
4047
        // ignore this connection.
4048
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4049
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4050

×
4051
                if connReq != nil {
×
4052
                        s.connMgr.Remove(connReq.ID())
×
4053
                }
×
4054

4055
                conn.Close()
×
4056
                return
×
4057
        }
4058

4059
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
4060
                conn.RemoteAddr())
×
4061

×
4062
        if connReq != nil {
×
4063
                // A successful connection was returned by the connmgr.
×
4064
                // Immediately cancel all pending requests, excluding the
×
4065
                // outbound connection we just established.
×
4066
                ignore := connReq.ID()
×
4067
                s.cancelConnReqs(pubStr, &ignore)
×
4068
        } else {
×
4069
                // This was a successful connection made by some other
×
4070
                // subsystem. Remove all requests being managed by the connmgr.
×
4071
                s.cancelConnReqs(pubStr, nil)
×
4072
        }
×
4073

4074
        // If we already have a connection with this peer, decide whether or not
4075
        // we need to drop the stale connection. We forgo adding a default case
4076
        // as we expect these to be the only error values returned from
4077
        // findPeerByPubStr.
4078
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
4079
        switch err {
×
4080
        case ErrPeerNotConnected:
×
4081
                // We were unable to locate an existing connection with the
×
4082
                // target peer, proceed to connect.
×
4083
                s.peerConnected(conn, connReq, false)
×
4084

4085
        case nil:
×
4086
                ctx := btclog.WithCtx(
×
4087
                        context.TODO(),
×
4088
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
4089
                )
×
4090

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

×
4100
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4101
                                "to peer, but already have inbound "+
×
4102
                                "connection, dropping conn",
×
4103
                                fmt.Errorf("already have inbound conn"))
×
4104
                        if connReq != nil {
×
4105
                                s.connMgr.Remove(connReq.ID())
×
4106
                        }
×
4107
                        conn.Close()
×
4108
                        return
×
4109
                }
4110

4111
                // Otherwise, _their_ connection should be dropped. So we'll
4112
                // disconnect the peer and send the now obsolete peer to the
4113
                // server for garbage collection.
4114
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4115

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

4127
// UnassignedConnID is the default connection ID that a request can have before
4128
// it actually is submitted to the connmgr.
4129
// TODO(conner): move into connmgr package, or better, add connmgr method for
4130
// generating atomic IDs
4131
const UnassignedConnID uint64 = 0
4132

4133
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4134
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4135
// Afterwards, each connection request removed from the connmgr. The caller can
4136
// optionally specify a connection ID to ignore, which prevents us from
4137
// canceling a successful request. All persistent connreqs for the provided
4138
// pubkey are discarded after the operationjw.
4139
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
4140
        // First, cancel any lingering persistent retry attempts, which will
×
4141
        // prevent retries for any with backoffs that are still maturing.
×
4142
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
4143
                close(cancelChan)
×
4144
                delete(s.persistentRetryCancels, pubStr)
×
4145
        }
×
4146

4147
        // Next, check to see if we have any outstanding persistent connection
4148
        // requests to this peer. If so, then we'll remove all of these
4149
        // connection requests, and also delete the entry from the map.
4150
        connReqs, ok := s.persistentConnReqs[pubStr]
×
4151
        if !ok {
×
4152
                return
×
4153
        }
×
4154

4155
        for _, connReq := range connReqs {
×
4156
                srvrLog.Tracef("Canceling %s:", connReqs)
×
4157

×
4158
                // Atomically capture the current request identifier.
×
4159
                connID := connReq.ID()
×
4160

×
4161
                // Skip any zero IDs, this indicates the request has not
×
4162
                // yet been schedule.
×
4163
                if connID == UnassignedConnID {
×
4164
                        continue
×
4165
                }
4166

4167
                // Skip a particular connection ID if instructed.
4168
                if skip != nil && connID == *skip {
×
4169
                        continue
×
4170
                }
4171

4172
                s.connMgr.Remove(connID)
×
4173
        }
4174

4175
        delete(s.persistentConnReqs, pubStr)
×
4176
}
4177

4178
// handleCustomMessage dispatches an incoming custom peers message to
4179
// subscribers.
4180
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
4181
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
4182
                peer, msg.Type)
×
4183

×
4184
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4185
                Peer: peer,
×
4186
                Msg:  msg,
×
4187
        })
×
4188
}
×
4189

4190
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4191
// messages.
4192
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4193
        return s.customMessageServer.Subscribe()
×
4194
}
×
4195

4196
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4197
// the channelNotifier's NotifyOpenChannelEvent.
4198
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4199
        remotePub *btcec.PublicKey) {
×
4200

×
4201
        // Call newOpenChan to update the access manager's maps for this peer.
×
4202
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
4203
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4204
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
4205
        }
×
4206

4207
        // Notify subscribers about this open channel event.
4208
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4209
}
4210

4211
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4212
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4213
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4214
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
4215

×
4216
        // Call newPendingOpenChan to update the access manager's maps for this
×
4217
        // peer.
×
4218
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
4219
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4220
                        "channel[%v] pending open",
×
4221
                        remotePub.SerializeCompressed(), op)
×
4222
        }
×
4223

4224
        // Notify subscribers about this event.
4225
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4226
}
4227

4228
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4229
// calls the channelNotifier's NotifyFundingTimeout.
4230
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4231
        remotePub *btcec.PublicKey) {
×
4232

×
4233
        // Call newPendingCloseChan to potentially demote the peer.
×
4234
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
4235
        if err != nil {
×
4236
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4237
                        "channel[%v] pending close",
×
4238
                        remotePub.SerializeCompressed(), op)
×
4239
        }
×
4240

4241
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4242
                // If we encounter an error while attempting to disconnect the
×
4243
                // peer, log the error.
×
4244
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4245
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4246
                }
×
4247
        }
4248

4249
        // Notify subscribers about this event.
4250
        s.channelNotifier.NotifyFundingTimeout(op)
×
4251
}
4252

4253
// peerConnected is a function that handles initialization a newly connected
4254
// peer by adding it to the server's global list of all active peers, and
4255
// starting all the goroutines the peer needs to function properly. The inbound
4256
// boolean should be true if the peer initiated the connection to us.
4257
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4258
        inbound bool) {
×
4259

×
4260
        brontideConn := conn.(*brontide.Conn)
×
4261
        addr := conn.RemoteAddr()
×
4262
        pubKey := brontideConn.RemotePub()
×
4263

×
4264
        // Only restrict access for inbound connections, which means if the
×
4265
        // remote node's public key is banned or the restricted slots are used
×
4266
        // up, we will drop the connection.
×
4267
        //
×
4268
        // TODO(yy): Consider perform this check in
×
4269
        // `peerAccessMan.addPeerAccess`.
×
4270
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
4271
        if inbound && err != nil {
×
4272
                pubSer := pubKey.SerializeCompressed()
×
4273

×
4274
                // Clean up the persistent peer maps if we're dropping this
×
4275
                // connection.
×
4276
                s.bannedPersistentPeerConnection(string(pubSer))
×
4277

×
4278
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4279
                        "of restricted-access connection slots: %v.", pubSer,
×
4280
                        err)
×
4281

×
4282
                conn.Close()
×
4283

×
4284
                return
×
4285
        }
×
4286

4287
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4288
                pubKey.SerializeCompressed(), addr, inbound)
×
4289

×
4290
        peerAddr := &lnwire.NetAddress{
×
4291
                IdentityKey: pubKey,
×
4292
                Address:     addr,
×
4293
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4294
        }
×
4295

×
4296
        // With the brontide connection established, we'll now craft the feature
×
4297
        // vectors to advertise to the remote node.
×
4298
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
4299
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4300

×
4301
        // Lookup past error caches for the peer in the server. If no buffer is
×
4302
        // found, create a fresh buffer.
×
4303
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
4304
        errBuffer, ok := s.peerErrors[pkStr]
×
4305
        if !ok {
×
4306
                var err error
×
4307
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
4308
                if err != nil {
×
4309
                        srvrLog.Errorf("unable to create peer %v", err)
×
4310
                        return
×
4311
                }
×
4312
        }
4313

4314
        // If we directly set the peer.Config TowerClient member to the
4315
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4316
        // the peer.Config's TowerClient member will not evaluate to nil even
4317
        // though the underlying value is nil. To avoid this gotcha which can
4318
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4319
        // TowerClient if needed.
4320
        var towerClient wtclient.ClientManager
×
4321
        if s.towerClientMgr != nil {
×
4322
                towerClient = s.towerClientMgr
×
4323
        }
×
4324

4325
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
4326
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
4327

×
4328
        // Now that we've established a connection, create a peer, and it to the
×
4329
        // set of currently active peers. Configure the peer with the incoming
×
4330
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
4331
        // offered that would trigger channel closure. In case of outgoing
×
4332
        // htlcs, an extra block is added to prevent the channel from being
×
4333
        // closed when the htlc is outstanding and a new block comes in.
×
4334
        pCfg := peer.Config{
×
4335
                Conn:                    brontideConn,
×
4336
                ConnReq:                 connReq,
×
4337
                Addr:                    peerAddr,
×
4338
                Inbound:                 inbound,
×
4339
                Features:                initFeatures,
×
4340
                LegacyFeatures:          legacyFeatures,
×
4341
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
4342
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
4343
                ErrorBuffer:             errBuffer,
×
4344
                WritePool:               s.writePool,
×
4345
                ReadPool:                s.readPool,
×
4346
                Switch:                  s.htlcSwitch,
×
4347
                InterceptSwitch:         s.interceptableSwitch,
×
4348
                ChannelDB:               s.chanStateDB,
×
4349
                ChannelGraph:            s.graphDB,
×
4350
                ChainArb:                s.chainArb,
×
4351
                AuthGossiper:            s.authGossiper,
×
4352
                ChanStatusMgr:           s.chanStatusMgr,
×
4353
                ChainIO:                 s.cc.ChainIO,
×
4354
                FeeEstimator:            s.cc.FeeEstimator,
×
4355
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
4356
                SigPool:                 s.sigPool,
×
4357
                Wallet:                  s.cc.Wallet,
×
4358
                ChainNotifier:           s.cc.ChainNotifier,
×
4359
                BestBlockView:           s.cc.BestBlockTracker,
×
4360
                RoutingPolicy:           s.cc.RoutingPolicy,
×
4361
                Sphinx:                  s.sphinx,
×
4362
                WitnessBeacon:           s.witnessBeacon,
×
4363
                Invoices:                s.invoices,
×
4364
                ChannelNotifier:         s.channelNotifier,
×
4365
                HtlcNotifier:            s.htlcNotifier,
×
4366
                TowerClient:             towerClient,
×
4367
                DisconnectPeer:          s.DisconnectPeer,
×
4368
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
4369
                        lnwire.NodeAnnouncement1, error) {
×
4370

×
4371
                        return s.genNodeAnnouncement(nil)
×
4372
                },
×
4373

4374
                PongBuf: s.pongBuf,
4375

4376
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4377

4378
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4379

4380
                FundingManager: s.fundingMgr,
4381

4382
                Hodl:                    s.cfg.Hodl,
4383
                UnsafeReplay:            s.cfg.UnsafeReplay,
4384
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4385
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4386
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4387
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4388
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4389
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4390
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4391
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4392
                HandleCustomMessage:    s.handleCustomMessage,
4393
                GetAliases:             s.aliasMgr.GetAliases,
4394
                RequestAlias:           s.aliasMgr.RequestAlias,
4395
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4396
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4397
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4398
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4399
                MaxFeeExposure:         thresholdMSats,
4400
                Quit:                   s.quit,
4401
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4402
                AuxSigner:              s.implCfg.AuxSigner,
4403
                MsgRouter:              s.implCfg.MsgRouter,
4404
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4405
                AuxResolver:            s.implCfg.AuxContractResolver,
4406
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4407
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4408
                ShouldFwdExpEndorsement: func() bool {
×
4409
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
4410
                                return false
×
4411
                        }
×
4412

4413
                        return clock.NewDefaultClock().Now().Before(
×
4414
                                EndorsementExperimentEnd,
×
4415
                        )
×
4416
                },
4417
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4418
        }
4419

4420
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
4421
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
4422

×
4423
        p := peer.NewBrontide(pCfg)
×
4424

×
4425
        // Update the access manager with the access permission for this peer.
×
4426
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
4427

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

×
4431
        s.addPeer(p)
×
4432

×
4433
        // Once we have successfully added the peer to the server, we can
×
4434
        // delete the previous error buffer from the server's map of error
×
4435
        // buffers.
×
4436
        delete(s.peerErrors, pkStr)
×
4437

×
4438
        // Dispatch a goroutine to asynchronously start the peer. This process
×
4439
        // includes sending and receiving Init messages, which would be a DOS
×
4440
        // vector if we held the server's mutex throughout the procedure.
×
4441
        s.wg.Add(1)
×
4442
        go s.peerInitializer(p)
×
4443
}
4444

4445
// addPeer adds the passed peer to the server's global state of all active
4446
// peers.
4447
func (s *server) addPeer(p *peer.Brontide) {
×
4448
        if p == nil {
×
4449
                return
×
4450
        }
×
4451

4452
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4453

×
4454
        // Ignore new peers if we're shutting down.
×
4455
        if s.Stopped() {
×
4456
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4457
                        pubBytes)
×
4458
                p.Disconnect(ErrServerShuttingDown)
×
4459

×
4460
                return
×
4461
        }
×
4462

4463
        // Track the new peer in our indexes so we can quickly look it up either
4464
        // according to its public key, or its peer ID.
4465
        // TODO(roasbeef): pipe all requests through to the
4466
        // queryHandler/peerManager
4467

4468
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4469
        // be human-readable.
4470
        pubStr := string(pubBytes)
×
4471

×
4472
        s.peersByPub[pubStr] = p
×
4473

×
4474
        if p.Inbound() {
×
4475
                s.inboundPeers[pubStr] = p
×
4476
        } else {
×
4477
                s.outboundPeers[pubStr] = p
×
4478
        }
×
4479

4480
        // Inform the peer notifier of a peer online event so that it can be reported
4481
        // to clients listening for peer events.
4482
        var pubKey [33]byte
×
4483
        copy(pubKey[:], pubBytes)
×
4484
}
4485

4486
// peerInitializer asynchronously starts a newly connected peer after it has
4487
// been added to the server's peer map. This method sets up a
4488
// peerTerminationWatcher for the given peer, and ensures that it executes even
4489
// if the peer failed to start. In the event of a successful connection, this
4490
// method reads the negotiated, local feature-bits and spawns the appropriate
4491
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4492
// be signaled of the new peer once the method returns.
4493
//
4494
// NOTE: This MUST be launched as a goroutine.
4495
func (s *server) peerInitializer(p *peer.Brontide) {
×
4496
        defer s.wg.Done()
×
4497

×
4498
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4499

×
4500
        // Avoid initializing peers while the server is exiting.
×
4501
        if s.Stopped() {
×
4502
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4503
                        pubBytes)
×
4504
                return
×
4505
        }
×
4506

4507
        // Create a channel that will be used to signal a successful start of
4508
        // the link. This prevents the peer termination watcher from beginning
4509
        // its duty too early.
4510
        ready := make(chan struct{})
×
4511

×
4512
        // Before starting the peer, launch a goroutine to watch for the
×
4513
        // unexpected termination of this peer, which will ensure all resources
×
4514
        // are properly cleaned up, and re-establish persistent connections when
×
4515
        // necessary. The peer termination watcher will be short circuited if
×
4516
        // the peer is ever added to the ignorePeerTermination map, indicating
×
4517
        // that the server has already handled the removal of this peer.
×
4518
        s.wg.Add(1)
×
4519
        go s.peerTerminationWatcher(p, ready)
×
4520

×
4521
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
4522
        // will unblock the peerTerminationWatcher.
×
4523
        if err := p.Start(); err != nil {
×
4524
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4525

×
4526
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4527
                return
×
4528
        }
×
4529

4530
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4531
        // was successful, and to begin watching the peer's wait group.
4532
        close(ready)
×
4533

×
4534
        s.mu.Lock()
×
4535
        defer s.mu.Unlock()
×
4536

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

×
4540
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
4541
        // route.Vertex as the key type of peerConnectedListeners.
×
4542
        pubStr := string(pubBytes)
×
4543
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
4544
                select {
×
4545
                case peerChan <- p:
×
4546
                case <-s.quit:
×
4547
                        return
×
4548
                }
4549
        }
4550
        delete(s.peerConnectedListeners, pubStr)
×
4551

×
4552
        // Since the peer has been fully initialized, now it's time to notify
×
4553
        // the RPC about the peer online event.
×
4554
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4555
}
4556

4557
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4558
// and then cleans up all resources allocated to the peer, notifies relevant
4559
// sub-systems of its demise, and finally handles re-connecting to the peer if
4560
// it's persistent. If the server intentionally disconnects a peer, it should
4561
// have a corresponding entry in the ignorePeerTermination map which will cause
4562
// the cleanup routine to exit early. The passed `ready` chan is used to
4563
// synchronize when WaitForDisconnect should begin watching on the peer's
4564
// waitgroup. The ready chan should only be signaled if the peer starts
4565
// successfully, otherwise the peer should be disconnected instead.
4566
//
4567
// NOTE: This MUST be launched as a goroutine.
4568
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
4569
        defer s.wg.Done()
×
4570

×
4571
        ctx := btclog.WithCtx(
×
4572
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
4573
        )
×
4574

×
4575
        p.WaitForDisconnect(ready)
×
4576

×
4577
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
4578

×
4579
        // If the server is exiting then we can bail out early ourselves as all
×
4580
        // the other sub-systems will already be shutting down.
×
4581
        if s.Stopped() {
×
4582
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
4583
                return
×
4584
        }
×
4585

4586
        // Next, we'll cancel all pending funding reservations with this node.
4587
        // If we tried to initiate any funding flows that haven't yet finished,
4588
        // then we need to unlock those committed outputs so they're still
4589
        // available for use.
4590
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
4591

×
4592
        pubKey := p.IdentityKey()
×
4593

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

×
4598
        // Tell the switch to remove all links associated with this peer.
×
4599
        // Passing nil as the target link indicates that all links associated
×
4600
        // with this interface should be closed.
×
4601
        //
×
4602
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
4603
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
4604
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4605
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4606
        }
×
4607

4608
        for _, link := range links {
×
4609
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4610
        }
×
4611

4612
        s.mu.Lock()
×
4613
        defer s.mu.Unlock()
×
4614

×
4615
        // If there were any notification requests for when this peer
×
4616
        // disconnected, we can trigger them now.
×
4617
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
4618
        pubStr := string(pubKey.SerializeCompressed())
×
4619
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
4620
                close(offlineChan)
×
4621
        }
×
4622
        delete(s.peerDisconnectedListeners, pubStr)
×
4623

×
4624
        // If the server has already removed this peer, we can short circuit the
×
4625
        // peer termination watcher and skip cleanup.
×
4626
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4627
                delete(s.ignorePeerTermination, p)
×
4628

×
4629
                pubKey := p.PubKey()
×
4630
                pubStr := string(pubKey[:])
×
4631

×
4632
                // If a connection callback is present, we'll go ahead and
×
4633
                // execute it now that previous peer has fully disconnected. If
×
4634
                // the callback is not present, this likely implies the peer was
×
4635
                // purposefully disconnected via RPC, and that no reconnect
×
4636
                // should be attempted.
×
4637
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4638
                if ok {
×
4639
                        delete(s.scheduledPeerConnection, pubStr)
×
4640
                        connCallback()
×
4641
                }
×
4642
                return
×
4643
        }
4644

4645
        // First, cleanup any remaining state the server has regarding the peer
4646
        // in question.
4647
        s.removePeerUnsafe(ctx, p)
×
4648

×
4649
        // Next, check to see if this is a persistent peer or not.
×
4650
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4651
                return
×
4652
        }
×
4653

4654
        // Get the last address that we used to connect to the peer.
4655
        addrs := []net.Addr{
×
4656
                p.NetAddress().Address,
×
4657
        }
×
4658

×
4659
        // We'll ensure that we locate all the peers advertised addresses for
×
4660
        // reconnection purposes.
×
4661
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
4662
        switch {
×
4663
        // We found advertised addresses, so use them.
4664
        case err == nil:
×
4665
                addrs = advertisedAddrs
×
4666

4667
        // The peer doesn't have an advertised address.
4668
        case err == errNoAdvertisedAddr:
×
4669
                // If it is an outbound peer then we fall back to the existing
×
4670
                // peer address.
×
4671
                if !p.Inbound() {
×
4672
                        break
×
4673
                }
4674

4675
                // Fall back to the existing peer address if
4676
                // we're not accepting connections over Tor.
4677
                if s.torController == nil {
×
4678
                        break
×
4679
                }
4680

4681
                // If we are, the peer's address won't be known
4682
                // to us (we'll see a private address, which is
4683
                // the address used by our onion service to dial
4684
                // to lnd), so we don't have enough information
4685
                // to attempt a reconnect.
4686
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4687
                        "to inbound peer without advertised address")
×
4688
                return
×
4689

4690
        // We came across an error retrieving an advertised
4691
        // address, log it, and fall back to the existing peer
4692
        // address.
4693
        default:
×
4694
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
4695
                        "address for peer", err)
×
4696
        }
4697

4698
        // Make an easy lookup map so that we can check if an address
4699
        // is already in the address list that we have stored for this peer.
4700
        existingAddrs := make(map[string]bool)
×
4701
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
4702
                existingAddrs[addr.String()] = true
×
4703
        }
×
4704

4705
        // Add any missing addresses for this peer to persistentPeerAddr.
4706
        for _, addr := range addrs {
×
4707
                if existingAddrs[addr.String()] {
×
4708
                        continue
×
4709
                }
4710

4711
                s.persistentPeerAddrs[pubStr] = append(
×
4712
                        s.persistentPeerAddrs[pubStr],
×
4713
                        &lnwire.NetAddress{
×
4714
                                IdentityKey: p.IdentityKey(),
×
4715
                                Address:     addr,
×
4716
                                ChainNet:    p.NetAddress().ChainNet,
×
4717
                        },
×
4718
                )
×
4719
        }
4720

4721
        // Record the computed backoff in the backoff map.
4722
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4723
        s.persistentPeersBackoff[pubStr] = backoff
×
4724

×
4725
        // Initialize a retry canceller for this peer if one does not
×
4726
        // exist.
×
4727
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4728
        if !ok {
×
4729
                cancelChan = make(chan struct{})
×
4730
                s.persistentRetryCancels[pubStr] = cancelChan
×
4731
        }
×
4732

4733
        // We choose not to wait group this go routine since the Connect
4734
        // call can stall for arbitrarily long if we shutdown while an
4735
        // outbound connection attempt is being made.
4736
        go func() {
×
4737
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
4738
                        "re-establishment to persistent peer",
×
4739
                        "reconnecting_in", backoff)
×
4740

×
4741
                select {
×
4742
                case <-time.After(backoff):
×
4743
                case <-cancelChan:
×
4744
                        return
×
4745
                case <-s.quit:
×
4746
                        return
×
4747
                }
4748

4749
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
4750
                        "connection")
×
4751

×
4752
                s.connectToPersistentPeer(pubStr)
×
4753
        }()
4754
}
4755

4756
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4757
// to connect to the peer. It creates connection requests if there are
4758
// currently none for a given address and it removes old connection requests
4759
// if the associated address is no longer in the latest address list for the
4760
// peer.
4761
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
4762
        s.mu.Lock()
×
4763
        defer s.mu.Unlock()
×
4764

×
4765
        // Create an easy lookup map of the addresses we have stored for the
×
4766
        // peer. We will remove entries from this map if we have existing
×
4767
        // connection requests for the associated address and then any leftover
×
4768
        // entries will indicate which addresses we should create new
×
4769
        // connection requests for.
×
4770
        addrMap := make(map[string]*lnwire.NetAddress)
×
4771
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
4772
                addrMap[addr.String()] = addr
×
4773
        }
×
4774

4775
        // Go through each of the existing connection requests and
4776
        // check if they correspond to the latest set of addresses. If
4777
        // there is a connection requests that does not use one of the latest
4778
        // advertised addresses then remove that connection request.
4779
        var updatedConnReqs []*connmgr.ConnReq
×
4780
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
4781
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
4782

×
4783
                switch _, ok := addrMap[lnAddr]; ok {
×
4784
                // If the existing connection request is using one of the
4785
                // latest advertised addresses for the peer then we add it to
4786
                // updatedConnReqs and remove the associated address from
4787
                // addrMap so that we don't recreate this connReq later on.
4788
                case true:
×
4789
                        updatedConnReqs = append(
×
4790
                                updatedConnReqs, connReq,
×
4791
                        )
×
4792
                        delete(addrMap, lnAddr)
×
4793

4794
                // If the existing connection request is using an address that
4795
                // is not one of the latest advertised addresses for the peer
4796
                // then we remove the connecting request from the connection
4797
                // manager.
4798
                case false:
×
4799
                        srvrLog.Info(
×
4800
                                "Removing conn req:", connReq.Addr.String(),
×
4801
                        )
×
4802
                        s.connMgr.Remove(connReq.ID())
×
4803
                }
4804
        }
4805

4806
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
4807

×
4808
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
4809
        if !ok {
×
4810
                cancelChan = make(chan struct{})
×
4811
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
4812
        }
×
4813

4814
        // Any addresses left in addrMap are new ones that we have not made
4815
        // connection requests for. So create new connection requests for those.
4816
        // If there is more than one address in the address map, stagger the
4817
        // creation of the connection requests for those.
4818
        go func() {
×
4819
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4820
                defer ticker.Stop()
×
4821

×
4822
                for _, addr := range addrMap {
×
4823
                        // Send the persistent connection request to the
×
4824
                        // connection manager, saving the request itself so we
×
4825
                        // can cancel/restart the process as needed.
×
4826
                        connReq := &connmgr.ConnReq{
×
4827
                                Addr:      addr,
×
4828
                                Permanent: true,
×
4829
                        }
×
4830

×
4831
                        s.mu.Lock()
×
4832
                        s.persistentConnReqs[pubKeyStr] = append(
×
4833
                                s.persistentConnReqs[pubKeyStr], connReq,
×
4834
                        )
×
4835
                        s.mu.Unlock()
×
4836

×
4837
                        srvrLog.Debugf("Attempting persistent connection to "+
×
4838
                                "channel peer %v", addr)
×
4839

×
4840
                        go s.connMgr.Connect(connReq)
×
4841

×
4842
                        select {
×
4843
                        case <-s.quit:
×
4844
                                return
×
4845
                        case <-cancelChan:
×
4846
                                return
×
4847
                        case <-ticker.C:
×
4848
                        }
4849
                }
4850
        }()
4851
}
4852

4853
// removePeerUnsafe removes the passed peer from the server's state of all
4854
// active peers.
4855
//
4856
// NOTE: Server mutex must be held when calling this function.
4857
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
4858
        if p == nil {
×
4859
                return
×
4860
        }
×
4861

4862
        srvrLog.DebugS(ctx, "Removing peer")
×
4863

×
4864
        // Exit early if we have already been instructed to shutdown, the peers
×
4865
        // will be disconnected in the server shutdown process.
×
4866
        if s.Stopped() {
×
4867
                return
×
4868
        }
×
4869

4870
        // Capture the peer's public key and string representation.
4871
        pKey := p.PubKey()
×
4872
        pubSer := pKey[:]
×
4873
        pubStr := string(pubSer)
×
4874

×
4875
        delete(s.peersByPub, pubStr)
×
4876

×
4877
        if p.Inbound() {
×
4878
                delete(s.inboundPeers, pubStr)
×
4879
        } else {
×
4880
                delete(s.outboundPeers, pubStr)
×
4881
        }
×
4882

4883
        // When removing the peer we make sure to disconnect it asynchronously
4884
        // to avoid blocking the main server goroutine because it is holding the
4885
        // server's mutex. Disconnecting the peer might block and wait until the
4886
        // peer has fully started up. This can happen if an inbound and outbound
4887
        // race condition occurs.
4888
        s.wg.Add(1)
×
4889
        go func() {
×
4890
                defer s.wg.Done()
×
4891

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

×
4894
                // If this peer had an active persistent connection request,
×
4895
                // remove it.
×
4896
                if p.ConnReq() != nil {
×
4897
                        s.connMgr.Remove(p.ConnReq().ID())
×
4898
                }
×
4899

4900
                // Remove the peer's access permission from the access manager.
4901
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
4902
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
4903

×
4904
                // Copy the peer's error buffer across to the server if it has
×
4905
                // any items in it so that we can restore peer errors across
×
4906
                // connections. We need to look up the error after the peer has
×
4907
                // been disconnected because we write the error in the
×
4908
                // `Disconnect` method.
×
4909
                s.mu.Lock()
×
4910
                if p.ErrorBuffer().Total() > 0 {
×
4911
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
4912
                }
×
4913
                s.mu.Unlock()
×
4914

×
4915
                // Inform the peer notifier of a peer offline event so that it
×
4916
                // can be reported to clients listening for peer events.
×
4917
                var pubKey [33]byte
×
4918
                copy(pubKey[:], pubSer)
×
4919

×
4920
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4921
        }()
4922
}
4923

4924
// ConnectToPeer requests that the server connect to a Lightning Network peer
4925
// at the specified address. This function will *block* until either a
4926
// connection is established, or the initial handshake process fails.
4927
//
4928
// NOTE: This function is safe for concurrent access.
4929
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4930
        perm bool, timeout time.Duration) error {
×
4931

×
4932
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
4933

×
4934
        // Acquire mutex, but use explicit unlocking instead of defer for
×
4935
        // better granularity.  In certain conditions, this method requires
×
4936
        // making an outbound connection to a remote peer, which requires the
×
4937
        // lock to be released, and subsequently reacquired.
×
4938
        s.mu.Lock()
×
4939

×
4940
        // Ensure we're not already connected to this peer.
×
4941
        peer, err := s.findPeerByPubStr(targetPub)
×
4942

×
4943
        // When there's no error it means we already have a connection with this
×
4944
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
4945
        // set, we will ignore the existing connection and continue.
×
4946
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
4947
                s.mu.Unlock()
×
4948
                return &errPeerAlreadyConnected{peer: peer}
×
4949
        }
×
4950

4951
        // Peer was not found, continue to pursue connection with peer.
4952

4953
        // If there's already a pending connection request for this pubkey,
4954
        // then we ignore this request to ensure we don't create a redundant
4955
        // connection.
4956
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
4957
                srvrLog.Warnf("Already have %d persistent connection "+
×
4958
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
4959
        }
×
4960

4961
        // If there's not already a pending or active connection to this node,
4962
        // then instruct the connection manager to attempt to establish a
4963
        // persistent connection to the peer.
4964
        srvrLog.Debugf("Connecting to %v", addr)
×
4965
        if perm {
×
4966
                connReq := &connmgr.ConnReq{
×
4967
                        Addr:      addr,
×
4968
                        Permanent: true,
×
4969
                }
×
4970

×
4971
                // Since the user requested a permanent connection, we'll set
×
4972
                // the entry to true which will tell the server to continue
×
4973
                // reconnecting even if the number of channels with this peer is
×
4974
                // zero.
×
4975
                s.persistentPeers[targetPub] = true
×
4976
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
4977
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
4978
                }
×
4979
                s.persistentConnReqs[targetPub] = append(
×
4980
                        s.persistentConnReqs[targetPub], connReq,
×
4981
                )
×
4982
                s.mu.Unlock()
×
4983

×
4984
                go s.connMgr.Connect(connReq)
×
4985

×
4986
                return nil
×
4987
        }
4988
        s.mu.Unlock()
×
4989

×
4990
        // If we're not making a persistent connection, then we'll attempt to
×
4991
        // connect to the target peer. If the we can't make the connection, or
×
4992
        // the crypto negotiation breaks down, then return an error to the
×
4993
        // caller.
×
4994
        errChan := make(chan error, 1)
×
4995
        s.connectToPeer(addr, errChan, timeout)
×
4996

×
4997
        select {
×
4998
        case err := <-errChan:
×
4999
                return err
×
5000
        case <-s.quit:
×
5001
                return ErrServerShuttingDown
×
5002
        }
5003
}
5004

5005
// connectToPeer establishes a connection to a remote peer. errChan is used to
5006
// notify the caller if the connection attempt has failed. Otherwise, it will be
5007
// closed.
5008
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5009
        errChan chan<- error, timeout time.Duration) {
×
5010

×
5011
        conn, err := brontide.Dial(
×
5012
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
5013
        )
×
5014
        if err != nil {
×
5015
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
5016
                select {
×
5017
                case errChan <- err:
×
5018
                case <-s.quit:
×
5019
                }
5020
                return
×
5021
        }
5022

5023
        close(errChan)
×
5024

×
5025
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
5026
                conn.LocalAddr(), conn.RemoteAddr())
×
5027

×
5028
        s.OutboundPeerConnected(nil, conn)
×
5029
}
5030

5031
// DisconnectPeer sends the request to server to close the connection with peer
5032
// identified by public key.
5033
//
5034
// NOTE: This function is safe for concurrent access.
5035
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
5036
        pubBytes := pubKey.SerializeCompressed()
×
5037
        pubStr := string(pubBytes)
×
5038

×
5039
        s.mu.Lock()
×
5040
        defer s.mu.Unlock()
×
5041

×
5042
        // Check that were actually connected to this peer. If not, then we'll
×
5043
        // exit in an error as we can't disconnect from a peer that we're not
×
5044
        // currently connected to.
×
5045
        peer, err := s.findPeerByPubStr(pubStr)
×
5046
        if err == ErrPeerNotConnected {
×
5047
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
5048
        }
×
5049

5050
        srvrLog.Infof("Disconnecting from %v", peer)
×
5051

×
5052
        s.cancelConnReqs(pubStr, nil)
×
5053

×
5054
        // If this peer was formerly a persistent connection, then we'll remove
×
5055
        // them from this map so we don't attempt to re-connect after we
×
5056
        // disconnect.
×
5057
        delete(s.persistentPeers, pubStr)
×
5058
        delete(s.persistentPeersBackoff, pubStr)
×
5059

×
5060
        // Remove the peer by calling Disconnect. Previously this was done with
×
5061
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
5062
        //
×
5063
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
5064
        // goroutine because we might hold the server's mutex.
×
5065
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
5066

×
5067
        return nil
×
5068
}
5069

5070
// OpenChannel sends a request to the server to open a channel to the specified
5071
// peer identified by nodeKey with the passed channel funding parameters.
5072
//
5073
// NOTE: This function is safe for concurrent access.
5074
func (s *server) OpenChannel(
5075
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
5076

×
5077
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
5078
        // + a ChanOpen update, and we want to make sure the funding process is
×
5079
        // not blocked if the caller is not reading the updates.
×
5080
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
5081
        req.Err = make(chan error, 1)
×
5082

×
5083
        // First attempt to locate the target peer to open a channel with, if
×
5084
        // we're unable to locate the peer then this request will fail.
×
5085
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
5086
        s.mu.RLock()
×
5087
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
5088
        if !ok {
×
5089
                s.mu.RUnlock()
×
5090

×
5091
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5092
                return req.Updates, req.Err
×
5093
        }
×
5094
        req.Peer = peer
×
5095
        s.mu.RUnlock()
×
5096

×
5097
        // We'll wait until the peer is active before beginning the channel
×
5098
        // opening process.
×
5099
        select {
×
5100
        case <-peer.ActiveSignal():
×
5101
        case <-peer.QuitSignal():
×
5102
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5103
                return req.Updates, req.Err
×
5104
        case <-s.quit:
×
5105
                req.Err <- ErrServerShuttingDown
×
5106
                return req.Updates, req.Err
×
5107
        }
5108

5109
        // If the fee rate wasn't specified at this point we fail the funding
5110
        // because of the missing fee rate information. The caller of the
5111
        // `OpenChannel` method needs to make sure that default values for the
5112
        // fee rate are set beforehand.
5113
        if req.FundingFeePerKw == 0 {
×
5114
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5115
                        "the channel opening transaction")
×
5116

×
5117
                return req.Updates, req.Err
×
5118
        }
×
5119

5120
        // Spawn a goroutine to send the funding workflow request to the funding
5121
        // manager. This allows the server to continue handling queries instead
5122
        // of blocking on this request which is exported as a synchronous
5123
        // request to the outside world.
5124
        go s.fundingMgr.InitFundingWorkflow(req)
×
5125

×
5126
        return req.Updates, req.Err
×
5127
}
5128

5129
// Peers returns a slice of all active peers.
5130
//
5131
// NOTE: This function is safe for concurrent access.
5132
func (s *server) Peers() []*peer.Brontide {
×
5133
        s.mu.RLock()
×
5134
        defer s.mu.RUnlock()
×
5135

×
5136
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
5137
        for _, peer := range s.peersByPub {
×
5138
                peers = append(peers, peer)
×
5139
        }
×
5140

5141
        return peers
×
5142
}
5143

5144
// computeNextBackoff uses a truncated exponential backoff to compute the next
5145
// backoff using the value of the exiting backoff. The returned duration is
5146
// randomized in either direction by 1/20 to prevent tight loops from
5147
// stabilizing.
5148
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
5149
        // Double the current backoff, truncating if it exceeds our maximum.
×
5150
        nextBackoff := 2 * currBackoff
×
5151
        if nextBackoff > maxBackoff {
×
5152
                nextBackoff = maxBackoff
×
5153
        }
×
5154

5155
        // Using 1/10 of our duration as a margin, compute a random offset to
5156
        // avoid the nodes entering connection cycles.
5157
        margin := nextBackoff / 10
×
5158

×
5159
        var wiggle big.Int
×
5160
        wiggle.SetUint64(uint64(margin))
×
5161
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5162
                // Randomizing is not mission critical, so we'll just return the
×
5163
                // current backoff.
×
5164
                return nextBackoff
×
5165
        }
×
5166

5167
        // Otherwise add in our wiggle, but subtract out half of the margin so
5168
        // that the backoff can tweaked by 1/20 in either direction.
5169
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5170
}
5171

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

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

×
5180
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
5181
        if err != nil {
×
5182
                return nil, err
×
5183
        }
×
5184

5185
        node, err := s.graphDB.FetchNode(ctx, vertex)
×
5186
        if err != nil {
×
5187
                return nil, err
×
5188
        }
×
5189

5190
        if len(node.Addresses) == 0 {
×
5191
                return nil, errNoAdvertisedAddr
×
5192
        }
×
5193

5194
        return node.Addresses, nil
×
5195
}
5196

5197
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5198
// channel update for a target channel.
5199
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5200
        *lnwire.ChannelUpdate1, error) {
×
5201

×
5202
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
5203
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
5204
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
5205
                if err != nil {
×
5206
                        return nil, err
×
5207
                }
×
5208

5209
                return netann.ExtractChannelUpdate(
×
5210
                        ourPubKey[:], info, edge1, edge2,
×
5211
                )
×
5212
        }
5213
}
5214

5215
// applyChannelUpdate applies the channel update to the different sub-systems of
5216
// the server. The useAlias boolean denotes whether or not to send an alias in
5217
// place of the real SCID.
5218
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5219
        op *wire.OutPoint, useAlias bool) error {
×
5220

×
5221
        var (
×
5222
                peerAlias    *lnwire.ShortChannelID
×
5223
                defaultAlias lnwire.ShortChannelID
×
5224
        )
×
5225

×
5226
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
5227

×
5228
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
5229
        // in the ChannelUpdate if it hasn't been announced yet.
×
5230
        if useAlias {
×
5231
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
5232
                if foundAlias != defaultAlias {
×
5233
                        peerAlias = &foundAlias
×
5234
                }
×
5235
        }
5236

5237
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
5238
                update, discovery.RemoteAlias(peerAlias),
×
5239
        )
×
5240
        select {
×
5241
        case err := <-errChan:
×
5242
                return err
×
5243
        case <-s.quit:
×
5244
                return ErrServerShuttingDown
×
5245
        }
5246
}
5247

5248
// SendCustomMessage sends a custom message to the peer with the specified
5249
// pubkey.
5250
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5251
        data []byte) error {
×
5252

×
5253
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5254
        if err != nil {
×
5255
                return err
×
5256
        }
×
5257

5258
        // We'll wait until the peer is active.
5259
        select {
×
5260
        case <-peer.ActiveSignal():
×
5261
        case <-peer.QuitSignal():
×
5262
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5263
        case <-s.quit:
×
5264
                return ErrServerShuttingDown
×
5265
        }
5266

5267
        msg, err := lnwire.NewCustom(msgType, data)
×
5268
        if err != nil {
×
5269
                return err
×
5270
        }
×
5271

5272
        // Send the message as low-priority. For now we assume that all
5273
        // application-defined message are low priority.
5274
        return peer.SendMessageLazy(true, msg)
×
5275
}
5276

5277
// newSweepPkScriptGen creates closure that generates a new public key script
5278
// which should be used to sweep any funds into the on-chain wallet.
5279
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5280
// (p2wkh) output.
5281
func newSweepPkScriptGen(
5282
        wallet lnwallet.WalletController,
5283
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
5284

×
5285
        return func() fn.Result[lnwallet.AddrWithKey] {
×
5286
                sweepAddr, err := wallet.NewAddress(
×
5287
                        lnwallet.TaprootPubkey, false,
×
5288
                        lnwallet.DefaultAccountName,
×
5289
                )
×
5290
                if err != nil {
×
5291
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5292
                }
×
5293

5294
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
5295
                if err != nil {
×
5296
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5297
                }
×
5298

5299
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
5300
                        wallet, netParams, addr,
×
5301
                )
×
5302
                if err != nil {
×
5303
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5304
                }
×
5305

5306
                return fn.Ok(lnwallet.AddrWithKey{
×
5307
                        DeliveryAddress: addr,
×
5308
                        InternalKey:     internalKeyDesc,
×
5309
                })
×
5310
        }
5311
}
5312

5313
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5314
// finished.
5315
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
5316
        // Get a list of closed channels.
×
5317
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
5318
        if err != nil {
×
5319
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5320
                return nil
×
5321
        }
×
5322

5323
        // Save the SCIDs in a map.
5324
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5325
        for _, c := range channels {
×
5326
                // If the channel is not pending, its FC has been finalized.
×
5327
                if !c.IsPending {
×
5328
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
5329
                }
×
5330
        }
5331

5332
        // Double check whether the reported closed channel has indeed finished
5333
        // closing.
5334
        //
5335
        // NOTE: There are misalignments regarding when a channel's FC is
5336
        // marked as finalized. We double check the pending channels to make
5337
        // sure the returned SCIDs are indeed terminated.
5338
        //
5339
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5340
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
5341
        if err != nil {
×
5342
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5343
                return nil
×
5344
        }
×
5345

5346
        for _, c := range pendings {
×
5347
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5348
                        continue
×
5349
                }
5350

5351
                // If the channel is still reported as pending, remove it from
5352
                // the map.
5353
                delete(closedSCIDs, c.ShortChannelID)
×
5354

×
5355
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5356
                        c.ShortChannelID)
×
5357
        }
5358

5359
        return closedSCIDs
×
5360
}
5361

5362
// getStartingBeat returns the current beat. This is used during the startup to
5363
// initialize blockbeat consumers.
5364
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
5365
        // beat is the current blockbeat.
×
5366
        var beat *chainio.Beat
×
5367

×
5368
        // If the node is configured with nochainbackend mode (remote signer),
×
5369
        // we will skip fetching the best block.
×
5370
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5371
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5372
                        "mode")
×
5373

×
5374
                return &chainio.Beat{}, nil
×
5375
        }
×
5376

5377
        // We should get a notification with the current best block immediately
5378
        // by passing a nil block.
5379
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
5380
        if err != nil {
×
5381
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5382
        }
×
5383
        defer blockEpochs.Cancel()
×
5384

×
5385
        // We registered for the block epochs with a nil request. The notifier
×
5386
        // should send us the current best block immediately. So we need to
×
5387
        // wait for it here because we need to know the current best height.
×
5388
        select {
×
5389
        case bestBlock := <-blockEpochs.Epochs:
×
5390
                srvrLog.Infof("Received initial block %v at height %d",
×
5391
                        bestBlock.Hash, bestBlock.Height)
×
5392

×
5393
                // Update the current blockbeat.
×
5394
                beat = chainio.NewBeat(*bestBlock)
×
5395

5396
        case <-s.quit:
×
5397
                srvrLog.Debug("LND shutting down")
×
5398
        }
5399

5400
        return beat, nil
×
5401
}
5402

5403
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5404
// point has an active RBF chan closer.
5405
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5406
        chanPoint wire.OutPoint) bool {
×
5407

×
5408
        pubBytes := peerPub.SerializeCompressed()
×
5409

×
5410
        s.mu.RLock()
×
5411
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
5412
        s.mu.RUnlock()
×
5413
        if !ok {
×
5414
                return false
×
5415
        }
×
5416

5417
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5418
}
5419

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

×
5428
        // First, we'll attempt to look up the channel based on it's
×
5429
        // ChannelPoint.
×
5430
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
5431
        if err != nil {
×
5432
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5433
        }
×
5434

5435
        // From the channel, we can now get the pubkey of the peer, then use
5436
        // that to eventually get the chan closer.
5437
        peerPub := channel.IdentityPub.SerializeCompressed()
×
5438

×
5439
        // Now that we have the peer pub, we can look up the peer itself.
×
5440
        s.mu.RLock()
×
5441
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
5442
        s.mu.RUnlock()
×
5443
        if !ok {
×
5444
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5445
                        "not online", chanPoint)
×
5446
        }
×
5447

5448
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
5449
                ctx, chanPoint, feeRate, deliveryScript,
×
5450
        )
×
5451
        if err != nil {
×
5452
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5453
                        "%w", err)
×
5454
        }
×
5455

5456
        return closeUpdates, nil
×
5457
}
5458

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

×
5467
        // If the channel is present in the switch, then the request should flow
×
5468
        // through the switch instead.
×
5469
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
5470
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5471
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5472
                        "invalid request", chanPoint)
×
5473
        }
×
5474

5475
        // At this point, we know that the channel isn't present in the link, so
5476
        // we'll check to see if we have an entry in the active chan closer map.
5477
        updates, err := s.attemptCoopRbfFeeBump(
×
5478
                ctx, chanPoint, feeRate, deliveryScript,
×
5479
        )
×
5480
        if err != nil {
×
5481
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5482
                        "ChannelPoint(%v)", chanPoint)
×
5483
        }
×
5484

5485
        return updates, nil
×
5486
}
5487

5488
// setSelfNode configures and sets the server's self node. It sets the node
5489
// announcement, signs it, and updates the source node in the graph. When
5490
// determining values such as color and alias, the method prioritizes values
5491
// set in the config, then values previously persisted on disk, and finally
5492
// falls back to the defaults.
5493
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5494
        listenAddrs []net.Addr) error {
×
5495

×
5496
        // If we were requested to automatically configure port forwarding,
×
5497
        // we'll use the ports that the server will be listening on.
×
5498
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
×
5499
        for _, ip := range s.cfg.ExternalIPs {
×
5500
                externalIPStrings = append(externalIPStrings, ip.String())
×
5501
        }
×
5502
        if s.natTraversal != nil {
×
5503
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5504
                for _, listenAddr := range listenAddrs {
×
5505
                        // At this point, the listen addresses should have
×
5506
                        // already been normalized, so it's safe to ignore the
×
5507
                        // errors.
×
5508
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5509
                        port, _ := strconv.Atoi(portStr)
×
5510

×
5511
                        listenPorts = append(listenPorts, uint16(port))
×
5512
                }
×
5513

5514
                ips, err := s.configurePortForwarding(listenPorts...)
×
5515
                if err != nil {
×
5516
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5517
                                "forwarding using %s: %v",
×
5518
                                s.natTraversal.Name(), err)
×
5519
                } else {
×
5520
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5521
                                "using %s to advertise external IP",
×
5522
                                s.natTraversal.Name())
×
5523
                        externalIPStrings = append(externalIPStrings, ips...)
×
5524
                }
×
5525
        }
5526

5527
        // Normalize the external IP strings to net.Addr.
5528
        addrs, err := lncfg.NormalizeAddresses(
×
5529
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
5530
                s.cfg.net.ResolveTCPAddr,
×
5531
        )
×
5532
        if err != nil {
×
5533
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5534
        }
×
5535

5536
        // Parse the color from config. We will update this later if the config
5537
        // color is not changed from default (#3399FF) and we have a value in
5538
        // the source node.
5539
        color, err := lncfg.ParseHexColor(s.cfg.Color)
×
5540
        if err != nil {
×
5541
                return fmt.Errorf("unable to parse color: %w", err)
×
5542
        }
×
5543

5544
        var (
×
5545
                alias          = s.cfg.Alias
×
5546
                nodeLastUpdate = time.Now()
×
5547
        )
×
5548

×
5549
        srcNode, err := s.graphDB.SourceNode(ctx)
×
5550
        switch {
×
5551
        case err == nil:
×
5552
                // If we have a source node persisted in the DB already, then we
×
5553
                // just need to make sure that the new LastUpdate time is at
×
5554
                // least one second after the last update time.
×
5555
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
5556
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
5557
                }
×
5558

5559
                // If the color is not changed from default, it means that we
5560
                // didn't specify a different color in the config. We'll use the
5561
                // source node's color.
5562
                if s.cfg.Color == defaultColor {
×
5563
                        color = srcNode.Color
×
5564
                }
×
5565

5566
                // If an alias is not specified in the config, we'll use the
5567
                // source node's alias.
5568
                if alias == "" {
×
5569
                        alias = srcNode.Alias
×
5570
                }
×
5571

5572
                // If the `externalip` is not specified in the config, it means
5573
                // `addrs` will be empty, we'll use the source node's addresses.
5574
                if len(s.cfg.ExternalIPs) == 0 {
×
5575
                        addrs = srcNode.Addresses
×
5576
                }
×
5577

5578
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
5579
                // If an alias is not specified in the config, we'll use the
×
5580
                // default, which is the first 10 bytes of the serialized
×
5581
                // pubkey.
×
5582
                if alias == "" {
×
5583
                        alias = hex.EncodeToString(nodePub[:10])
×
5584
                }
×
5585

5586
        // If the above cases are not matched, then we have an unhandled non
5587
        // nil error.
5588
        default:
×
5589
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5590
        }
5591

5592
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
5593
        if err != nil {
×
5594
                return err
×
5595
        }
×
5596

5597
        // TODO(abdulkbk): potentially find a way to use the source node's
5598
        // features in the self node.
5599
        selfNode := &models.Node{
×
5600
                HaveNodeAnnouncement: true,
×
5601
                LastUpdate:           nodeLastUpdate,
×
5602
                Addresses:            addrs,
×
5603
                Alias:                nodeAlias.String(),
×
5604
                Color:                color,
×
5605
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
5606
        }
×
5607

×
5608
        copy(selfNode.PubKeyBytes[:], nodePub[:])
×
5609

×
5610
        // Based on the disk representation of the node announcement generated
×
5611
        // above, we'll generate a node announcement that can go out on the
×
5612
        // network so we can properly sign it.
×
5613
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
5614
        if err != nil {
×
5615
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5616
        }
×
5617

5618
        // With the announcement generated, we'll sign it to properly
5619
        // authenticate the message on the network.
5620
        authSig, err := netann.SignAnnouncement(
×
5621
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
×
5622
        )
×
5623
        if err != nil {
×
5624
                return fmt.Errorf("unable to generate signature for self node "+
×
5625
                        "announcement: %v", err)
×
5626
        }
×
5627

5628
        selfNode.AuthSigBytes = authSig.Serialize()
×
5629
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
5630
                selfNode.AuthSigBytes,
×
5631
        )
×
5632
        if err != nil {
×
5633
                return err
×
5634
        }
×
5635

5636
        // Finally, we'll update the representation on disk, and update our
5637
        // cached in-memory version as well.
5638
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
5639
                return fmt.Errorf("can't set self node: %w", err)
×
5640
        }
×
5641

5642
        s.currentNodeAnn = nodeAnn
×
5643

×
5644
        return nil
×
5645
}
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