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

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 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.NodeAnnouncement
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
        // Start the low-level services once they are initialized.
×
737
        //
×
738
        // TODO(yy): break the server startup into four steps,
×
739
        // 1. init the low-level services.
×
740
        // 2. start the low-level services.
×
741
        // 3. init the high-level services.
×
742
        // 4. start the high-level services.
×
743
        if err := s.startLowLevelServices(); err != nil {
×
744
                return nil, err
×
745
        }
×
746

747
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
748
        if err != nil {
×
749
                return nil, err
×
750
        }
×
751

752
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
753
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
754
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
755
        )
×
756
        s.invoices = invoices.NewRegistry(
×
757
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
758
        )
×
759

×
760
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
761

×
762
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
763
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
764

×
765
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
766
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
767
                if err != nil {
×
768
                        return err
×
769
                }
×
770

771
                s.htlcSwitch.UpdateLinkAliases(link)
×
772

×
773
                return nil
×
774
        }
775

776
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
777
        if err != nil {
×
778
                return nil, err
×
779
        }
×
780

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

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

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

833
        s.witnessBeacon = newPreimageBeacon(
×
834
                dbs.ChanStateDB.NewWitnessCache(),
×
835
                s.interceptableSwitch.ForwardPacket,
×
836
        )
×
837

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

×
851
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
852
        if err != nil {
×
853
                return nil, err
×
854
        }
×
855
        s.chanStatusMgr = chanStatusMgr
×
856

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

×
862
                discoveryTimeout := time.Duration(10 * time.Second)
×
863

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

×
878
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
879
                                "enabled device")
×
880

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

890
                        s.natTraversal = pmp
×
891
                }
892
        }
893

894
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
×
895
        // Set the self node which represents our node in the graph.
×
896
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
×
897
        if err != nil {
×
898
                return nil, err
×
899
        }
×
900

901
        // The router will get access to the payment ID sequencer, such that it
902
        // can generate unique payment IDs.
903
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
904
        if err != nil {
×
905
                return nil, err
×
906
        }
×
907

908
        // Instantiate mission control with config from the sub server.
909
        //
910
        // TODO(joostjager): When we are further in the process of moving to sub
911
        // servers, the mission control instance itself can be moved there too.
912
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
913

×
914
        // We only initialize a probability estimator if there's no custom one.
×
915
        var estimator routing.Estimator
×
916
        if cfg.Estimator != nil {
×
917
                estimator = cfg.Estimator
×
918
        } else {
×
919
                switch routingConfig.ProbabilityEstimatorType {
×
920
                case routing.AprioriEstimatorName:
×
921
                        aCfg := routingConfig.AprioriConfig
×
922
                        aprioriConfig := routing.AprioriConfig{
×
923
                                AprioriHopProbability: aCfg.HopProbability,
×
924
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
925
                                AprioriWeight:         aCfg.Weight,
×
926
                                CapacityFraction:      aCfg.CapacityFraction,
×
927
                        }
×
928

×
929
                        estimator, err = routing.NewAprioriEstimator(
×
930
                                aprioriConfig,
×
931
                        )
×
932
                        if err != nil {
×
933
                                return nil, err
×
934
                        }
×
935

936
                case routing.BimodalEstimatorName:
×
937
                        bCfg := routingConfig.BimodalConfig
×
938
                        bimodalConfig := routing.BimodalConfig{
×
939
                                BimodalNodeWeight: bCfg.NodeWeight,
×
940
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
941
                                        bCfg.Scale,
×
942
                                ),
×
943
                                BimodalDecayTime: bCfg.DecayTime,
×
944
                        }
×
945

×
946
                        estimator, err = routing.NewBimodalEstimator(
×
947
                                bimodalConfig,
×
948
                        )
×
949
                        if err != nil {
×
950
                                return nil, err
×
951
                        }
×
952

953
                default:
×
954
                        return nil, fmt.Errorf("unknown estimator type %v",
×
955
                                routingConfig.ProbabilityEstimatorType)
×
956
                }
957
        }
958

959
        mcCfg := &routing.MissionControlConfig{
×
960
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
961
                Estimator:               estimator,
×
962
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
963
                McFlushInterval:         routingConfig.McFlushInterval,
×
964
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
965
        }
×
966

×
967
        s.missionController, err = routing.NewMissionController(
×
968
                dbs.ChanStateDB, nodePubKey, mcCfg,
×
969
        )
×
970
        if err != nil {
×
971
                return nil, fmt.Errorf("can't create mission control "+
×
972
                        "manager: %w", err)
×
973
        }
×
974
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
975
                routing.DefaultMissionControlNamespace,
×
976
        )
×
977
        if err != nil {
×
978
                return nil, fmt.Errorf("can't create mission control in the "+
×
979
                        "default namespace: %w", err)
×
980
        }
×
981

982
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
983
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
984
                int64(routingConfig.AttemptCost),
×
985
                float64(routingConfig.AttemptCostPPM)/10000,
×
986
                routingConfig.MinRouteProbability)
×
987

×
988
        pathFindingConfig := routing.PathFindingConfig{
×
989
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
990
                        routingConfig.AttemptCost,
×
991
                ),
×
992
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
993
                MinProbability: routingConfig.MinRouteProbability,
×
994
        }
×
995

×
996
        sourceNode, err := dbs.GraphDB.SourceNode(ctx)
×
997
        if err != nil {
×
998
                return nil, fmt.Errorf("error getting source node: %w", err)
×
999
        }
×
1000
        paymentSessionSource := &routing.SessionSource{
×
1001
                GraphSessionFactory: dbs.GraphDB,
×
1002
                SourceNode:          sourceNode,
×
1003
                MissionControl:      s.defaultMC,
×
1004
                GetLink:             s.htlcSwitch.GetLinkByShortID,
×
1005
                PathFindingConfig:   pathFindingConfig,
×
1006
        }
×
1007

×
1008
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
×
1009

×
1010
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
1011
                cfg.Routing.StrictZombiePruning
×
1012

×
1013
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
1014
                SelfNode:            nodePubKey,
×
1015
                Graph:               dbs.GraphDB,
×
1016
                Chain:               cc.ChainIO,
×
1017
                ChainView:           cc.ChainView,
×
1018
                Notifier:            cc.ChainNotifier,
×
1019
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
1020
                GraphPruneInterval:  time.Hour,
×
1021
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
1022
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
1023
                StrictZombiePruning: strictPruning,
×
1024
                IsAlias:             aliasmgr.IsAlias,
×
1025
        })
×
1026
        if err != nil {
×
1027
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1028
        }
×
1029

1030
        s.chanRouter, err = routing.New(routing.Config{
×
1031
                SelfNode:           nodePubKey,
×
1032
                RoutingGraph:       dbs.GraphDB,
×
1033
                Chain:              cc.ChainIO,
×
1034
                Payer:              s.htlcSwitch,
×
1035
                Control:            s.controlTower,
×
1036
                MissionControl:     s.defaultMC,
×
1037
                SessionSource:      paymentSessionSource,
×
1038
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
1039
                NextPaymentID:      sequencer.NextID,
×
1040
                PathFindingConfig:  pathFindingConfig,
×
1041
                Clock:              clock.NewDefaultClock(),
×
1042
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
1043
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
1044
                TrafficShaper:      implCfg.TrafficShaper,
×
1045
        })
×
1046
        if err != nil {
×
1047
                return nil, fmt.Errorf("can't create router: %w", err)
×
1048
        }
×
1049

1050
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
1051
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
1052
        if err != nil {
×
1053
                return nil, err
×
1054
        }
×
1055
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
1056
        if err != nil {
×
1057
                return nil, err
×
1058
        }
×
1059

1060
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
1061

×
1062
        s.authGossiper = discovery.New(discovery.Config{
×
1063
                Graph:                 s.graphBuilder,
×
1064
                ChainIO:               s.cc.ChainIO,
×
1065
                Notifier:              s.cc.ChainNotifier,
×
1066
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
1067
                Broadcast:             s.BroadcastMessage,
×
1068
                ChanSeries:            chanSeries,
×
1069
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
1070
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
1071
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
1072
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
1073
                        error) {
×
1074

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

1109
        accessCfg := &accessManConfig{
×
1110
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
1111
                        error) {
×
1112

×
1113
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
1114
                        return s.chanStateDB.FetchPermAndTempPeers(
×
1115
                                genesisHash[:],
×
1116
                        )
×
1117
                },
×
1118
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1119
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1120
        }
1121

1122
        peerAccessMan, err := newAccessMan(accessCfg)
×
1123
        if err != nil {
×
1124
                return nil, err
×
1125
        }
×
1126

1127
        s.peerAccessMan = peerAccessMan
×
1128

×
1129
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
1130
        //nolint:ll
×
1131
        s.localChanMgr = &localchans.Manager{
×
1132
                SelfPub:              nodeKeyDesc.PubKey,
×
1133
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
1134
                ForAllOutgoingChannels: func(ctx context.Context,
×
1135
                        cb func(*models.ChannelEdgeInfo,
×
1136
                                *models.ChannelEdgePolicy) error,
×
1137
                        reset func()) error {
×
1138

×
1139
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
1140
                                func(c *models.ChannelEdgeInfo,
×
1141
                                        e *models.ChannelEdgePolicy,
×
1142
                                        _ *models.ChannelEdgePolicy) error {
×
1143

×
1144
                                        // NOTE: The invoked callback here may
×
1145
                                        // receive a nil channel policy.
×
1146
                                        return cb(c, e)
×
1147
                                }, reset,
×
1148
                        )
1149
                },
1150
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1151
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1152
                FetchChannel:              s.chanStateDB.FetchChannel,
1153
                AddEdge: func(ctx context.Context,
1154
                        edge *models.ChannelEdgeInfo) error {
×
1155

×
1156
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1157
                },
×
1158
        }
1159

1160
        utxnStore, err := contractcourt.NewNurseryStore(
×
1161
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
1162
        )
×
1163
        if err != nil {
×
1164
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1165
                return nil, err
×
1166
        }
×
1167

1168
        sweeperStore, err := sweep.NewSweeperStore(
×
1169
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
1170
        )
×
1171
        if err != nil {
×
1172
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1173
                return nil, err
×
1174
        }
×
1175

1176
        aggregator := sweep.NewBudgetAggregator(
×
1177
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
1178
                s.implCfg.AuxSweeper,
×
1179
        )
×
1180

×
1181
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1182
                Signer:     cc.Wallet.Cfg.Signer,
×
1183
                Wallet:     cc.Wallet,
×
1184
                Estimator:  cc.FeeEstimator,
×
1185
                Notifier:   cc.ChainNotifier,
×
1186
                AuxSweeper: s.implCfg.AuxSweeper,
×
1187
        })
×
1188

×
1189
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
1190
                FeeEstimator: cc.FeeEstimator,
×
1191
                GenSweepScript: newSweepPkScriptGen(
×
1192
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1193
                ),
×
1194
                Signer:               cc.Wallet.Cfg.Signer,
×
1195
                Wallet:               newSweeperWallet(cc.Wallet),
×
1196
                Mempool:              cc.MempoolNotifier,
×
1197
                Notifier:             cc.ChainNotifier,
×
1198
                Store:                sweeperStore,
×
1199
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
1200
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
1201
                Aggregator:           aggregator,
×
1202
                Publisher:            s.txPublisher,
×
1203
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
1204
        })
×
1205

×
1206
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
1207
                ChainIO:             cc.ChainIO,
×
1208
                ConfDepth:           1,
×
1209
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
1210
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
1211
                Notifier:            cc.ChainNotifier,
×
1212
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
1213
                Store:               utxnStore,
×
1214
                SweepInput:          s.sweeper.SweepInput,
×
1215
                Budget:              s.cfg.Sweeper.Budget,
×
1216
        })
×
1217

×
1218
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
1219
        closeLink := func(chanPoint *wire.OutPoint,
×
1220
                closureType contractcourt.ChannelCloseType) {
×
1221
                // TODO(conner): Properly respect the update and error channels
×
1222
                // returned by CloseLink.
×
1223

×
1224
                // Instruct the switch to close the channel.  Provide no close out
×
1225
                // delivery script or target fee per kw because user input is not
×
1226
                // available when the remote peer closes the channel.
×
1227
                s.htlcSwitch.CloseLink(
×
1228
                        context.Background(), chanPoint, closureType, 0, 0, nil,
×
1229
                )
×
1230
        }
×
1231

1232
        // We will use the following channel to reliably hand off contract
1233
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1234
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
×
1235

×
1236
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
1237
                &contractcourt.BreachConfig{
×
1238
                        CloseLink: closeLink,
×
1239
                        DB:        s.chanStateDB,
×
1240
                        Estimator: s.cc.FeeEstimator,
×
1241
                        GenSweepScript: newSweepPkScriptGen(
×
1242
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
1243
                        ),
×
1244
                        Notifier:           cc.ChainNotifier,
×
1245
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
1246
                        ContractBreaches:   contractBreaches,
×
1247
                        Signer:             cc.Wallet.Cfg.Signer,
×
1248
                        Store: contractcourt.NewRetributionStore(
×
1249
                                dbs.ChanStateDB,
×
1250
                        ),
×
1251
                        AuxSweeper: s.implCfg.AuxSweeper,
×
1252
                },
×
1253
        )
×
1254

×
1255
        //nolint:ll
×
1256
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
1257
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
1258
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
1259
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
1260
                NewSweepAddr: func() ([]byte, error) {
×
1261
                        addr, err := newSweepPkScriptGen(
×
1262
                                cc.Wallet, netParams,
×
1263
                        )().Unpack()
×
1264
                        if err != nil {
×
1265
                                return nil, err
×
1266
                        }
×
1267

1268
                        return addr.DeliveryAddress, nil
×
1269
                },
1270
                PublishTx: cc.Wallet.PublishTransaction,
1271
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
1272
                        for _, msg := range msgs {
×
1273
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
1274
                                if err != nil {
×
1275
                                        return err
×
1276
                                }
×
1277
                        }
1278
                        return nil
×
1279
                },
1280
                IncubateOutputs: func(chanPoint wire.OutPoint,
1281
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1282
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1283
                        broadcastHeight uint32,
1284
                        deadlineHeight fn.Option[int32]) error {
×
1285

×
1286
                        return s.utxoNursery.IncubateOutputs(
×
1287
                                chanPoint, outHtlcRes, inHtlcRes,
×
1288
                                broadcastHeight, deadlineHeight,
×
1289
                        )
×
1290
                },
×
1291
                PreimageDB:   s.witnessBeacon,
1292
                Notifier:     cc.ChainNotifier,
1293
                Mempool:      cc.MempoolNotifier,
1294
                Signer:       cc.Wallet.Cfg.Signer,
1295
                FeeEstimator: cc.FeeEstimator,
1296
                ChainIO:      cc.ChainIO,
1297
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
1298
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1299
                        s.htlcSwitch.RemoveLink(chanID)
×
1300
                        return nil
×
1301
                },
×
1302
                IsOurAddress: cc.Wallet.IsOurAddress,
1303
                ContractBreach: func(chanPoint wire.OutPoint,
1304
                        breachRet *lnwallet.BreachRetribution) error {
×
1305

×
1306
                        // processACK will handle the BreachArbitrator ACKing
×
1307
                        // the event.
×
1308
                        finalErr := make(chan error, 1)
×
1309
                        processACK := func(brarErr error) {
×
1310
                                if brarErr != nil {
×
1311
                                        finalErr <- brarErr
×
1312
                                        return
×
1313
                                }
×
1314

1315
                                // If the BreachArbitrator successfully handled
1316
                                // the event, we can signal that the handoff
1317
                                // was successful.
1318
                                finalErr <- nil
×
1319
                        }
1320

1321
                        event := &contractcourt.ContractBreachEvent{
×
1322
                                ChanPoint:         chanPoint,
×
1323
                                ProcessACK:        processACK,
×
1324
                                BreachRetribution: breachRet,
×
1325
                        }
×
1326

×
1327
                        // Send the contract breach event to the
×
1328
                        // BreachArbitrator.
×
1329
                        select {
×
1330
                        case contractBreaches <- event:
×
1331
                        case <-s.quit:
×
1332
                                return ErrServerShuttingDown
×
1333
                        }
1334

1335
                        // We'll wait for a final error to be available from
1336
                        // the BreachArbitrator.
1337
                        select {
×
1338
                        case err := <-finalErr:
×
1339
                                return err
×
1340
                        case <-s.quit:
×
1341
                                return ErrServerShuttingDown
×
1342
                        }
1343
                },
1344
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
1345
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
1346
                },
×
1347
                Sweeper:                       s.sweeper,
1348
                Registry:                      s.invoices,
1349
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1350
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1351
                OnionProcessor:                s.sphinx,
1352
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1353
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1354
                Clock:                         clock.NewDefaultClock(),
1355
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1356
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1357
                HtlcNotifier:                  s.htlcNotifier,
1358
                Budget:                        *s.cfg.Sweeper.Budget,
1359

1360
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1361
                QueryIncomingCircuit: func(
1362
                        circuit models.CircuitKey) *models.CircuitKey {
×
1363

×
1364
                        // Get the circuit map.
×
1365
                        circuits := s.htlcSwitch.CircuitLookup()
×
1366

×
1367
                        // Lookup the outgoing circuit.
×
1368
                        pc := circuits.LookupOpenCircuit(circuit)
×
1369
                        if pc == nil {
×
1370
                                return nil
×
1371
                        }
×
1372

1373
                        return &pc.Incoming
×
1374
                },
1375
                AuxLeafStore: implCfg.AuxLeafStore,
1376
                AuxSigner:    implCfg.AuxSigner,
1377
                AuxResolver:  implCfg.AuxContractResolver,
1378
        }, dbs.ChanStateDB)
1379

1380
        // Select the configuration and funding parameters for Bitcoin.
1381
        chainCfg := cfg.Bitcoin
×
1382
        minRemoteDelay := funding.MinBtcRemoteDelay
×
1383
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
1384

×
1385
        var chanIDSeed [32]byte
×
1386
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1387
                return nil, err
×
1388
        }
×
1389

1390
        // Wrap the DeleteChannelEdges method so that the funding manager can
1391
        // use it without depending on several layers of indirection.
1392
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
1393
                *models.ChannelEdgePolicy, error) {
×
1394

×
1395
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
1396
                        scid.ToUint64(),
×
1397
                )
×
1398
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
1399
                        // This is unlikely but there is a slim chance of this
×
1400
                        // being hit if lnd was killed via SIGKILL and the
×
1401
                        // funding manager was stepping through the delete
×
1402
                        // alias edge logic.
×
1403
                        return nil, nil
×
1404
                } else if err != nil {
×
1405
                        return nil, err
×
1406
                }
×
1407

1408
                // Grab our key to find our policy.
1409
                var ourKey [33]byte
×
1410
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1411

×
1412
                var ourPolicy *models.ChannelEdgePolicy
×
1413
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1414
                        ourPolicy = e1
×
1415
                } else {
×
1416
                        ourPolicy = e2
×
1417
                }
×
1418

1419
                if ourPolicy == nil {
×
1420
                        // Something is wrong, so return an error.
×
1421
                        return nil, fmt.Errorf("we don't have an edge")
×
1422
                }
×
1423

1424
                err = s.graphDB.DeleteChannelEdges(
×
1425
                        false, false, scid.ToUint64(),
×
1426
                )
×
1427
                return ourPolicy, err
×
1428
        }
1429

1430
        // For the reservationTimeout and the zombieSweeperInterval different
1431
        // values are set in case we are in a dev environment so enhance test
1432
        // capacilities.
1433
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
1434
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
1435

×
1436
        // Get the development config for funding manager. If we are not in
×
1437
        // development mode, this would be nil.
×
1438
        var devCfg *funding.DevConfig
×
1439
        if lncfg.IsDevBuild() {
×
1440
                devCfg = &funding.DevConfig{
×
1441
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
1442
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
×
1443
                                GetMaxWaitNumBlocksFundingConf(),
×
1444
                }
×
1445

×
1446
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
1447
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
1448

×
1449
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1450
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1451
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
1452
        }
×
1453

1454
        //nolint:ll
1455
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
1456
                Dev:                devCfg,
×
1457
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
1458
                IDKey:              nodeKeyDesc.PubKey,
×
1459
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
1460
                Wallet:             cc.Wallet,
×
1461
                PublishTransaction: cc.Wallet.PublishTransaction,
×
1462
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
1463
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
1464
                },
×
1465
                Notifier:     cc.ChainNotifier,
1466
                ChannelDB:    s.chanStateDB,
1467
                FeeEstimator: cc.FeeEstimator,
1468
                SignMessage:  cc.MsgSigner.SignMessage,
1469
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1470
                        error) {
×
1471

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

×
1492
                        // In case the user has explicitly specified
×
1493
                        // a default value for the number of
×
1494
                        // confirmations, we use it.
×
1495
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
1496
                        if defaultConf != 0 {
×
1497
                                return defaultConf
×
1498
                        }
×
1499

1500
                        minConf := uint64(3)
×
1501
                        maxConf := uint64(6)
×
1502

×
1503
                        // If this is a wumbo channel, then we'll require the
×
1504
                        // max amount of confirmations.
×
1505
                        if chanAmt > MaxFundingAmount {
×
1506
                                return uint16(maxConf)
×
1507
                        }
×
1508

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

×
1531
                        // In case the user has explicitly specified
×
1532
                        // a default value for the remote delay, we
×
1533
                        // use it.
×
1534
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
1535
                        if defaultDelay > 0 {
×
1536
                                return defaultDelay
×
1537
                        }
×
1538

1539
                        // If this is a wumbo channel, then we'll require the
1540
                        // max value.
1541
                        if chanAmt > MaxFundingAmount {
×
1542
                                return maxRemoteDelay
×
1543
                        }
×
1544

1545
                        // If not we scale according to channel size.
1546
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1547
                                chanAmt / MaxFundingAmount)
×
1548
                        if delay < minRemoteDelay {
×
1549
                                delay = minRemoteDelay
×
1550
                        }
×
1551
                        if delay > maxRemoteDelay {
×
1552
                                delay = maxRemoteDelay
×
1553
                        }
×
1554
                        return delay
×
1555
                },
1556
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1557
                        peerKey *btcec.PublicKey) error {
×
1558

×
1559
                        // First, we'll mark this new peer as a persistent peer
×
1560
                        // for re-connection purposes. If the peer is not yet
×
1561
                        // tracked or the user hasn't requested it to be perm,
×
1562
                        // we'll set false to prevent the server from continuing
×
1563
                        // to connect to this peer even if the number of
×
1564
                        // channels with this peer is zero.
×
1565
                        s.mu.Lock()
×
1566
                        pubStr := string(peerKey.SerializeCompressed())
×
1567
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
1568
                                s.persistentPeers[pubStr] = false
×
1569
                        }
×
1570
                        s.mu.Unlock()
×
1571

×
1572
                        // With that taken care of, we'll send this channel to
×
1573
                        // the chain arb so it can react to on-chain events.
×
1574
                        return s.chainArb.WatchNewChannel(channel)
×
1575
                },
1576
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
1577
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
1578
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
1579
                },
×
1580
                RequiredRemoteChanReserve: func(chanAmt,
1581
                        dustLimit btcutil.Amount) btcutil.Amount {
×
1582

×
1583
                        // By default, we'll require the remote peer to maintain
×
1584
                        // at least 1% of the total channel capacity at all
×
1585
                        // times. If this value ends up dipping below the dust
×
1586
                        // limit, then we'll use the dust limit itself as the
×
1587
                        // reserve as required by BOLT #2.
×
1588
                        reserve := chanAmt / 100
×
1589
                        if reserve < dustLimit {
×
1590
                                reserve = dustLimit
×
1591
                        }
×
1592

1593
                        return reserve
×
1594
                },
1595
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
1596
                        // By default, we'll allow the remote peer to fully
×
1597
                        // utilize the full bandwidth of the channel, minus our
×
1598
                        // required reserve.
×
1599
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
1600
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
1601
                },
×
1602
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
1603
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
1604
                                return cfg.DefaultRemoteMaxHtlcs
×
1605
                        }
×
1606

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

1636
        // Next, we'll assemble the sub-system that will maintain an on-disk
1637
        // static backup of the latest channel state.
1638
        chanNotifier := &channelNotifier{
×
1639
                chanNotifier: s.channelNotifier,
×
1640
                addrs:        s.addrSource,
×
1641
        }
×
1642
        backupFile := chanbackup.NewMultiFile(
×
1643
                cfg.BackupFilePath, cfg.NoBackupArchive,
×
1644
        )
×
1645
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
1646
                ctx, s.chanStateDB, s.addrSource,
×
1647
        )
×
1648
        if err != nil {
×
1649
                return nil, err
×
1650
        }
×
1651
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
1652
                ctx, startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
1653
        )
×
1654
        if err != nil {
×
1655
                return nil, err
×
1656
        }
×
1657

1658
        // Assemble a peer notifier which will provide clients with subscriptions
1659
        // to peer online and offline events.
1660
        s.peerNotifier = peernotifier.New()
×
1661

×
1662
        // Create a channel event store which monitors all open channels.
×
1663
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
1664
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
1665
                        return s.channelNotifier.SubscribeChannelEvents()
×
1666
                },
×
1667
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
1668
                        return s.peerNotifier.SubscribePeerEvents()
×
1669
                },
×
1670
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1671
                Clock:           clock.NewDefaultClock(),
1672
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1673
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1674
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1675
        })
1676

1677
        if cfg.WtClient.Active {
×
1678
                policy := wtpolicy.DefaultPolicy()
×
1679
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
1680

×
1681
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1682
                // protocol operations on sat/kw.
×
1683
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
1684
                        1000 * cfg.WtClient.SweepFeeRate,
×
1685
                )
×
1686

×
1687
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1688

×
1689
                if err := policy.Validate(); err != nil {
×
1690
                        return nil, err
×
1691
                }
×
1692

1693
                // authDial is the wrapper around the btrontide.Dial for the
1694
                // watchtower.
1695
                authDial := func(localKey keychain.SingleKeyECDH,
×
1696
                        netAddr *lnwire.NetAddress,
×
1697
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
1698

×
1699
                        return brontide.Dial(
×
1700
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1701
                        )
×
1702
                }
×
1703

1704
                // buildBreachRetribution is a call-back that can be used to
1705
                // query the BreachRetribution info and channel type given a
1706
                // channel ID and commitment height.
1707
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
1708
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
1709
                        channeldb.ChannelType, error) {
×
1710

×
1711
                        channel, err := s.chanStateDB.FetchChannelByID(
×
1712
                                nil, chanID,
×
1713
                        )
×
1714
                        if err != nil {
×
1715
                                return nil, 0, err
×
1716
                        }
×
1717

1718
                        br, err := lnwallet.NewBreachRetribution(
×
1719
                                channel, commitHeight, 0, nil,
×
1720
                                implCfg.AuxLeafStore,
×
1721
                                implCfg.AuxContractResolver,
×
1722
                        )
×
1723
                        if err != nil {
×
1724
                                return nil, 0, err
×
1725
                        }
×
1726

1727
                        return br, channel.ChanType, nil
×
1728
                }
1729

1730
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
1731

×
1732
                // Copy the policy for legacy channels and set the blob flag
×
1733
                // signalling support for anchor channels.
×
1734
                anchorPolicy := policy
×
1735
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1736

×
1737
                // Copy the policy for legacy channels and set the blob flag
×
1738
                // signalling support for taproot channels.
×
1739
                taprootPolicy := policy
×
1740
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
1741
                        blob.FlagTaprootChannel,
×
1742
                )
×
1743

×
1744
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1745
                        FetchClosedChannel:     fetchClosedChannel,
×
1746
                        BuildBreachRetribution: buildBreachRetribution,
×
1747
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
1748
                        ChainNotifier:          s.cc.ChainNotifier,
×
1749
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
1750
                                error) {
×
1751

×
1752
                                return s.channelNotifier.
×
1753
                                        SubscribeChannelEvents()
×
1754
                        },
×
1755
                        Signer: cc.Wallet.Cfg.Signer,
1756
                        NewAddress: func() ([]byte, error) {
×
1757
                                addr, err := newSweepPkScriptGen(
×
1758
                                        cc.Wallet, netParams,
×
1759
                                )().Unpack()
×
1760
                                if err != nil {
×
1761
                                        return nil, err
×
1762
                                }
×
1763

1764
                                return addr.DeliveryAddress, nil
×
1765
                        },
1766
                        SecretKeyRing:      s.cc.KeyRing,
1767
                        Dial:               cfg.net.Dial,
1768
                        AuthDial:           authDial,
1769
                        DB:                 dbs.TowerClientDB,
1770
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1771
                        MinBackoff:         10 * time.Second,
1772
                        MaxBackoff:         5 * time.Minute,
1773
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1774
                }, policy, anchorPolicy, taprootPolicy)
1775
                if err != nil {
×
1776
                        return nil, err
×
1777
                }
×
1778
        }
1779

1780
        if len(cfg.ExternalHosts) != 0 {
×
1781
                advertisedIPs := make(map[string]struct{})
×
1782
                for _, addr := range s.currentNodeAnn.Addresses {
×
1783
                        advertisedIPs[addr.String()] = struct{}{}
×
1784
                }
×
1785

1786
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1787
                        Hosts:         cfg.ExternalHosts,
×
1788
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1789
                        LookupHost: func(host string) (net.Addr, error) {
×
1790
                                return lncfg.ParseAddressString(
×
1791
                                        host, strconv.Itoa(defaultPeerPort),
×
1792
                                        cfg.net.ResolveTCPAddr,
×
1793
                                )
×
1794
                        },
×
1795
                        AdvertisedIPs: advertisedIPs,
1796
                        AnnounceNewIPs: netann.IPAnnouncer(
1797
                                func(modifier ...netann.NodeAnnModifier) (
1798
                                        lnwire.NodeAnnouncement, error) {
×
1799

×
1800
                                        return s.genNodeAnnouncement(
×
1801
                                                nil, modifier...,
×
1802
                                        )
×
1803
                                }),
×
1804
                })
1805
        }
1806

1807
        // Create liveness monitor.
1808
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1809

×
1810
        listeners := make([]net.Listener, len(listenAddrs))
×
1811
        for i, listenAddr := range listenAddrs {
×
1812
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
1813
                // doesn't need to call the general lndResolveTCP function
×
1814
                // since we are resolving a local address.
×
1815

×
1816
                // RESOLVE: We are actually partially accepting inbound
×
1817
                // connection requests when we call NewListener.
×
1818
                listeners[i], err = brontide.NewListener(
×
1819
                        nodeKeyECDH, listenAddr.String(),
×
1820
                        // TODO(yy): remove this check and unify the inbound
×
1821
                        // connection check inside `InboundPeerConnected`.
×
1822
                        s.peerAccessMan.checkAcceptIncomingConn,
×
1823
                )
×
1824
                if err != nil {
×
1825
                        return nil, err
×
1826
                }
×
1827
        }
1828

1829
        // Create the connection manager which will be responsible for
1830
        // maintaining persistent outbound connections and also accepting new
1831
        // incoming connections
1832
        cmgr, err := connmgr.New(&connmgr.Config{
×
1833
                Listeners:      listeners,
×
1834
                OnAccept:       s.InboundPeerConnected,
×
1835
                RetryDuration:  time.Second * 5,
×
1836
                TargetOutbound: 100,
×
1837
                Dial: noiseDial(
×
1838
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
1839
                ),
×
1840
                OnConnection: s.OutboundPeerConnected,
×
1841
        })
×
1842
        if err != nil {
×
1843
                return nil, err
×
1844
        }
×
1845
        s.connMgr = cmgr
×
1846

×
1847
        // Finally, register the subsystems in blockbeat.
×
1848
        s.registerBlockConsumers()
×
1849

×
1850
        return s, nil
×
1851
}
1852

1853
// UpdateRoutingConfig is a callback function to update the routing config
1854
// values in the main cfg.
1855
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1856
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
1857

×
1858
        switch c := cfg.Estimator.Config().(type) {
×
1859
        case routing.AprioriConfig:
×
1860
                routerCfg.ProbabilityEstimatorType =
×
1861
                        routing.AprioriEstimatorName
×
1862

×
1863
                targetCfg := routerCfg.AprioriConfig
×
1864
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
1865
                targetCfg.Weight = c.AprioriWeight
×
1866
                targetCfg.CapacityFraction = c.CapacityFraction
×
1867
                targetCfg.HopProbability = c.AprioriHopProbability
×
1868

1869
        case routing.BimodalConfig:
×
1870
                routerCfg.ProbabilityEstimatorType =
×
1871
                        routing.BimodalEstimatorName
×
1872

×
1873
                targetCfg := routerCfg.BimodalConfig
×
1874
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
1875
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
1876
                targetCfg.DecayTime = c.BimodalDecayTime
×
1877
        }
1878

1879
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1880
}
1881

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

1901
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1902
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1903
// may differ from what is on disk.
1904
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1905
        error) {
×
1906

×
1907
        data, err := u.DataToSign()
×
1908
        if err != nil {
×
1909
                return nil, err
×
1910
        }
×
1911

1912
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1913
}
1914

1915
// createLivenessMonitor creates a set of health checks using our configured
1916
// values and uses these checks to create a liveness monitor. Available
1917
// health checks,
1918
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1919
//   - diskCheck
1920
//   - tlsHealthCheck
1921
//   - torController, only created when tor is enabled.
1922
//
1923
// If a health check has been disabled by setting attempts to 0, our monitor
1924
// will not run it.
1925
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1926
        leaderElector cluster.LeaderElector) {
×
1927

×
1928
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
1929
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1930
                srvrLog.Info("Disabling chain backend checks for " +
×
1931
                        "nochainbackend mode")
×
1932

×
1933
                chainBackendAttempts = 0
×
1934
        }
×
1935

1936
        chainHealthCheck := healthcheck.NewObservation(
×
1937
                "chain backend",
×
1938
                cc.HealthCheck,
×
1939
                cfg.HealthChecks.ChainCheck.Interval,
×
1940
                cfg.HealthChecks.ChainCheck.Timeout,
×
1941
                cfg.HealthChecks.ChainCheck.Backoff,
×
1942
                chainBackendAttempts,
×
1943
        )
×
1944

×
1945
        diskCheck := healthcheck.NewObservation(
×
1946
                "disk space",
×
1947
                func() error {
×
1948
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1949
                                cfg.LndDir,
×
1950
                        )
×
1951
                        if err != nil {
×
1952
                                return err
×
1953
                        }
×
1954

1955
                        // If we have more free space than we require,
1956
                        // we return a nil error.
1957
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1958
                                return nil
×
1959
                        }
×
1960

1961
                        return fmt.Errorf("require: %v free space, got: %v",
×
1962
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1963
                                free)
×
1964
                },
1965
                cfg.HealthChecks.DiskCheck.Interval,
1966
                cfg.HealthChecks.DiskCheck.Timeout,
1967
                cfg.HealthChecks.DiskCheck.Backoff,
1968
                cfg.HealthChecks.DiskCheck.Attempts,
1969
        )
1970

1971
        tlsHealthCheck := healthcheck.NewObservation(
×
1972
                "tls",
×
1973
                func() error {
×
1974
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1975
                                s.cc.KeyRing,
×
1976
                        )
×
1977
                        if err != nil {
×
1978
                                return err
×
1979
                        }
×
1980
                        if expired {
×
1981
                                return fmt.Errorf("TLS certificate is "+
×
1982
                                        "expired as of %v", expTime)
×
1983
                        }
×
1984

1985
                        // If the certificate is not outdated, no error needs
1986
                        // to be returned
1987
                        return nil
×
1988
                },
1989
                cfg.HealthChecks.TLSCheck.Interval,
1990
                cfg.HealthChecks.TLSCheck.Timeout,
1991
                cfg.HealthChecks.TLSCheck.Backoff,
1992
                cfg.HealthChecks.TLSCheck.Attempts,
1993
        )
1994

1995
        checks := []*healthcheck.Observation{
×
1996
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
1997
        }
×
1998

×
1999
        // If Tor is enabled, add the healthcheck for tor connection.
×
2000
        if s.torController != nil {
×
2001
                torConnectionCheck := healthcheck.NewObservation(
×
2002
                        "tor connection",
×
2003
                        func() error {
×
2004
                                return healthcheck.CheckTorServiceStatus(
×
2005
                                        s.torController,
×
2006
                                        func() error {
×
2007
                                                return s.createNewHiddenService(
×
2008
                                                        context.TODO(),
×
2009
                                                )
×
2010
                                        },
×
2011
                                )
2012
                        },
2013
                        cfg.HealthChecks.TorConnection.Interval,
2014
                        cfg.HealthChecks.TorConnection.Timeout,
2015
                        cfg.HealthChecks.TorConnection.Backoff,
2016
                        cfg.HealthChecks.TorConnection.Attempts,
2017
                )
2018
                checks = append(checks, torConnectionCheck)
×
2019
        }
2020

2021
        // If remote signing is enabled, add the healthcheck for the remote
2022
        // signing RPC interface.
2023
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
2024
                // Because we have two cascading timeouts here, we need to add
×
2025
                // some slack to the "outer" one of them in case the "inner"
×
2026
                // returns exactly on time.
×
2027
                overhead := time.Millisecond * 10
×
2028

×
2029
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2030
                        "remote signer connection",
×
2031
                        rpcwallet.HealthCheck(
×
2032
                                s.cfg.RemoteSigner,
×
2033

×
2034
                                // For the health check we might to be even
×
2035
                                // stricter than the initial/normal connect, so
×
2036
                                // we use the health check timeout here.
×
2037
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
2038
                        ),
×
2039
                        cfg.HealthChecks.RemoteSigner.Interval,
×
2040
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
2041
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
2042
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
2043
                )
×
2044
                checks = append(checks, remoteSignerConnectionCheck)
×
2045
        }
×
2046

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

×
2065
                                leader, err := leaderElector.IsLeader(
×
2066
                                        timeoutCtx,
×
2067
                                )
×
2068
                                if err != nil {
×
2069
                                        return fmt.Errorf("unable to check if "+
×
2070
                                                "still leader: %v", err)
×
2071
                                }
×
2072

2073
                                if !leader {
×
2074
                                        srvrLog.Debug("Not the current leader")
×
2075
                                        return fmt.Errorf("not the current " +
×
2076
                                                "leader")
×
2077
                                }
×
2078

2079
                                return nil
×
2080
                        },
2081
                        cfg.HealthChecks.LeaderCheck.Interval,
2082
                        cfg.HealthChecks.LeaderCheck.Timeout,
2083
                        cfg.HealthChecks.LeaderCheck.Backoff,
2084
                        cfg.HealthChecks.LeaderCheck.Attempts,
2085
                )
2086

2087
                checks = append(checks, leaderCheck)
×
2088
        }
2089

2090
        // If we have not disabled all of our health checks, we create a
2091
        // liveness monitor with our configured checks.
2092
        s.livenessMonitor = healthcheck.NewMonitor(
×
2093
                &healthcheck.Config{
×
2094
                        Checks:   checks,
×
2095
                        Shutdown: srvrLog.Criticalf,
×
2096
                },
×
2097
        )
×
2098
}
2099

2100
// Started returns true if the server has been started, and false otherwise.
2101
// NOTE: This function is safe for concurrent access.
2102
func (s *server) Started() bool {
×
2103
        return atomic.LoadInt32(&s.active) != 0
×
2104
}
×
2105

2106
// cleaner is used to aggregate "cleanup" functions during an operation that
2107
// starts several subsystems. In case one of the subsystem fails to start
2108
// and a proper resource cleanup is required, the "run" method achieves this
2109
// by running all these added "cleanup" functions.
2110
type cleaner []func() error
2111

2112
// add is used to add a cleanup function to be called when
2113
// the run function is executed.
2114
func (c cleaner) add(cleanup func() error) cleaner {
×
2115
        return append(c, cleanup)
×
2116
}
×
2117

2118
// run is used to run all the previousely added cleanup functions.
2119
func (c cleaner) run() {
×
2120
        for i := len(c) - 1; i >= 0; i-- {
×
2121
                if err := c[i](); err != nil {
×
2122
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2123
                }
×
2124
        }
2125
}
2126

2127
// startLowLevelServices starts the low-level services of the server. These
2128
// services must be started successfully before running the main server. The
2129
// services are,
2130
// 1. the chain notifier.
2131
//
2132
// TODO(yy): identify and add more low-level services here.
2133
func (s *server) startLowLevelServices() error {
×
2134
        var startErr error
×
2135

×
2136
        cleanup := cleaner{}
×
2137

×
2138
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2139
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2140
                startErr = err
×
2141
        }
×
2142

2143
        if startErr != nil {
×
2144
                cleanup.run()
×
2145
        }
×
2146

2147
        return startErr
×
2148
}
2149

2150
// Start starts the main daemon server, all requested listeners, and any helper
2151
// goroutines.
2152
// NOTE: This function is safe for concurrent access.
2153
//
2154
//nolint:funlen
2155
func (s *server) Start(ctx context.Context) error {
×
2156
        // Get the current blockbeat.
×
2157
        beat, err := s.getStartingBeat()
×
2158
        if err != nil {
×
2159
                return err
×
2160
        }
×
2161

2162
        var startErr error
×
2163

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

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

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

2184
                if s.livenessMonitor != nil {
×
2185
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
2186
                        if err := s.livenessMonitor.Start(); err != nil {
×
2187
                                startErr = err
×
2188
                                return
×
2189
                        }
×
2190
                }
2191

2192
                // Start the notification server. This is used so channel
2193
                // management goroutines can be notified when a funding
2194
                // transaction reaches a sufficient number of confirmations, or
2195
                // when the input for the funding transaction is spent in an
2196
                // attempt at an uncooperative close by the counterparty.
2197
                cleanup = cleanup.add(s.sigPool.Stop)
×
2198
                if err := s.sigPool.Start(); err != nil {
×
2199
                        startErr = err
×
2200
                        return
×
2201
                }
×
2202

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

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

2215
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
2216
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2217
                        startErr = err
×
2218
                        return
×
2219
                }
×
2220

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

2227
                cleanup = cleanup.add(func() error {
×
2228
                        return s.peerNotifier.Stop()
×
2229
                })
×
2230
                if err := s.peerNotifier.Start(); err != nil {
×
2231
                        startErr = err
×
2232
                        return
×
2233
                }
×
2234

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

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

2249
                cleanup = cleanup.add(s.txPublisher.Stop)
×
2250
                if err := s.txPublisher.Start(beat); err != nil {
×
2251
                        startErr = err
×
2252
                        return
×
2253
                }
×
2254

2255
                cleanup = cleanup.add(s.sweeper.Stop)
×
2256
                if err := s.sweeper.Start(beat); err != nil {
×
2257
                        startErr = err
×
2258
                        return
×
2259
                }
×
2260

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

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

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

2279
                // htlcSwitch must be started before chainArb since the latter
2280
                // relies on htlcSwitch to deliver resolution message upon
2281
                // start.
2282
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2283
                if err := s.htlcSwitch.Start(); err != nil {
×
2284
                        startErr = err
×
2285
                        return
×
2286
                }
×
2287

2288
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
×
2289
                if err := s.interceptableSwitch.Start(); err != nil {
×
2290
                        startErr = err
×
2291
                        return
×
2292
                }
×
2293

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

2300
                cleanup = cleanup.add(s.chainArb.Stop)
×
2301
                if err := s.chainArb.Start(beat); err != nil {
×
2302
                        startErr = err
×
2303
                        return
×
2304
                }
×
2305

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

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

2318
                cleanup = cleanup.add(s.chanRouter.Stop)
×
2319
                if err := s.chanRouter.Start(); err != nil {
×
2320
                        startErr = err
×
2321
                        return
×
2322
                }
×
2323
                // The authGossiper depends on the chanRouter and therefore
2324
                // should be started after it.
2325
                cleanup = cleanup.add(s.authGossiper.Stop)
×
2326
                if err := s.authGossiper.Start(); err != nil {
×
2327
                        startErr = err
×
2328
                        return
×
2329
                }
×
2330

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

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

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

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

2355
                cleanup.add(func() error {
×
2356
                        s.missionController.StopStoreTickers()
×
2357
                        return nil
×
2358
                })
×
2359
                s.missionController.RunStoreTickers()
×
2360

×
2361
                // Before we start the connMgr, we'll check to see if we have
×
2362
                // any backups to recover. We do this now as we want to ensure
×
2363
                // that have all the information we need to handle channel
×
2364
                // recovery _before_ we even accept connections from any peers.
×
2365
                chanRestorer := &chanDBRestorer{
×
2366
                        db:         s.chanStateDB,
×
2367
                        secretKeys: s.cc.KeyRing,
×
2368
                        chainArb:   s.chainArb,
×
2369
                }
×
2370
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2371
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2372
                                s.chansToRestore.PackedSingleChanBackups,
×
2373
                                s.cc.KeyRing, chanRestorer, s,
×
2374
                        )
×
2375
                        if err != nil {
×
2376
                                startErr = fmt.Errorf("unable to unpack single "+
×
2377
                                        "backups: %v", err)
×
2378
                                return
×
2379
                        }
×
2380
                }
2381
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
2382
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
2383
                                s.chansToRestore.PackedMultiChanBackup,
×
2384
                                s.cc.KeyRing, chanRestorer, s,
×
2385
                        )
×
2386
                        if err != nil {
×
2387
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2388
                                        "backup: %v", err)
×
2389
                                return
×
2390
                        }
×
2391
                }
2392

2393
                // chanSubSwapper must be started after the `channelNotifier`
2394
                // because it depends on channel events as a synchronization
2395
                // point.
2396
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
2397
                if err := s.chanSubSwapper.Start(); err != nil {
×
2398
                        startErr = err
×
2399
                        return
×
2400
                }
×
2401

2402
                if s.torController != nil {
×
2403
                        cleanup = cleanup.add(s.torController.Stop)
×
2404
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2405
                                startErr = err
×
2406
                                return
×
2407
                        }
×
2408
                }
2409

2410
                if s.natTraversal != nil {
×
2411
                        s.wg.Add(1)
×
2412
                        go s.watchExternalIP()
×
2413
                }
×
2414

2415
                // Start connmgr last to prevent connections before init.
2416
                cleanup = cleanup.add(func() error {
×
2417
                        s.connMgr.Stop()
×
2418
                        return nil
×
2419
                })
×
2420

2421
                // RESOLVE: s.connMgr.Start() is called here, but
2422
                // brontide.NewListener() is called in newServer. This means
2423
                // that we are actually listening and partially accepting
2424
                // inbound connections even before the connMgr starts.
2425
                //
2426
                // TODO(yy): move the log into the connMgr's `Start` method.
2427
                srvrLog.Info("connMgr starting...")
×
2428
                s.connMgr.Start()
×
2429
                srvrLog.Debug("connMgr started")
×
2430

×
2431
                // If peers are specified as a config option, we'll add those
×
2432
                // peers first.
×
2433
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
2434
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
2435
                                peerAddrCfg,
×
2436
                        )
×
2437
                        if err != nil {
×
2438
                                startErr = fmt.Errorf("unable to parse peer "+
×
2439
                                        "pubkey from config: %v", err)
×
2440
                                return
×
2441
                        }
×
2442
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
2443
                        if err != nil {
×
2444
                                startErr = fmt.Errorf("unable to parse peer "+
×
2445
                                        "address provided as a config option: "+
×
2446
                                        "%v", err)
×
2447
                                return
×
2448
                        }
×
2449

2450
                        peerAddr := &lnwire.NetAddress{
×
2451
                                IdentityKey: parsedPubkey,
×
2452
                                Address:     addr,
×
2453
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2454
                        }
×
2455

×
2456
                        err = s.ConnectToPeer(
×
2457
                                peerAddr, true,
×
2458
                                s.cfg.ConnectionTimeout,
×
2459
                        )
×
2460
                        if err != nil {
×
2461
                                startErr = fmt.Errorf("unable to connect to "+
×
2462
                                        "peer address provided as a config "+
×
2463
                                        "option: %v", err)
×
2464
                                return
×
2465
                        }
×
2466
                }
2467

2468
                // Subscribe to NodeAnnouncements that advertise new addresses
2469
                // our persistent peers.
2470
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2471
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2472
                                "addr: %v", err)
×
2473

×
2474
                        startErr = err
×
2475
                        return
×
2476
                }
×
2477

2478
                // With all the relevant sub-systems started, we'll now attempt
2479
                // to establish persistent connections to our direct channel
2480
                // collaborators within the network. Before doing so however,
2481
                // we'll prune our set of link nodes found within the database
2482
                // to ensure we don't reconnect to any nodes we no longer have
2483
                // open channels with.
2484
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2485
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2486

×
2487
                        startErr = err
×
2488
                        return
×
2489
                }
×
2490

2491
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2492
                        srvrLog.Errorf("Failed to establish persistent "+
×
2493
                                "connections: %v", err)
×
2494
                }
×
2495

2496
                // setSeedList is a helper function that turns multiple DNS seed
2497
                // server tuples from the command line or config file into the
2498
                // data structure we need and does a basic formal sanity check
2499
                // in the process.
2500
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2501
                        if len(tuples) == 0 {
×
2502
                                return
×
2503
                        }
×
2504

2505
                        result := make([][2]string, len(tuples))
×
2506
                        for idx, tuple := range tuples {
×
2507
                                tuple = strings.TrimSpace(tuple)
×
2508
                                if len(tuple) == 0 {
×
2509
                                        return
×
2510
                                }
×
2511

2512
                                servers := strings.Split(tuple, ",")
×
2513
                                if len(servers) > 2 || len(servers) == 0 {
×
2514
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2515
                                                "seed tuple: %v", servers)
×
2516
                                        return
×
2517
                                }
×
2518

2519
                                copy(result[idx][:], servers)
×
2520
                        }
2521

2522
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2523
                }
2524

2525
                // Let users overwrite the DNS seed nodes. We only allow them
2526
                // for bitcoin mainnet/testnet/signet.
2527
                if s.cfg.Bitcoin.MainNet {
×
2528
                        setSeedList(
×
2529
                                s.cfg.Bitcoin.DNSSeeds,
×
2530
                                chainreg.BitcoinMainnetGenesis,
×
2531
                        )
×
2532
                }
×
2533
                if s.cfg.Bitcoin.TestNet3 {
×
2534
                        setSeedList(
×
2535
                                s.cfg.Bitcoin.DNSSeeds,
×
2536
                                chainreg.BitcoinTestnetGenesis,
×
2537
                        )
×
2538
                }
×
2539
                if s.cfg.Bitcoin.TestNet4 {
×
2540
                        setSeedList(
×
2541
                                s.cfg.Bitcoin.DNSSeeds,
×
2542
                                chainreg.BitcoinTestnet4Genesis,
×
2543
                        )
×
2544
                }
×
2545
                if s.cfg.Bitcoin.SigNet {
×
2546
                        setSeedList(
×
2547
                                s.cfg.Bitcoin.DNSSeeds,
×
2548
                                chainreg.BitcoinSignetGenesis,
×
2549
                        )
×
2550
                }
×
2551

2552
                // If network bootstrapping hasn't been disabled, then we'll
2553
                // configure the set of active bootstrappers, and launch a
2554
                // dedicated goroutine to maintain a set of persistent
2555
                // connections.
2556
                if !s.cfg.NoNetBootstrap {
×
2557
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2558
                        if err != nil {
×
2559
                                startErr = err
×
2560
                                return
×
2561
                        }
×
2562

2563
                        s.wg.Add(1)
×
2564
                        go s.peerBootstrapper(
×
2565
                                ctx, defaultMinPeers, bootstrappers,
×
2566
                        )
×
2567
                } else {
×
2568
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2569
                }
×
2570

2571
                // Start the blockbeat after all other subsystems have been
2572
                // started so they are ready to receive new blocks.
2573
                cleanup = cleanup.add(func() error {
×
2574
                        s.blockbeatDispatcher.Stop()
×
2575
                        return nil
×
2576
                })
×
2577
                if err := s.blockbeatDispatcher.Start(); err != nil {
×
2578
                        startErr = err
×
2579
                        return
×
2580
                }
×
2581

2582
                // Set the active flag now that we've completed the full
2583
                // startup.
2584
                atomic.StoreInt32(&s.active, 1)
×
2585
        })
2586

2587
        if startErr != nil {
×
2588
                cleanup.run()
×
2589
        }
×
2590
        return startErr
×
2591
}
2592

2593
// Stop gracefully shutsdown the main daemon server. This function will signal
2594
// any active goroutines, or helper objects to exit, then blocks until they've
2595
// all successfully exited. Additionally, any/all listeners are closed.
2596
// NOTE: This function is safe for concurrent access.
2597
func (s *server) Stop() error {
×
2598
        s.stop.Do(func() {
×
2599
                atomic.StoreInt32(&s.stopping, 1)
×
2600

×
2601
                ctx := context.Background()
×
2602

×
2603
                close(s.quit)
×
2604

×
2605
                // Shutdown connMgr first to prevent conns during shutdown.
×
2606
                s.connMgr.Stop()
×
2607

×
2608
                // Stop dispatching blocks to other systems immediately.
×
2609
                s.blockbeatDispatcher.Stop()
×
2610

×
2611
                // Shutdown the wallet, funding manager, and the rpc server.
×
2612
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2613
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2614
                }
×
2615
                if err := s.htlcSwitch.Stop(); err != nil {
×
2616
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2617
                }
×
2618
                if err := s.sphinx.Stop(); err != nil {
×
2619
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2620
                }
×
2621
                if err := s.invoices.Stop(); err != nil {
×
2622
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2623
                }
×
2624
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2625
                        srvrLog.Warnf("failed to stop interceptable "+
×
2626
                                "switch: %v", err)
×
2627
                }
×
2628
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2629
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2630
                                "modifier: %v", err)
×
2631
                }
×
2632
                if err := s.chanRouter.Stop(); err != nil {
×
2633
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2634
                }
×
2635
                if err := s.graphBuilder.Stop(); err != nil {
×
2636
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2637
                }
×
2638
                if err := s.graphDB.Stop(); err != nil {
×
2639
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2640
                }
×
2641
                if err := s.chainArb.Stop(); err != nil {
×
2642
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2643
                }
×
2644
                if err := s.fundingMgr.Stop(); err != nil {
×
2645
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2646
                }
×
2647
                if err := s.breachArbitrator.Stop(); err != nil {
×
2648
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2649
                                err)
×
2650
                }
×
2651
                if err := s.utxoNursery.Stop(); err != nil {
×
2652
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2653
                }
×
2654
                if err := s.authGossiper.Stop(); err != nil {
×
2655
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2656
                }
×
2657
                if err := s.sweeper.Stop(); err != nil {
×
2658
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2659
                }
×
2660
                if err := s.txPublisher.Stop(); err != nil {
×
2661
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2662
                }
×
2663
                if err := s.channelNotifier.Stop(); err != nil {
×
2664
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2665
                }
×
2666
                if err := s.peerNotifier.Stop(); err != nil {
×
2667
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2668
                }
×
2669
                if err := s.htlcNotifier.Stop(); err != nil {
×
2670
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2671
                }
×
2672

2673
                // Update channel.backup file. Make sure to do it before
2674
                // stopping chanSubSwapper.
2675
                singles, err := chanbackup.FetchStaticChanBackups(
×
2676
                        ctx, s.chanStateDB, s.addrSource,
×
2677
                )
×
2678
                if err != nil {
×
2679
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2680
                                err)
×
2681
                } else {
×
2682
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
2683
                        if err != nil {
×
2684
                                srvrLog.Warnf("Manual update of channel "+
×
2685
                                        "backup failed: %v", err)
×
2686
                        }
×
2687
                }
2688

2689
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2690
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2691
                }
×
2692
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2693
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2694
                }
×
2695
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2696
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2697
                                err)
×
2698
                }
×
2699
                if err := s.chanEventStore.Stop(); err != nil {
×
2700
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2701
                                err)
×
2702
                }
×
2703
                s.missionController.StopStoreTickers()
×
2704

×
2705
                // Disconnect from each active peers to ensure that
×
2706
                // peerTerminationWatchers signal completion to each peer.
×
2707
                for _, peer := range s.Peers() {
×
2708
                        err := s.DisconnectPeer(peer.IdentityKey())
×
2709
                        if err != nil {
×
2710
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2711
                                        "received error: %v", peer.IdentityKey(),
×
2712
                                        err,
×
2713
                                )
×
2714
                        }
×
2715
                }
2716

2717
                // Now that all connections have been torn down, stop the tower
2718
                // client which will reliably flush all queued states to the
2719
                // tower. If this is halted for any reason, the force quit timer
2720
                // will kick in and abort to allow this method to return.
2721
                if s.towerClientMgr != nil {
×
2722
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2723
                                srvrLog.Warnf("Unable to shut down tower "+
×
2724
                                        "client manager: %v", err)
×
2725
                        }
×
2726
                }
2727

2728
                if s.hostAnn != nil {
×
2729
                        if err := s.hostAnn.Stop(); err != nil {
×
2730
                                srvrLog.Warnf("unable to shut down host "+
×
2731
                                        "annoucner: %v", err)
×
2732
                        }
×
2733
                }
2734

2735
                if s.livenessMonitor != nil {
×
2736
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2737
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2738
                                        "monitor: %v", err)
×
2739
                        }
×
2740
                }
2741

2742
                // Wait for all lingering goroutines to quit.
2743
                srvrLog.Debug("Waiting for server to shutdown...")
×
2744
                s.wg.Wait()
×
2745

×
2746
                srvrLog.Debug("Stopping buffer pools...")
×
2747
                s.sigPool.Stop()
×
2748
                s.writePool.Stop()
×
2749
                s.readPool.Stop()
×
2750
        })
2751

2752
        return nil
×
2753
}
2754

2755
// Stopped returns true if the server has been instructed to shutdown.
2756
// NOTE: This function is safe for concurrent access.
2757
func (s *server) Stopped() bool {
×
2758
        return atomic.LoadInt32(&s.stopping) != 0
×
2759
}
×
2760

2761
// configurePortForwarding attempts to set up port forwarding for the different
2762
// ports that the server will be listening on.
2763
//
2764
// NOTE: This should only be used when using some kind of NAT traversal to
2765
// automatically set up forwarding rules.
2766
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2767
        ip, err := s.natTraversal.ExternalIP()
×
2768
        if err != nil {
×
2769
                return nil, err
×
2770
        }
×
2771
        s.lastDetectedIP = ip
×
2772

×
2773
        externalIPs := make([]string, 0, len(ports))
×
2774
        for _, port := range ports {
×
2775
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2776
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2777
                        continue
×
2778
                }
2779

2780
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2781
                externalIPs = append(externalIPs, hostIP)
×
2782
        }
2783

2784
        return externalIPs, nil
×
2785
}
2786

2787
// removePortForwarding attempts to clear the forwarding rules for the different
2788
// ports the server is currently listening on.
2789
//
2790
// NOTE: This should only be used when using some kind of NAT traversal to
2791
// automatically set up forwarding rules.
2792
func (s *server) removePortForwarding() {
×
2793
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2794
        for _, port := range forwardedPorts {
×
2795
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2796
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2797
                                "port %d: %v", port, err)
×
2798
                }
×
2799
        }
2800
}
2801

2802
// watchExternalIP continuously checks for an updated external IP address every
2803
// 15 minutes. Once a new IP address has been detected, it will automatically
2804
// handle port forwarding rules and send updated node announcements to the
2805
// currently connected peers.
2806
//
2807
// NOTE: This MUST be run as a goroutine.
2808
func (s *server) watchExternalIP() {
×
2809
        defer s.wg.Done()
×
2810

×
2811
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2812
        // up by the server.
×
2813
        defer s.removePortForwarding()
×
2814

×
2815
        // Keep track of the external IPs set by the user to avoid replacing
×
2816
        // them when detecting a new IP.
×
2817
        ipsSetByUser := make(map[string]struct{})
×
2818
        for _, ip := range s.cfg.ExternalIPs {
×
2819
                ipsSetByUser[ip.String()] = struct{}{}
×
2820
        }
×
2821

2822
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2823

×
2824
        ticker := time.NewTicker(15 * time.Minute)
×
2825
        defer ticker.Stop()
×
2826
out:
×
2827
        for {
×
2828
                select {
×
2829
                case <-ticker.C:
×
2830
                        // We'll start off by making sure a new IP address has
×
2831
                        // been detected.
×
2832
                        ip, err := s.natTraversal.ExternalIP()
×
2833
                        if err != nil {
×
2834
                                srvrLog.Debugf("Unable to retrieve the "+
×
2835
                                        "external IP address: %v", err)
×
2836
                                continue
×
2837
                        }
2838

2839
                        // Periodically renew the NAT port forwarding.
2840
                        for _, port := range forwardedPorts {
×
2841
                                err := s.natTraversal.AddPortMapping(port)
×
2842
                                if err != nil {
×
2843
                                        srvrLog.Warnf("Unable to automatically "+
×
2844
                                                "re-create port forwarding using %s: %v",
×
2845
                                                s.natTraversal.Name(), err)
×
2846
                                } else {
×
2847
                                        srvrLog.Debugf("Automatically re-created "+
×
2848
                                                "forwarding for port %d using %s to "+
×
2849
                                                "advertise external IP",
×
2850
                                                port, s.natTraversal.Name())
×
2851
                                }
×
2852
                        }
2853

2854
                        if ip.Equal(s.lastDetectedIP) {
×
2855
                                continue
×
2856
                        }
2857

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

×
2860
                        // Next, we'll craft the new addresses that will be
×
2861
                        // included in the new node announcement and advertised
×
2862
                        // to the network. Each address will consist of the new
×
2863
                        // IP detected and one of the currently advertised
×
2864
                        // ports.
×
2865
                        var newAddrs []net.Addr
×
2866
                        for _, port := range forwardedPorts {
×
2867
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2868
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2869
                                if err != nil {
×
2870
                                        srvrLog.Debugf("Unable to resolve "+
×
2871
                                                "host %v: %v", addr, err)
×
2872
                                        continue
×
2873
                                }
2874

2875
                                newAddrs = append(newAddrs, addr)
×
2876
                        }
2877

2878
                        // Skip the update if we weren't able to resolve any of
2879
                        // the new addresses.
2880
                        if len(newAddrs) == 0 {
×
2881
                                srvrLog.Debug("Skipping node announcement " +
×
2882
                                        "update due to not being able to " +
×
2883
                                        "resolve any new addresses")
×
2884
                                continue
×
2885
                        }
2886

2887
                        // Now, we'll need to update the addresses in our node's
2888
                        // announcement in order to propagate the update
2889
                        // throughout the network. We'll only include addresses
2890
                        // that have a different IP from the previous one, as
2891
                        // the previous IP is no longer valid.
2892
                        currentNodeAnn := s.getNodeAnnouncement()
×
2893

×
2894
                        for _, addr := range currentNodeAnn.Addresses {
×
2895
                                host, _, err := net.SplitHostPort(addr.String())
×
2896
                                if err != nil {
×
2897
                                        srvrLog.Debugf("Unable to determine "+
×
2898
                                                "host from address %v: %v",
×
2899
                                                addr, err)
×
2900
                                        continue
×
2901
                                }
2902

2903
                                // We'll also make sure to include external IPs
2904
                                // set manually by the user.
2905
                                _, setByUser := ipsSetByUser[addr.String()]
×
2906
                                if setByUser || host != s.lastDetectedIP.String() {
×
2907
                                        newAddrs = append(newAddrs, addr)
×
2908
                                }
×
2909
                        }
2910

2911
                        // Then, we'll generate a new timestamped node
2912
                        // announcement with the updated addresses and broadcast
2913
                        // it to our peers.
2914
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2915
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2916
                        )
×
2917
                        if err != nil {
×
2918
                                srvrLog.Debugf("Unable to generate new node "+
×
2919
                                        "announcement: %v", err)
×
2920
                                continue
×
2921
                        }
2922

2923
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2924
                        if err != nil {
×
2925
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2926
                                        "announcement to peers: %v", err)
×
2927
                                continue
×
2928
                        }
2929

2930
                        // Finally, update the last IP seen to the current one.
2931
                        s.lastDetectedIP = ip
×
2932
                case <-s.quit:
×
2933
                        break out
×
2934
                }
2935
        }
2936
}
2937

2938
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2939
// based on the server, and currently active bootstrap mechanisms as defined
2940
// within the current configuration.
2941
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2942
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2943

×
2944
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2945

×
2946
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2947
        // this can be used by default if we've already partially seeded the
×
2948
        // network.
×
2949
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2950
        graphBootstrapper, err := discovery.NewGraphBootstrapper(
×
2951
                chanGraph, s.cfg.Bitcoin.IsLocalNetwork(),
×
2952
        )
×
2953
        if err != nil {
×
2954
                return nil, err
×
2955
        }
×
2956
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2957

×
2958
        // If this isn't using simnet or regtest mode, then one of our
×
2959
        // additional bootstrapping sources will be the set of running DNS
×
2960
        // seeds.
×
2961
        if !s.cfg.Bitcoin.IsLocalNetwork() {
×
2962
                //nolint:ll
×
2963
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
2964

×
2965
                // If we have a set of DNS seeds for this chain, then we'll add
×
2966
                // it as an additional bootstrapping source.
×
2967
                if ok {
×
2968
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2969
                                "seeds: %v", dnsSeeds)
×
2970

×
2971
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2972
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2973
                        )
×
2974
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2975
                }
×
2976
        }
2977

2978
        return bootStrappers, nil
×
2979
}
2980

2981
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2982
// needs to ignore, which is made of three parts,
2983
//   - the node itself needs to be skipped as it doesn't make sense to connect
2984
//     to itself.
2985
//   - the peers that already have connections with, as in s.peersByPub.
2986
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2987
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2988
        s.mu.RLock()
×
2989
        defer s.mu.RUnlock()
×
2990

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

×
2993
        // We should ignore ourselves from bootstrapping.
×
2994
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2995
        ignore[selfKey] = struct{}{}
×
2996

×
2997
        // Ignore all connected peers.
×
2998
        for _, peer := range s.peersByPub {
×
2999
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3000
                ignore[nID] = struct{}{}
×
3001
        }
×
3002

3003
        // Ignore all persistent peers as they have a dedicated reconnecting
3004
        // process.
3005
        for pubKeyStr := range s.persistentPeers {
×
3006
                var nID autopilot.NodeID
×
3007
                copy(nID[:], []byte(pubKeyStr))
×
3008
                ignore[nID] = struct{}{}
×
3009
        }
×
3010

3011
        return ignore
×
3012
}
3013

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

×
3022
        defer s.wg.Done()
×
3023

×
3024
        // Before we continue, init the ignore peers map.
×
3025
        ignoreList := s.createBootstrapIgnorePeers()
×
3026

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

×
3031
        // Once done, we'll attempt to maintain our target minimum number of
×
3032
        // peers.
×
3033
        //
×
3034
        // We'll use a 15 second backoff, and double the time every time an
×
3035
        // epoch fails up to a ceiling.
×
3036
        backOff := time.Second * 15
×
3037

×
3038
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3039
        // see if we've reached our minimum number of peers.
×
3040
        sampleTicker := time.NewTicker(backOff)
×
3041
        defer sampleTicker.Stop()
×
3042

×
3043
        // We'll use the number of attempts and errors to determine if we need
×
3044
        // to increase the time between discovery epochs.
×
3045
        var epochErrors uint32 // To be used atomically.
×
3046
        var epochAttempts uint32
×
3047

×
3048
        for {
×
3049
                select {
×
3050
                // The ticker has just woken us up, so we'll need to check if
3051
                // we need to attempt to connect our to any more peers.
3052
                case <-sampleTicker.C:
×
3053
                        // Obtain the current number of peers, so we can gauge
×
3054
                        // if we need to sample more peers or not.
×
3055
                        s.mu.RLock()
×
3056
                        numActivePeers := uint32(len(s.peersByPub))
×
3057
                        s.mu.RUnlock()
×
3058

×
3059
                        // If we have enough peers, then we can loop back
×
3060
                        // around to the next round as we're done here.
×
3061
                        if numActivePeers >= numTargetPeers {
×
3062
                                continue
×
3063
                        }
3064

3065
                        // If all of our attempts failed during this last back
3066
                        // off period, then will increase our backoff to 5
3067
                        // minute ceiling to avoid an excessive number of
3068
                        // queries
3069
                        //
3070
                        // TODO(roasbeef): add reverse policy too?
3071

3072
                        if epochAttempts > 0 &&
×
3073
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3074

×
3075
                                sampleTicker.Stop()
×
3076

×
3077
                                backOff *= 2
×
3078
                                if backOff > bootstrapBackOffCeiling {
×
3079
                                        backOff = bootstrapBackOffCeiling
×
3080
                                }
×
3081

3082
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3083
                                        "%v", backOff)
×
3084
                                sampleTicker = time.NewTicker(backOff)
×
3085
                                continue
×
3086
                        }
3087

3088
                        atomic.StoreUint32(&epochErrors, 0)
×
3089
                        epochAttempts = 0
×
3090

×
3091
                        // Since we know need more peers, we'll compute the
×
3092
                        // exact number we need to reach our threshold.
×
3093
                        numNeeded := numTargetPeers - numActivePeers
×
3094

×
3095
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3096
                                "peers", numNeeded)
×
3097

×
3098
                        // With the number of peers we need calculated, we'll
×
3099
                        // query the network bootstrappers to sample a set of
×
3100
                        // random addrs for us.
×
3101
                        //
×
3102
                        // Before we continue, get a copy of the ignore peers
×
3103
                        // map.
×
3104
                        ignoreList = s.createBootstrapIgnorePeers()
×
3105

×
3106
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3107
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3108
                        )
×
3109
                        if err != nil {
×
3110
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3111
                                        "peers: %v", err)
×
3112
                                continue
×
3113
                        }
3114

3115
                        // Finally, we'll launch a new goroutine for each
3116
                        // prospective peer candidates.
3117
                        for _, addr := range peerAddrs {
×
3118
                                epochAttempts++
×
3119

×
3120
                                go func(a *lnwire.NetAddress) {
×
3121
                                        // TODO(roasbeef): can do AS, subnet,
×
3122
                                        // country diversity, etc
×
3123
                                        errChan := make(chan error, 1)
×
3124
                                        s.connectToPeer(
×
3125
                                                a, errChan,
×
3126
                                                s.cfg.ConnectionTimeout,
×
3127
                                        )
×
3128
                                        select {
×
3129
                                        case err := <-errChan:
×
3130
                                                if err == nil {
×
3131
                                                        return
×
3132
                                                }
×
3133

3134
                                                srvrLog.Errorf("Unable to "+
×
3135
                                                        "connect to %v: %v",
×
3136
                                                        a, err)
×
3137
                                                atomic.AddUint32(&epochErrors, 1)
×
3138
                                        case <-s.quit:
×
3139
                                        }
3140
                                }(addr)
3141
                        }
3142
                case <-s.quit:
×
3143
                        return
×
3144
                }
3145
        }
3146
}
3147

3148
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3149
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3150
// query back off each time we encounter a failure.
3151
const bootstrapBackOffCeiling = time.Minute * 5
3152

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

×
3160
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3161
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3162

×
3163
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3164
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3165
        var delaySignal <-chan time.Time
×
3166
        delayTime := time.Second * 2
×
3167

×
3168
        // As want to be more aggressive, we'll use a lower back off celling
×
3169
        // then the main peer bootstrap logic.
×
3170
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3171

×
3172
        for attempts := 0; ; attempts++ {
×
3173
                // Check if the server has been requested to shut down in order
×
3174
                // to prevent blocking.
×
3175
                if s.Stopped() {
×
3176
                        return
×
3177
                }
×
3178

3179
                // We can exit our aggressive initial peer bootstrapping stage
3180
                // if we've reached out target number of peers.
3181
                s.mu.RLock()
×
3182
                numActivePeers := uint32(len(s.peersByPub))
×
3183
                s.mu.RUnlock()
×
3184

×
3185
                if numActivePeers >= numTargetPeers {
×
3186
                        return
×
3187
                }
×
3188

3189
                if attempts > 0 {
×
3190
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3191
                                "bootstrap peers (attempt #%v)", delayTime,
×
3192
                                attempts)
×
3193

×
3194
                        // We've completed at least one iterating and haven't
×
3195
                        // finished, so we'll start to insert a delay period
×
3196
                        // between each attempt.
×
3197
                        delaySignal = time.After(delayTime)
×
3198
                        select {
×
3199
                        case <-delaySignal:
×
3200
                        case <-s.quit:
×
3201
                                return
×
3202
                        }
3203

3204
                        // After our delay, we'll double the time we wait up to
3205
                        // the max back off period.
3206
                        delayTime *= 2
×
3207
                        if delayTime > backOffCeiling {
×
3208
                                delayTime = backOffCeiling
×
3209
                        }
×
3210
                }
3211

3212
                // Otherwise, we'll request for the remaining number of peers
3213
                // in order to reach our target.
3214
                peersNeeded := numTargetPeers - numActivePeers
×
3215
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3216
                        ctx, ignore, peersNeeded, bootstrappers...,
×
3217
                )
×
3218
                if err != nil {
×
3219
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3220
                                "peers: %v", err)
×
3221
                        continue
×
3222
                }
3223

3224
                // Then, we'll attempt to establish a connection to the
3225
                // different peer addresses retrieved by our bootstrappers.
3226
                var wg sync.WaitGroup
×
3227
                for _, bootstrapAddr := range bootstrapAddrs {
×
3228
                        wg.Add(1)
×
3229
                        go func(addr *lnwire.NetAddress) {
×
3230
                                defer wg.Done()
×
3231

×
3232
                                errChan := make(chan error, 1)
×
3233
                                go s.connectToPeer(
×
3234
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3235
                                )
×
3236

×
3237
                                // We'll only allow this connection attempt to
×
3238
                                // take up to 3 seconds. This allows us to move
×
3239
                                // quickly by discarding peers that are slowing
×
3240
                                // us down.
×
3241
                                select {
×
3242
                                case err := <-errChan:
×
3243
                                        if err == nil {
×
3244
                                                return
×
3245
                                        }
×
3246
                                        srvrLog.Errorf("Unable to connect to "+
×
3247
                                                "%v: %v", addr, err)
×
3248
                                // TODO: tune timeout? 3 seconds might be *too*
3249
                                // aggressive but works well.
3250
                                case <-time.After(3 * time.Second):
×
3251
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3252
                                                "to not establishing a "+
×
3253
                                                "connection within 3 seconds",
×
3254
                                                addr)
×
3255
                                case <-s.quit:
×
3256
                                }
3257
                        }(bootstrapAddr)
3258
                }
3259

3260
                wg.Wait()
×
3261
        }
3262
}
3263

3264
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3265
// order to listen for inbound connections over Tor.
3266
func (s *server) createNewHiddenService(ctx context.Context) error {
×
3267
        // Determine the different ports the server is listening on. The onion
×
3268
        // service's virtual port will map to these ports and one will be picked
×
3269
        // at random when the onion service is being accessed.
×
3270
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3271
        for _, listenAddr := range s.listenAddrs {
×
3272
                port := listenAddr.(*net.TCPAddr).Port
×
3273
                listenPorts = append(listenPorts, port)
×
3274
        }
×
3275

3276
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3277
        if err != nil {
×
3278
                return err
×
3279
        }
×
3280

3281
        // Once the port mapping has been set, we can go ahead and automatically
3282
        // create our onion service. The service's private key will be saved to
3283
        // disk in order to regain access to this service when restarting `lnd`.
3284
        onionCfg := tor.AddOnionConfig{
×
3285
                VirtualPort: defaultPeerPort,
×
3286
                TargetPorts: listenPorts,
×
3287
                Store: tor.NewOnionFile(
×
3288
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3289
                        encrypter,
×
3290
                ),
×
3291
        }
×
3292

×
3293
        switch {
×
3294
        case s.cfg.Tor.V2:
×
3295
                onionCfg.Type = tor.V2
×
3296
        case s.cfg.Tor.V3:
×
3297
                onionCfg.Type = tor.V3
×
3298
        }
3299

3300
        addr, err := s.torController.AddOnion(onionCfg)
×
3301
        if err != nil {
×
3302
                return err
×
3303
        }
×
3304

3305
        // Now that the onion service has been created, we'll add the onion
3306
        // address it can be reached at to our list of advertised addresses.
3307
        newNodeAnn, err := s.genNodeAnnouncement(
×
3308
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3309
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3310
                },
×
3311
        )
3312
        if err != nil {
×
3313
                return fmt.Errorf("unable to generate new node "+
×
3314
                        "announcement: %v", err)
×
3315
        }
×
3316

3317
        // Finally, we'll update the on-disk version of our announcement so it
3318
        // will eventually propagate to nodes in the network.
3319
        selfNode := &models.Node{
×
3320
                HaveNodeAnnouncement: true,
×
3321
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3322
                Addresses:            newNodeAnn.Addresses,
×
3323
                Alias:                newNodeAnn.Alias.String(),
×
3324
                Features: lnwire.NewFeatureVector(
×
3325
                        newNodeAnn.Features, lnwire.Features,
×
3326
                ),
×
3327
                Color:        newNodeAnn.RGBColor,
×
3328
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3329
        }
×
3330
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3331
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3332
                return fmt.Errorf("can't set self node: %w", err)
×
3333
        }
×
3334

3335
        return nil
×
3336
}
3337

3338
// findChannel finds a channel given a public key and ChannelID. It is an
3339
// optimization that is quicker than seeking for a channel given only the
3340
// ChannelID.
3341
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3342
        *channeldb.OpenChannel, error) {
×
3343

×
3344
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3345
        if err != nil {
×
3346
                return nil, err
×
3347
        }
×
3348

3349
        for _, channel := range nodeChans {
×
3350
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3351
                        return channel, nil
×
3352
                }
×
3353
        }
3354

3355
        return nil, fmt.Errorf("unable to find channel")
×
3356
}
3357

3358
// getNodeAnnouncement fetches the current, fully signed node announcement.
3359
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
3360
        s.mu.Lock()
×
3361
        defer s.mu.Unlock()
×
3362

×
3363
        return *s.currentNodeAnn
×
3364
}
×
3365

3366
// genNodeAnnouncement generates and returns the current fully signed node
3367
// announcement. The time stamp of the announcement will be updated in order
3368
// to ensure it propagates through the network.
3369
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3370
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
3371

×
3372
        s.mu.Lock()
×
3373
        defer s.mu.Unlock()
×
3374

×
3375
        // Create a shallow copy of the current node announcement to work on.
×
3376
        // This ensures the original announcement remains unchanged
×
3377
        // until the new announcement is fully signed and valid.
×
3378
        newNodeAnn := *s.currentNodeAnn
×
3379

×
3380
        // First, try to update our feature manager with the updated set of
×
3381
        // features.
×
3382
        if features != nil {
×
3383
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
3384
                        feature.SetNodeAnn: features,
×
3385
                }
×
3386
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
3387
                if err != nil {
×
3388
                        return lnwire.NodeAnnouncement{}, err
×
3389
                }
×
3390

3391
                // If we could successfully update our feature manager, add
3392
                // an update modifier to include these new features to our
3393
                // set.
3394
                modifiers = append(
×
3395
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3396
                )
×
3397
        }
3398

3399
        // Always update the timestamp when refreshing to ensure the update
3400
        // propagates.
3401
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3402

×
3403
        // Apply the requested changes to the node announcement.
×
3404
        for _, modifier := range modifiers {
×
3405
                modifier(&newNodeAnn)
×
3406
        }
×
3407

3408
        // Sign a new update after applying all of the passed modifiers.
3409
        err := netann.SignNodeAnnouncement(
×
3410
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
3411
        )
×
3412
        if err != nil {
×
3413
                return lnwire.NodeAnnouncement{}, err
×
3414
        }
×
3415

3416
        // If signing succeeds, update the current announcement.
3417
        *s.currentNodeAnn = newNodeAnn
×
3418

×
3419
        return *s.currentNodeAnn, nil
×
3420
}
3421

3422
// updateAndBroadcastSelfNode generates a new node announcement
3423
// applying the giving modifiers and updating the time stamp
3424
// to ensure it propagates through the network. Then it broadcasts
3425
// it to the network.
3426
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3427
        features *lnwire.RawFeatureVector,
3428
        modifiers ...netann.NodeAnnModifier) error {
×
3429

×
3430
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
3431
        if err != nil {
×
3432
                return fmt.Errorf("unable to generate new node "+
×
3433
                        "announcement: %v", err)
×
3434
        }
×
3435

3436
        // Update the on-disk version of our announcement.
3437
        // Load and modify self node istead of creating anew instance so we
3438
        // don't risk overwriting any existing values.
3439
        selfNode, err := s.graphDB.SourceNode(ctx)
×
3440
        if err != nil {
×
3441
                return fmt.Errorf("unable to get current source node: %w", err)
×
3442
        }
×
3443

3444
        selfNode.HaveNodeAnnouncement = true
×
3445
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
3446
        selfNode.Addresses = newNodeAnn.Addresses
×
3447
        selfNode.Alias = newNodeAnn.Alias.String()
×
3448
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
3449
        selfNode.Color = newNodeAnn.RGBColor
×
3450
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
3451

×
3452
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3453

×
3454
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3455
                return fmt.Errorf("can't set self node: %w", err)
×
3456
        }
×
3457

3458
        // Finally, propagate it to the nodes in the network.
3459
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3460
        if err != nil {
×
3461
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3462
                        "announcement to peers: %v", err)
×
3463
                return err
×
3464
        }
×
3465

3466
        return nil
×
3467
}
3468

3469
type nodeAddresses struct {
3470
        pubKey    *btcec.PublicKey
3471
        addresses []net.Addr
3472
}
3473

3474
// establishPersistentConnections attempts to establish persistent connections
3475
// to all our direct channel collaborators. In order to promote liveness of our
3476
// active channels, we instruct the connection manager to attempt to establish
3477
// and maintain persistent connections to all our direct channel counterparties.
3478
func (s *server) establishPersistentConnections(ctx context.Context) error {
×
3479
        // nodeAddrsMap stores the combination of node public keys and addresses
×
3480
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
3481
        // since other PubKey forms can't be compared.
×
3482
        nodeAddrsMap := make(map[string]*nodeAddresses)
×
3483

×
3484
        // Iterate through the list of LinkNodes to find addresses we should
×
3485
        // attempt to connect to based on our set of previous connections. Set
×
3486
        // the reconnection port to the default peer port.
×
3487
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
3488
        if err != nil && !errors.Is(err, channeldb.ErrLinkNodesNotFound) {
×
3489
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3490
        }
×
3491

3492
        for _, node := range linkNodes {
×
3493
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
3494
                nodeAddrs := &nodeAddresses{
×
3495
                        pubKey:    node.IdentityPub,
×
3496
                        addresses: node.Addresses,
×
3497
                }
×
3498
                nodeAddrsMap[pubStr] = nodeAddrs
×
3499
        }
×
3500

3501
        // After checking our previous connections for addresses to connect to,
3502
        // iterate through the nodes in our channel graph to find addresses
3503
        // that have been added via NodeAnnouncement messages.
3504
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3505
        // each of the nodes.
3506
        graphAddrs := make(map[string]*nodeAddresses)
×
3507
        forEachSrcNodeChan := func(chanPoint wire.OutPoint,
×
3508
                havePolicy bool, channelPeer *models.Node) error {
×
3509

×
3510
                // If the remote party has announced the channel to us, but we
×
3511
                // haven't yet, then we won't have a policy. However, we don't
×
3512
                // need this to connect to the peer, so we'll log it and move on.
×
3513
                if !havePolicy {
×
3514
                        srvrLog.Warnf("No channel policy found for "+
×
3515
                                "ChannelPoint(%v): ", chanPoint)
×
3516
                }
×
3517

3518
                pubStr := string(channelPeer.PubKeyBytes[:])
×
3519

×
3520
                // Add all unique addresses from channel
×
3521
                // graph/NodeAnnouncements to the list of addresses we'll
×
3522
                // connect to for this peer.
×
3523
                addrSet := make(map[string]net.Addr)
×
3524
                for _, addr := range channelPeer.Addresses {
×
3525
                        switch addr.(type) {
×
3526
                        case *net.TCPAddr:
×
3527
                                addrSet[addr.String()] = addr
×
3528

3529
                        // We'll only attempt to connect to Tor addresses if Tor
3530
                        // outbound support is enabled.
3531
                        case *tor.OnionAddr:
×
3532
                                if s.cfg.Tor.Active {
×
3533
                                        addrSet[addr.String()] = addr
×
3534
                                }
×
3535
                        }
3536
                }
3537

3538
                // If this peer is also recorded as a link node, we'll add any
3539
                // additional addresses that have not already been selected.
3540
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
3541
                if ok {
×
3542
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
3543
                                switch lnAddress.(type) {
×
3544
                                case *net.TCPAddr:
×
3545
                                        addrSet[lnAddress.String()] = lnAddress
×
3546

3547
                                // We'll only attempt to connect to Tor
3548
                                // addresses if Tor outbound support is enabled.
3549
                                case *tor.OnionAddr:
×
3550
                                        if s.cfg.Tor.Active {
×
3551
                                                //nolint:ll
×
3552
                                                addrSet[lnAddress.String()] = lnAddress
×
3553
                                        }
×
3554
                                }
3555
                        }
3556
                }
3557

3558
                // Construct a slice of the deduped addresses.
3559
                var addrs []net.Addr
×
3560
                for _, addr := range addrSet {
×
3561
                        addrs = append(addrs, addr)
×
3562
                }
×
3563

3564
                n := &nodeAddresses{
×
3565
                        addresses: addrs,
×
3566
                }
×
3567
                n.pubKey, err = channelPeer.PubKey()
×
3568
                if err != nil {
×
3569
                        return err
×
3570
                }
×
3571

3572
                graphAddrs[pubStr] = n
×
3573
                return nil
×
3574
        }
3575
        err = s.graphDB.ForEachSourceNodeChannel(
×
3576
                ctx, forEachSrcNodeChan, func() {
×
3577
                        clear(graphAddrs)
×
3578
                },
×
3579
        )
3580
        if err != nil {
×
3581
                srvrLog.Errorf("Failed to iterate over source node channels: "+
×
3582
                        "%v", err)
×
3583

×
3584
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3585
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3586

×
3587
                        return err
×
3588
                }
×
3589
        }
3590

3591
        // Combine the addresses from the link nodes and the channel graph.
3592
        for pubStr, nodeAddr := range graphAddrs {
×
3593
                nodeAddrsMap[pubStr] = nodeAddr
×
3594
        }
×
3595

3596
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3597
                len(nodeAddrsMap))
×
3598

×
3599
        // Acquire and hold server lock until all persistent connection requests
×
3600
        // have been recorded and sent to the connection manager.
×
3601
        s.mu.Lock()
×
3602
        defer s.mu.Unlock()
×
3603

×
3604
        // Iterate through the combined list of addresses from prior links and
×
3605
        // node announcements and attempt to reconnect to each node.
×
3606
        var numOutboundConns int
×
3607
        for pubStr, nodeAddr := range nodeAddrsMap {
×
3608
                // Add this peer to the set of peers we should maintain a
×
3609
                // persistent connection with. We set the value to false to
×
3610
                // indicate that we should not continue to reconnect if the
×
3611
                // number of channels returns to zero, since this peer has not
×
3612
                // been requested as perm by the user.
×
3613
                s.persistentPeers[pubStr] = false
×
3614
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
3615
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
3616
                }
×
3617

3618
                for _, address := range nodeAddr.addresses {
×
3619
                        // Create a wrapper address which couples the IP and
×
3620
                        // the pubkey so the brontide authenticated connection
×
3621
                        // can be established.
×
3622
                        lnAddr := &lnwire.NetAddress{
×
3623
                                IdentityKey: nodeAddr.pubKey,
×
3624
                                Address:     address,
×
3625
                        }
×
3626

×
3627
                        s.persistentPeerAddrs[pubStr] = append(
×
3628
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3629
                }
×
3630

3631
                // We'll connect to the first 10 peers immediately, then
3632
                // randomly stagger any remaining connections if the
3633
                // stagger initial reconnect flag is set. This ensures
3634
                // that mobile nodes or nodes with a small number of
3635
                // channels obtain connectivity quickly, but larger
3636
                // nodes are able to disperse the costs of connecting to
3637
                // all peers at once.
3638
                if numOutboundConns < numInstantInitReconnect ||
×
3639
                        !s.cfg.StaggerInitialReconnect {
×
3640

×
3641
                        go s.connectToPersistentPeer(pubStr)
×
3642
                } else {
×
3643
                        go s.delayInitialReconnect(pubStr)
×
3644
                }
×
3645

3646
                numOutboundConns++
×
3647
        }
3648

3649
        return nil
×
3650
}
3651

3652
// delayInitialReconnect will attempt a reconnection to the given peer after
3653
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3654
//
3655
// NOTE: This method MUST be run as a goroutine.
3656
func (s *server) delayInitialReconnect(pubStr string) {
×
3657
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3658
        select {
×
3659
        case <-time.After(delay):
×
3660
                s.connectToPersistentPeer(pubStr)
×
3661
        case <-s.quit:
×
3662
        }
3663
}
3664

3665
// prunePersistentPeerConnection removes all internal state related to
3666
// persistent connections to a peer within the server. This is used to avoid
3667
// persistent connection retries to peers we do not have any open channels with.
3668
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
×
3669
        pubKeyStr := string(compressedPubKey[:])
×
3670

×
3671
        s.mu.Lock()
×
3672
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3673
                delete(s.persistentPeers, pubKeyStr)
×
3674
                delete(s.persistentPeersBackoff, pubKeyStr)
×
3675
                delete(s.persistentPeerAddrs, pubKeyStr)
×
3676
                s.cancelConnReqs(pubKeyStr, nil)
×
3677
                s.mu.Unlock()
×
3678

×
3679
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3680
                        "peer has no open channels", compressedPubKey)
×
3681

×
3682
                return
×
3683
        }
×
3684
        s.mu.Unlock()
×
3685
}
3686

3687
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3688
// is instead used to remove persistent peer state for a peer that has been
3689
// disconnected for good cause by the server. Currently, a gossip ban from
3690
// sending garbage and the server running out of restricted-access
3691
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3692
// future, this function may expand when more ban criteria is added.
3693
//
3694
// NOTE: The server's write lock MUST be held when this is called.
3695
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3696
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3697
                delete(s.persistentPeers, remotePub)
×
3698
                delete(s.persistentPeersBackoff, remotePub)
×
3699
                delete(s.persistentPeerAddrs, remotePub)
×
3700
                s.cancelConnReqs(remotePub, nil)
×
3701
        }
×
3702
}
3703

3704
// BroadcastMessage sends a request to the server to broadcast a set of
3705
// messages to all peers other than the one specified by the `skips` parameter.
3706
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3707
// the target peers.
3708
//
3709
// NOTE: This function is safe for concurrent access.
3710
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3711
        msgs ...lnwire.Message) error {
×
3712

×
3713
        // Filter out peers found in the skips map. We synchronize access to
×
3714
        // peersByPub throughout this process to ensure we deliver messages to
×
3715
        // exact set of peers present at the time of invocation.
×
3716
        s.mu.RLock()
×
3717
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
3718
        for pubStr, sPeer := range s.peersByPub {
×
3719
                if skips != nil {
×
3720
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
3721
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
3722
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
3723
                                continue
×
3724
                        }
3725
                }
3726

3727
                peers = append(peers, sPeer)
×
3728
        }
3729
        s.mu.RUnlock()
×
3730

×
3731
        // Iterate over all known peers, dispatching a go routine to enqueue
×
3732
        // all messages to each of peers.
×
3733
        var wg sync.WaitGroup
×
3734
        for _, sPeer := range peers {
×
3735
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
3736
                        sPeer.PubKey())
×
3737

×
3738
                // Dispatch a go routine to enqueue all messages to this peer.
×
3739
                wg.Add(1)
×
3740
                s.wg.Add(1)
×
3741
                go func(p lnpeer.Peer) {
×
3742
                        defer s.wg.Done()
×
3743
                        defer wg.Done()
×
3744

×
3745
                        p.SendMessageLazy(false, msgs...)
×
3746
                }(sPeer)
×
3747
        }
3748

3749
        // Wait for all messages to have been dispatched before returning to
3750
        // caller.
3751
        wg.Wait()
×
3752

×
3753
        return nil
×
3754
}
3755

3756
// NotifyWhenOnline can be called by other subsystems to get notified when a
3757
// particular peer comes online. The peer itself is sent across the peerChan.
3758
//
3759
// NOTE: This function is safe for concurrent access.
3760
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3761
        peerChan chan<- lnpeer.Peer) {
×
3762

×
3763
        s.mu.Lock()
×
3764

×
3765
        // Compute the target peer's identifier.
×
3766
        pubStr := string(peerKey[:])
×
3767

×
3768
        // Check if peer is connected.
×
3769
        peer, ok := s.peersByPub[pubStr]
×
3770
        if ok {
×
3771
                // Unlock here so that the mutex isn't held while we are
×
3772
                // waiting for the peer to become active.
×
3773
                s.mu.Unlock()
×
3774

×
3775
                // Wait until the peer signals that it is actually active
×
3776
                // rather than only in the server's maps.
×
3777
                select {
×
3778
                case <-peer.ActiveSignal():
×
3779
                case <-peer.QuitSignal():
×
3780
                        // The peer quit, so we'll add the channel to the slice
×
3781
                        // and return.
×
3782
                        s.mu.Lock()
×
3783
                        s.peerConnectedListeners[pubStr] = append(
×
3784
                                s.peerConnectedListeners[pubStr], peerChan,
×
3785
                        )
×
3786
                        s.mu.Unlock()
×
3787
                        return
×
3788
                }
3789

3790
                // Connected, can return early.
3791
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
3792

×
3793
                select {
×
3794
                case peerChan <- peer:
×
3795
                case <-s.quit:
×
3796
                }
3797

3798
                return
×
3799
        }
3800

3801
        // Not connected, store this listener such that it can be notified when
3802
        // the peer comes online.
3803
        s.peerConnectedListeners[pubStr] = append(
×
3804
                s.peerConnectedListeners[pubStr], peerChan,
×
3805
        )
×
3806
        s.mu.Unlock()
×
3807
}
3808

3809
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3810
// the given public key has been disconnected. The notification is signaled by
3811
// closing the channel returned.
3812
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
3813
        s.mu.Lock()
×
3814
        defer s.mu.Unlock()
×
3815

×
3816
        c := make(chan struct{})
×
3817

×
3818
        // If the peer is already offline, we can immediately trigger the
×
3819
        // notification.
×
3820
        peerPubKeyStr := string(peerPubKey[:])
×
3821
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3822
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3823
                close(c)
×
3824
                return c
×
3825
        }
×
3826

3827
        // Otherwise, the peer is online, so we'll keep track of the channel to
3828
        // trigger the notification once the server detects the peer
3829
        // disconnects.
3830
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
3831
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
3832
        )
×
3833

×
3834
        return c
×
3835
}
3836

3837
// FindPeer will return the peer that corresponds to the passed in public key.
3838
// This function is used by the funding manager, allowing it to update the
3839
// daemon's local representation of the remote peer.
3840
//
3841
// NOTE: This function is safe for concurrent access.
3842
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
3843
        s.mu.RLock()
×
3844
        defer s.mu.RUnlock()
×
3845

×
3846
        pubStr := string(peerKey.SerializeCompressed())
×
3847

×
3848
        return s.findPeerByPubStr(pubStr)
×
3849
}
×
3850

3851
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3852
// which should be a string representation of the peer's serialized, compressed
3853
// public key.
3854
//
3855
// NOTE: This function is safe for concurrent access.
3856
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3857
        s.mu.RLock()
×
3858
        defer s.mu.RUnlock()
×
3859

×
3860
        return s.findPeerByPubStr(pubStr)
×
3861
}
×
3862

3863
// findPeerByPubStr is an internal method that retrieves the specified peer from
3864
// the server's internal state using.
3865
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3866
        peer, ok := s.peersByPub[pubStr]
×
3867
        if !ok {
×
3868
                return nil, ErrPeerNotConnected
×
3869
        }
×
3870

3871
        return peer, nil
×
3872
}
3873

3874
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3875
// exponential backoff. If no previous backoff was known, the default is
3876
// returned.
3877
func (s *server) nextPeerBackoff(pubStr string,
3878
        startTime time.Time) time.Duration {
×
3879

×
3880
        // Now, determine the appropriate backoff to use for the retry.
×
3881
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
3882
        if !ok {
×
3883
                // If an existing backoff was unknown, use the default.
×
3884
                return s.cfg.MinBackoff
×
3885
        }
×
3886

3887
        // If the peer failed to start properly, we'll just use the previous
3888
        // backoff to compute the subsequent randomized exponential backoff
3889
        // duration. This will roughly double on average.
3890
        if startTime.IsZero() {
×
3891
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3892
        }
×
3893

3894
        // The peer succeeded in starting. If the connection didn't last long
3895
        // enough to be considered stable, we'll continue to back off retries
3896
        // with this peer.
3897
        connDuration := time.Since(startTime)
×
3898
        if connDuration < defaultStableConnDuration {
×
3899
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3900
        }
×
3901

3902
        // The peer succeed in starting and this was stable peer, so we'll
3903
        // reduce the timeout duration by the length of the connection after
3904
        // applying randomized exponential backoff. We'll only apply this in the
3905
        // case that:
3906
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3907
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3908
        if relaxedBackoff > s.cfg.MinBackoff {
×
3909
                return relaxedBackoff
×
3910
        }
×
3911

3912
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3913
        // the stable connection lasted much longer than our previous backoff.
3914
        // To reward such good behavior, we'll reconnect after the default
3915
        // timeout.
3916
        return s.cfg.MinBackoff
×
3917
}
3918

3919
// shouldDropLocalConnection determines if our local connection to a remote peer
3920
// should be dropped in the case of concurrent connection establishment. In
3921
// order to deterministically decide which connection should be dropped, we'll
3922
// utilize the ordering of the local and remote public key. If we didn't use
3923
// such a tie breaker, then we risk _both_ connections erroneously being
3924
// dropped.
3925
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3926
        localPubBytes := local.SerializeCompressed()
×
3927
        remotePubPbytes := remote.SerializeCompressed()
×
3928

×
3929
        // The connection that comes from the node with a "smaller" pubkey
×
3930
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3931
        // should drop our established connection.
×
3932
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3933
}
×
3934

3935
// InboundPeerConnected initializes a new peer in response to a new inbound
3936
// connection.
3937
//
3938
// NOTE: This function is safe for concurrent access.
3939
func (s *server) InboundPeerConnected(conn net.Conn) {
×
3940
        // Exit early if we have already been instructed to shutdown, this
×
3941
        // prevents any delayed callbacks from accidentally registering peers.
×
3942
        if s.Stopped() {
×
3943
                return
×
3944
        }
×
3945

3946
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3947
        pubSer := nodePub.SerializeCompressed()
×
3948
        pubStr := string(pubSer)
×
3949

×
3950
        var pubBytes [33]byte
×
3951
        copy(pubBytes[:], pubSer)
×
3952

×
3953
        s.mu.Lock()
×
3954
        defer s.mu.Unlock()
×
3955

×
3956
        // If we already have an outbound connection to this peer, then ignore
×
3957
        // this new connection.
×
3958
        if p, ok := s.outboundPeers[pubStr]; ok {
×
3959
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
3960
                        "ignoring inbound connection from local=%v, remote=%v",
×
3961
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
3962

×
3963
                conn.Close()
×
3964
                return
×
3965
        }
×
3966

3967
        // If we already have a valid connection that is scheduled to take
3968
        // precedence once the prior peer has finished disconnecting, we'll
3969
        // ignore this connection.
3970
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3971
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3972
                        "scheduled", conn.RemoteAddr(), p)
×
3973
                conn.Close()
×
3974
                return
×
3975
        }
×
3976

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

×
3979
        // Check to see if we already have a connection with this peer. If so,
×
3980
        // we may need to drop our existing connection. This prevents us from
×
3981
        // having duplicate connections to the same peer. We forgo adding a
×
3982
        // default case as we expect these to be the only error values returned
×
3983
        // from findPeerByPubStr.
×
3984
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
3985
        switch err {
×
3986
        case ErrPeerNotConnected:
×
3987
                // We were unable to locate an existing connection with the
×
3988
                // target peer, proceed to connect.
×
3989
                s.cancelConnReqs(pubStr, nil)
×
3990
                s.peerConnected(conn, nil, true)
×
3991

3992
        case nil:
×
3993
                ctx := btclog.WithCtx(
×
3994
                        context.TODO(),
×
3995
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
3996
                )
×
3997

×
3998
                // We already have a connection with the incoming peer. If the
×
3999
                // connection we've already established should be kept and is
×
4000
                // not of the same type of the new connection (inbound), then
×
4001
                // we'll close out the new connection s.t there's only a single
×
4002
                // connection between us.
×
4003
                localPub := s.identityECDH.PubKey()
×
4004
                if !connectedPeer.Inbound() &&
×
4005
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4006

×
4007
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4008
                                "peer, but already have outbound "+
×
4009
                                "connection, dropping conn",
×
4010
                                fmt.Errorf("already have outbound conn"))
×
4011
                        conn.Close()
×
4012
                        return
×
4013
                }
×
4014

4015
                // Otherwise, if we should drop the connection, then we'll
4016
                // disconnect our already connected peer.
4017
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4018

×
4019
                s.cancelConnReqs(pubStr, nil)
×
4020

×
4021
                // Remove the current peer from the server's internal state and
×
4022
                // signal that the peer termination watcher does not need to
×
4023
                // execute for this peer.
×
4024
                s.removePeerUnsafe(ctx, connectedPeer)
×
4025
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4026
                s.scheduledPeerConnection[pubStr] = func() {
×
4027
                        s.peerConnected(conn, nil, true)
×
4028
                }
×
4029
        }
4030
}
4031

4032
// OutboundPeerConnected initializes a new peer in response to a new outbound
4033
// connection.
4034
// NOTE: This function is safe for concurrent access.
4035
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
4036
        // Exit early if we have already been instructed to shutdown, this
×
4037
        // prevents any delayed callbacks from accidentally registering peers.
×
4038
        if s.Stopped() {
×
4039
                return
×
4040
        }
×
4041

4042
        nodePub := conn.(*brontide.Conn).RemotePub()
×
4043
        pubSer := nodePub.SerializeCompressed()
×
4044
        pubStr := string(pubSer)
×
4045

×
4046
        var pubBytes [33]byte
×
4047
        copy(pubBytes[:], pubSer)
×
4048

×
4049
        s.mu.Lock()
×
4050
        defer s.mu.Unlock()
×
4051

×
4052
        // If we already have an inbound connection to this peer, then ignore
×
4053
        // this new connection.
×
4054
        if p, ok := s.inboundPeers[pubStr]; ok {
×
4055
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
4056
                        "ignoring outbound connection from local=%v, remote=%v",
×
4057
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
4058

×
4059
                if connReq != nil {
×
4060
                        s.connMgr.Remove(connReq.ID())
×
4061
                }
×
4062
                conn.Close()
×
4063
                return
×
4064
        }
4065
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4066
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4067
                s.connMgr.Remove(connReq.ID())
×
4068
                conn.Close()
×
4069
                return
×
4070
        }
×
4071

4072
        // If we already have a valid connection that is scheduled to take
4073
        // precedence once the prior peer has finished disconnecting, we'll
4074
        // ignore this connection.
4075
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4076
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4077

×
4078
                if connReq != nil {
×
4079
                        s.connMgr.Remove(connReq.ID())
×
4080
                }
×
4081

4082
                conn.Close()
×
4083
                return
×
4084
        }
4085

4086
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
4087
                conn.RemoteAddr())
×
4088

×
4089
        if connReq != nil {
×
4090
                // A successful connection was returned by the connmgr.
×
4091
                // Immediately cancel all pending requests, excluding the
×
4092
                // outbound connection we just established.
×
4093
                ignore := connReq.ID()
×
4094
                s.cancelConnReqs(pubStr, &ignore)
×
4095
        } else {
×
4096
                // This was a successful connection made by some other
×
4097
                // subsystem. Remove all requests being managed by the connmgr.
×
4098
                s.cancelConnReqs(pubStr, nil)
×
4099
        }
×
4100

4101
        // If we already have a connection with this peer, decide whether or not
4102
        // we need to drop the stale connection. We forgo adding a default case
4103
        // as we expect these to be the only error values returned from
4104
        // findPeerByPubStr.
4105
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
4106
        switch err {
×
4107
        case ErrPeerNotConnected:
×
4108
                // We were unable to locate an existing connection with the
×
4109
                // target peer, proceed to connect.
×
4110
                s.peerConnected(conn, connReq, false)
×
4111

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

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

×
4127
                        srvrLog.WarnS(ctx, "Established outbound connection "+
×
4128
                                "to peer, but already have inbound "+
×
4129
                                "connection, dropping conn",
×
4130
                                fmt.Errorf("already have inbound conn"))
×
4131
                        if connReq != nil {
×
4132
                                s.connMgr.Remove(connReq.ID())
×
4133
                        }
×
4134
                        conn.Close()
×
4135
                        return
×
4136
                }
4137

4138
                // Otherwise, _their_ connection should be dropped. So we'll
4139
                // disconnect the peer and send the now obsolete peer to the
4140
                // server for garbage collection.
4141
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4142

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

4154
// UnassignedConnID is the default connection ID that a request can have before
4155
// it actually is submitted to the connmgr.
4156
// TODO(conner): move into connmgr package, or better, add connmgr method for
4157
// generating atomic IDs
4158
const UnassignedConnID uint64 = 0
4159

4160
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4161
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4162
// Afterwards, each connection request removed from the connmgr. The caller can
4163
// optionally specify a connection ID to ignore, which prevents us from
4164
// canceling a successful request. All persistent connreqs for the provided
4165
// pubkey are discarded after the operationjw.
4166
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
4167
        // First, cancel any lingering persistent retry attempts, which will
×
4168
        // prevent retries for any with backoffs that are still maturing.
×
4169
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
4170
                close(cancelChan)
×
4171
                delete(s.persistentRetryCancels, pubStr)
×
4172
        }
×
4173

4174
        // Next, check to see if we have any outstanding persistent connection
4175
        // requests to this peer. If so, then we'll remove all of these
4176
        // connection requests, and also delete the entry from the map.
4177
        connReqs, ok := s.persistentConnReqs[pubStr]
×
4178
        if !ok {
×
4179
                return
×
4180
        }
×
4181

4182
        for _, connReq := range connReqs {
×
4183
                srvrLog.Tracef("Canceling %s:", connReqs)
×
4184

×
4185
                // Atomically capture the current request identifier.
×
4186
                connID := connReq.ID()
×
4187

×
4188
                // Skip any zero IDs, this indicates the request has not
×
4189
                // yet been schedule.
×
4190
                if connID == UnassignedConnID {
×
4191
                        continue
×
4192
                }
4193

4194
                // Skip a particular connection ID if instructed.
4195
                if skip != nil && connID == *skip {
×
4196
                        continue
×
4197
                }
4198

4199
                s.connMgr.Remove(connID)
×
4200
        }
4201

4202
        delete(s.persistentConnReqs, pubStr)
×
4203
}
4204

4205
// handleCustomMessage dispatches an incoming custom peers message to
4206
// subscribers.
4207
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
4208
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
4209
                peer, msg.Type)
×
4210

×
4211
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4212
                Peer: peer,
×
4213
                Msg:  msg,
×
4214
        })
×
4215
}
×
4216

4217
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4218
// messages.
4219
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4220
        return s.customMessageServer.Subscribe()
×
4221
}
×
4222

4223
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4224
// the channelNotifier's NotifyOpenChannelEvent.
4225
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4226
        remotePub *btcec.PublicKey) {
×
4227

×
4228
        // Call newOpenChan to update the access manager's maps for this peer.
×
4229
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
4230
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4231
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
4232
        }
×
4233

4234
        // Notify subscribers about this open channel event.
4235
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4236
}
4237

4238
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4239
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4240
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4241
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
4242

×
4243
        // Call newPendingOpenChan to update the access manager's maps for this
×
4244
        // peer.
×
4245
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
4246
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4247
                        "channel[%v] pending open",
×
4248
                        remotePub.SerializeCompressed(), op)
×
4249
        }
×
4250

4251
        // Notify subscribers about this event.
4252
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4253
}
4254

4255
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4256
// calls the channelNotifier's NotifyFundingTimeout.
4257
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4258
        remotePub *btcec.PublicKey) {
×
4259

×
4260
        // Call newPendingCloseChan to potentially demote the peer.
×
4261
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
4262
        if err != nil {
×
4263
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4264
                        "channel[%v] pending close",
×
4265
                        remotePub.SerializeCompressed(), op)
×
4266
        }
×
4267

4268
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4269
                // If we encounter an error while attempting to disconnect the
×
4270
                // peer, log the error.
×
4271
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4272
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4273
                }
×
4274
        }
4275

4276
        // Notify subscribers about this event.
4277
        s.channelNotifier.NotifyFundingTimeout(op)
×
4278
}
4279

4280
// peerConnected is a function that handles initialization a newly connected
4281
// peer by adding it to the server's global list of all active peers, and
4282
// starting all the goroutines the peer needs to function properly. The inbound
4283
// boolean should be true if the peer initiated the connection to us.
4284
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4285
        inbound bool) {
×
4286

×
4287
        brontideConn := conn.(*brontide.Conn)
×
4288
        addr := conn.RemoteAddr()
×
4289
        pubKey := brontideConn.RemotePub()
×
4290

×
4291
        // Only restrict access for inbound connections, which means if the
×
4292
        // remote node's public key is banned or the restricted slots are used
×
4293
        // up, we will drop the connection.
×
4294
        //
×
4295
        // TODO(yy): Consider perform this check in
×
4296
        // `peerAccessMan.addPeerAccess`.
×
4297
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
4298
        if inbound && err != nil {
×
4299
                pubSer := pubKey.SerializeCompressed()
×
4300

×
4301
                // Clean up the persistent peer maps if we're dropping this
×
4302
                // connection.
×
4303
                s.bannedPersistentPeerConnection(string(pubSer))
×
4304

×
4305
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4306
                        "of restricted-access connection slots: %v.", pubSer,
×
4307
                        err)
×
4308

×
4309
                conn.Close()
×
4310

×
4311
                return
×
4312
        }
×
4313

4314
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4315
                pubKey.SerializeCompressed(), addr, inbound)
×
4316

×
4317
        peerAddr := &lnwire.NetAddress{
×
4318
                IdentityKey: pubKey,
×
4319
                Address:     addr,
×
4320
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4321
        }
×
4322

×
4323
        // With the brontide connection established, we'll now craft the feature
×
4324
        // vectors to advertise to the remote node.
×
4325
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
4326
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4327

×
4328
        // Lookup past error caches for the peer in the server. If no buffer is
×
4329
        // found, create a fresh buffer.
×
4330
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
4331
        errBuffer, ok := s.peerErrors[pkStr]
×
4332
        if !ok {
×
4333
                var err error
×
4334
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
4335
                if err != nil {
×
4336
                        srvrLog.Errorf("unable to create peer %v", err)
×
4337
                        return
×
4338
                }
×
4339
        }
4340

4341
        // If we directly set the peer.Config TowerClient member to the
4342
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4343
        // the peer.Config's TowerClient member will not evaluate to nil even
4344
        // though the underlying value is nil. To avoid this gotcha which can
4345
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4346
        // TowerClient if needed.
4347
        var towerClient wtclient.ClientManager
×
4348
        if s.towerClientMgr != nil {
×
4349
                towerClient = s.towerClientMgr
×
4350
        }
×
4351

4352
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
4353
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
4354

×
4355
        // Now that we've established a connection, create a peer, and it to the
×
4356
        // set of currently active peers. Configure the peer with the incoming
×
4357
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
4358
        // offered that would trigger channel closure. In case of outgoing
×
4359
        // htlcs, an extra block is added to prevent the channel from being
×
4360
        // closed when the htlc is outstanding and a new block comes in.
×
4361
        pCfg := peer.Config{
×
4362
                Conn:                    brontideConn,
×
4363
                ConnReq:                 connReq,
×
4364
                Addr:                    peerAddr,
×
4365
                Inbound:                 inbound,
×
4366
                Features:                initFeatures,
×
4367
                LegacyFeatures:          legacyFeatures,
×
4368
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
4369
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
4370
                ErrorBuffer:             errBuffer,
×
4371
                WritePool:               s.writePool,
×
4372
                ReadPool:                s.readPool,
×
4373
                Switch:                  s.htlcSwitch,
×
4374
                InterceptSwitch:         s.interceptableSwitch,
×
4375
                ChannelDB:               s.chanStateDB,
×
4376
                ChannelGraph:            s.graphDB,
×
4377
                ChainArb:                s.chainArb,
×
4378
                AuthGossiper:            s.authGossiper,
×
4379
                ChanStatusMgr:           s.chanStatusMgr,
×
4380
                ChainIO:                 s.cc.ChainIO,
×
4381
                FeeEstimator:            s.cc.FeeEstimator,
×
4382
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
4383
                SigPool:                 s.sigPool,
×
4384
                Wallet:                  s.cc.Wallet,
×
4385
                ChainNotifier:           s.cc.ChainNotifier,
×
4386
                BestBlockView:           s.cc.BestBlockTracker,
×
4387
                RoutingPolicy:           s.cc.RoutingPolicy,
×
4388
                Sphinx:                  s.sphinx,
×
4389
                WitnessBeacon:           s.witnessBeacon,
×
4390
                Invoices:                s.invoices,
×
4391
                ChannelNotifier:         s.channelNotifier,
×
4392
                HtlcNotifier:            s.htlcNotifier,
×
4393
                TowerClient:             towerClient,
×
4394
                DisconnectPeer:          s.DisconnectPeer,
×
4395
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
4396
                        lnwire.NodeAnnouncement, error) {
×
4397

×
4398
                        return s.genNodeAnnouncement(nil)
×
4399
                },
×
4400

4401
                PongBuf: s.pongBuf,
4402

4403
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4404

4405
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4406

4407
                FundingManager: s.fundingMgr,
4408

4409
                Hodl:                    s.cfg.Hodl,
4410
                UnsafeReplay:            s.cfg.UnsafeReplay,
4411
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4412
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4413
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4414
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4415
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4416
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4417
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4418
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4419
                HandleCustomMessage:    s.handleCustomMessage,
4420
                GetAliases:             s.aliasMgr.GetAliases,
4421
                RequestAlias:           s.aliasMgr.RequestAlias,
4422
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4423
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4424
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4425
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4426
                MaxFeeExposure:         thresholdMSats,
4427
                Quit:                   s.quit,
4428
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4429
                AuxSigner:              s.implCfg.AuxSigner,
4430
                MsgRouter:              s.implCfg.MsgRouter,
4431
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4432
                AuxResolver:            s.implCfg.AuxContractResolver,
4433
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4434
                ShouldFwdExpEndorsement: func() bool {
×
4435
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
4436
                                return false
×
4437
                        }
×
4438

4439
                        return clock.NewDefaultClock().Now().Before(
×
4440
                                EndorsementExperimentEnd,
×
4441
                        )
×
4442
                },
4443
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4444
        }
4445

4446
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
4447
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
4448

×
4449
        p := peer.NewBrontide(pCfg)
×
4450

×
4451
        // Update the access manager with the access permission for this peer.
×
4452
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
4453

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

×
4457
        s.addPeer(p)
×
4458

×
4459
        // Once we have successfully added the peer to the server, we can
×
4460
        // delete the previous error buffer from the server's map of error
×
4461
        // buffers.
×
4462
        delete(s.peerErrors, pkStr)
×
4463

×
4464
        // Dispatch a goroutine to asynchronously start the peer. This process
×
4465
        // includes sending and receiving Init messages, which would be a DOS
×
4466
        // vector if we held the server's mutex throughout the procedure.
×
4467
        s.wg.Add(1)
×
4468
        go s.peerInitializer(p)
×
4469
}
4470

4471
// addPeer adds the passed peer to the server's global state of all active
4472
// peers.
4473
func (s *server) addPeer(p *peer.Brontide) {
×
4474
        if p == nil {
×
4475
                return
×
4476
        }
×
4477

4478
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4479

×
4480
        // Ignore new peers if we're shutting down.
×
4481
        if s.Stopped() {
×
4482
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4483
                        pubBytes)
×
4484
                p.Disconnect(ErrServerShuttingDown)
×
4485

×
4486
                return
×
4487
        }
×
4488

4489
        // Track the new peer in our indexes so we can quickly look it up either
4490
        // according to its public key, or its peer ID.
4491
        // TODO(roasbeef): pipe all requests through to the
4492
        // queryHandler/peerManager
4493

4494
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4495
        // be human-readable.
4496
        pubStr := string(pubBytes)
×
4497

×
4498
        s.peersByPub[pubStr] = p
×
4499

×
4500
        if p.Inbound() {
×
4501
                s.inboundPeers[pubStr] = p
×
4502
        } else {
×
4503
                s.outboundPeers[pubStr] = p
×
4504
        }
×
4505

4506
        // Inform the peer notifier of a peer online event so that it can be reported
4507
        // to clients listening for peer events.
4508
        var pubKey [33]byte
×
4509
        copy(pubKey[:], pubBytes)
×
4510
}
4511

4512
// peerInitializer asynchronously starts a newly connected peer after it has
4513
// been added to the server's peer map. This method sets up a
4514
// peerTerminationWatcher for the given peer, and ensures that it executes even
4515
// if the peer failed to start. In the event of a successful connection, this
4516
// method reads the negotiated, local feature-bits and spawns the appropriate
4517
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4518
// be signaled of the new peer once the method returns.
4519
//
4520
// NOTE: This MUST be launched as a goroutine.
4521
func (s *server) peerInitializer(p *peer.Brontide) {
×
4522
        defer s.wg.Done()
×
4523

×
4524
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4525

×
4526
        // Avoid initializing peers while the server is exiting.
×
4527
        if s.Stopped() {
×
4528
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4529
                        pubBytes)
×
4530
                return
×
4531
        }
×
4532

4533
        // Create a channel that will be used to signal a successful start of
4534
        // the link. This prevents the peer termination watcher from beginning
4535
        // its duty too early.
4536
        ready := make(chan struct{})
×
4537

×
4538
        // Before starting the peer, launch a goroutine to watch for the
×
4539
        // unexpected termination of this peer, which will ensure all resources
×
4540
        // are properly cleaned up, and re-establish persistent connections when
×
4541
        // necessary. The peer termination watcher will be short circuited if
×
4542
        // the peer is ever added to the ignorePeerTermination map, indicating
×
4543
        // that the server has already handled the removal of this peer.
×
4544
        s.wg.Add(1)
×
4545
        go s.peerTerminationWatcher(p, ready)
×
4546

×
4547
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
4548
        // will unblock the peerTerminationWatcher.
×
4549
        if err := p.Start(); err != nil {
×
4550
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4551

×
4552
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4553
                return
×
4554
        }
×
4555

4556
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4557
        // was successful, and to begin watching the peer's wait group.
4558
        close(ready)
×
4559

×
4560
        s.mu.Lock()
×
4561
        defer s.mu.Unlock()
×
4562

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

×
4566
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
4567
        // route.Vertex as the key type of peerConnectedListeners.
×
4568
        pubStr := string(pubBytes)
×
4569
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
4570
                select {
×
4571
                case peerChan <- p:
×
4572
                case <-s.quit:
×
4573
                        return
×
4574
                }
4575
        }
4576
        delete(s.peerConnectedListeners, pubStr)
×
4577

×
4578
        // Since the peer has been fully initialized, now it's time to notify
×
4579
        // the RPC about the peer online event.
×
4580
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4581
}
4582

4583
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4584
// and then cleans up all resources allocated to the peer, notifies relevant
4585
// sub-systems of its demise, and finally handles re-connecting to the peer if
4586
// it's persistent. If the server intentionally disconnects a peer, it should
4587
// have a corresponding entry in the ignorePeerTermination map which will cause
4588
// the cleanup routine to exit early. The passed `ready` chan is used to
4589
// synchronize when WaitForDisconnect should begin watching on the peer's
4590
// waitgroup. The ready chan should only be signaled if the peer starts
4591
// successfully, otherwise the peer should be disconnected instead.
4592
//
4593
// NOTE: This MUST be launched as a goroutine.
4594
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
4595
        defer s.wg.Done()
×
4596

×
4597
        ctx := btclog.WithCtx(
×
4598
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
4599
        )
×
4600

×
4601
        p.WaitForDisconnect(ready)
×
4602

×
4603
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
4604

×
4605
        // If the server is exiting then we can bail out early ourselves as all
×
4606
        // the other sub-systems will already be shutting down.
×
4607
        if s.Stopped() {
×
4608
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
4609
                return
×
4610
        }
×
4611

4612
        // Next, we'll cancel all pending funding reservations with this node.
4613
        // If we tried to initiate any funding flows that haven't yet finished,
4614
        // then we need to unlock those committed outputs so they're still
4615
        // available for use.
4616
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
4617

×
4618
        pubKey := p.IdentityKey()
×
4619

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

×
4624
        // Tell the switch to remove all links associated with this peer.
×
4625
        // Passing nil as the target link indicates that all links associated
×
4626
        // with this interface should be closed.
×
4627
        //
×
4628
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
4629
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
4630
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4631
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4632
        }
×
4633

4634
        for _, link := range links {
×
4635
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4636
        }
×
4637

4638
        s.mu.Lock()
×
4639
        defer s.mu.Unlock()
×
4640

×
4641
        // If there were any notification requests for when this peer
×
4642
        // disconnected, we can trigger them now.
×
4643
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
4644
        pubStr := string(pubKey.SerializeCompressed())
×
4645
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
4646
                close(offlineChan)
×
4647
        }
×
4648
        delete(s.peerDisconnectedListeners, pubStr)
×
4649

×
4650
        // If the server has already removed this peer, we can short circuit the
×
4651
        // peer termination watcher and skip cleanup.
×
4652
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4653
                delete(s.ignorePeerTermination, p)
×
4654

×
4655
                pubKey := p.PubKey()
×
4656
                pubStr := string(pubKey[:])
×
4657

×
4658
                // If a connection callback is present, we'll go ahead and
×
4659
                // execute it now that previous peer has fully disconnected. If
×
4660
                // the callback is not present, this likely implies the peer was
×
4661
                // purposefully disconnected via RPC, and that no reconnect
×
4662
                // should be attempted.
×
4663
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4664
                if ok {
×
4665
                        delete(s.scheduledPeerConnection, pubStr)
×
4666
                        connCallback()
×
4667
                }
×
4668
                return
×
4669
        }
4670

4671
        // First, cleanup any remaining state the server has regarding the peer
4672
        // in question.
4673
        s.removePeerUnsafe(ctx, p)
×
4674

×
4675
        // Next, check to see if this is a persistent peer or not.
×
4676
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4677
                return
×
4678
        }
×
4679

4680
        // Get the last address that we used to connect to the peer.
4681
        addrs := []net.Addr{
×
4682
                p.NetAddress().Address,
×
4683
        }
×
4684

×
4685
        // We'll ensure that we locate all the peers advertised addresses for
×
4686
        // reconnection purposes.
×
4687
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
4688
        switch {
×
4689
        // We found advertised addresses, so use them.
4690
        case err == nil:
×
4691
                addrs = advertisedAddrs
×
4692

4693
        // The peer doesn't have an advertised address.
4694
        case err == errNoAdvertisedAddr:
×
4695
                // If it is an outbound peer then we fall back to the existing
×
4696
                // peer address.
×
4697
                if !p.Inbound() {
×
4698
                        break
×
4699
                }
4700

4701
                // Fall back to the existing peer address if
4702
                // we're not accepting connections over Tor.
4703
                if s.torController == nil {
×
4704
                        break
×
4705
                }
4706

4707
                // If we are, the peer's address won't be known
4708
                // to us (we'll see a private address, which is
4709
                // the address used by our onion service to dial
4710
                // to lnd), so we don't have enough information
4711
                // to attempt a reconnect.
4712
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4713
                        "to inbound peer without advertised address")
×
4714
                return
×
4715

4716
        // We came across an error retrieving an advertised
4717
        // address, log it, and fall back to the existing peer
4718
        // address.
4719
        default:
×
4720
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
4721
                        "address for peer", err)
×
4722
        }
4723

4724
        // Make an easy lookup map so that we can check if an address
4725
        // is already in the address list that we have stored for this peer.
4726
        existingAddrs := make(map[string]bool)
×
4727
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
4728
                existingAddrs[addr.String()] = true
×
4729
        }
×
4730

4731
        // Add any missing addresses for this peer to persistentPeerAddr.
4732
        for _, addr := range addrs {
×
4733
                if existingAddrs[addr.String()] {
×
4734
                        continue
×
4735
                }
4736

4737
                s.persistentPeerAddrs[pubStr] = append(
×
4738
                        s.persistentPeerAddrs[pubStr],
×
4739
                        &lnwire.NetAddress{
×
4740
                                IdentityKey: p.IdentityKey(),
×
4741
                                Address:     addr,
×
4742
                                ChainNet:    p.NetAddress().ChainNet,
×
4743
                        },
×
4744
                )
×
4745
        }
4746

4747
        // Record the computed backoff in the backoff map.
4748
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4749
        s.persistentPeersBackoff[pubStr] = backoff
×
4750

×
4751
        // Initialize a retry canceller for this peer if one does not
×
4752
        // exist.
×
4753
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4754
        if !ok {
×
4755
                cancelChan = make(chan struct{})
×
4756
                s.persistentRetryCancels[pubStr] = cancelChan
×
4757
        }
×
4758

4759
        // We choose not to wait group this go routine since the Connect
4760
        // call can stall for arbitrarily long if we shutdown while an
4761
        // outbound connection attempt is being made.
4762
        go func() {
×
4763
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
4764
                        "re-establishment to persistent peer",
×
4765
                        "reconnecting_in", backoff)
×
4766

×
4767
                select {
×
4768
                case <-time.After(backoff):
×
4769
                case <-cancelChan:
×
4770
                        return
×
4771
                case <-s.quit:
×
4772
                        return
×
4773
                }
4774

4775
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
4776
                        "connection")
×
4777

×
4778
                s.connectToPersistentPeer(pubStr)
×
4779
        }()
4780
}
4781

4782
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4783
// to connect to the peer. It creates connection requests if there are
4784
// currently none for a given address and it removes old connection requests
4785
// if the associated address is no longer in the latest address list for the
4786
// peer.
4787
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
4788
        s.mu.Lock()
×
4789
        defer s.mu.Unlock()
×
4790

×
4791
        // Create an easy lookup map of the addresses we have stored for the
×
4792
        // peer. We will remove entries from this map if we have existing
×
4793
        // connection requests for the associated address and then any leftover
×
4794
        // entries will indicate which addresses we should create new
×
4795
        // connection requests for.
×
4796
        addrMap := make(map[string]*lnwire.NetAddress)
×
4797
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
4798
                addrMap[addr.String()] = addr
×
4799
        }
×
4800

4801
        // Go through each of the existing connection requests and
4802
        // check if they correspond to the latest set of addresses. If
4803
        // there is a connection requests that does not use one of the latest
4804
        // advertised addresses then remove that connection request.
4805
        var updatedConnReqs []*connmgr.ConnReq
×
4806
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
4807
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
4808

×
4809
                switch _, ok := addrMap[lnAddr]; ok {
×
4810
                // If the existing connection request is using one of the
4811
                // latest advertised addresses for the peer then we add it to
4812
                // updatedConnReqs and remove the associated address from
4813
                // addrMap so that we don't recreate this connReq later on.
4814
                case true:
×
4815
                        updatedConnReqs = append(
×
4816
                                updatedConnReqs, connReq,
×
4817
                        )
×
4818
                        delete(addrMap, lnAddr)
×
4819

4820
                // If the existing connection request is using an address that
4821
                // is not one of the latest advertised addresses for the peer
4822
                // then we remove the connecting request from the connection
4823
                // manager.
4824
                case false:
×
4825
                        srvrLog.Info(
×
4826
                                "Removing conn req:", connReq.Addr.String(),
×
4827
                        )
×
4828
                        s.connMgr.Remove(connReq.ID())
×
4829
                }
4830
        }
4831

4832
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
4833

×
4834
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
4835
        if !ok {
×
4836
                cancelChan = make(chan struct{})
×
4837
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
4838
        }
×
4839

4840
        // Any addresses left in addrMap are new ones that we have not made
4841
        // connection requests for. So create new connection requests for those.
4842
        // If there is more than one address in the address map, stagger the
4843
        // creation of the connection requests for those.
4844
        go func() {
×
4845
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4846
                defer ticker.Stop()
×
4847

×
4848
                for _, addr := range addrMap {
×
4849
                        // Send the persistent connection request to the
×
4850
                        // connection manager, saving the request itself so we
×
4851
                        // can cancel/restart the process as needed.
×
4852
                        connReq := &connmgr.ConnReq{
×
4853
                                Addr:      addr,
×
4854
                                Permanent: true,
×
4855
                        }
×
4856

×
4857
                        s.mu.Lock()
×
4858
                        s.persistentConnReqs[pubKeyStr] = append(
×
4859
                                s.persistentConnReqs[pubKeyStr], connReq,
×
4860
                        )
×
4861
                        s.mu.Unlock()
×
4862

×
4863
                        srvrLog.Debugf("Attempting persistent connection to "+
×
4864
                                "channel peer %v", addr)
×
4865

×
4866
                        go s.connMgr.Connect(connReq)
×
4867

×
4868
                        select {
×
4869
                        case <-s.quit:
×
4870
                                return
×
4871
                        case <-cancelChan:
×
4872
                                return
×
4873
                        case <-ticker.C:
×
4874
                        }
4875
                }
4876
        }()
4877
}
4878

4879
// removePeerUnsafe removes the passed peer from the server's state of all
4880
// active peers.
4881
//
4882
// NOTE: Server mutex must be held when calling this function.
4883
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
4884
        if p == nil {
×
4885
                return
×
4886
        }
×
4887

4888
        srvrLog.DebugS(ctx, "Removing peer")
×
4889

×
4890
        // Exit early if we have already been instructed to shutdown, the peers
×
4891
        // will be disconnected in the server shutdown process.
×
4892
        if s.Stopped() {
×
4893
                return
×
4894
        }
×
4895

4896
        // Capture the peer's public key and string representation.
4897
        pKey := p.PubKey()
×
4898
        pubSer := pKey[:]
×
4899
        pubStr := string(pubSer)
×
4900

×
4901
        delete(s.peersByPub, pubStr)
×
4902

×
4903
        if p.Inbound() {
×
4904
                delete(s.inboundPeers, pubStr)
×
4905
        } else {
×
4906
                delete(s.outboundPeers, pubStr)
×
4907
        }
×
4908

4909
        // When removing the peer we make sure to disconnect it asynchronously
4910
        // to avoid blocking the main server goroutine because it is holding the
4911
        // server's mutex. Disconnecting the peer might block and wait until the
4912
        // peer has fully started up. This can happen if an inbound and outbound
4913
        // race condition occurs.
4914
        s.wg.Add(1)
×
4915
        go func() {
×
4916
                defer s.wg.Done()
×
4917

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

×
4920
                // If this peer had an active persistent connection request,
×
4921
                // remove it.
×
4922
                if p.ConnReq() != nil {
×
4923
                        s.connMgr.Remove(p.ConnReq().ID())
×
4924
                }
×
4925

4926
                // Remove the peer's access permission from the access manager.
4927
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
4928
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
4929

×
4930
                // Copy the peer's error buffer across to the server if it has
×
4931
                // any items in it so that we can restore peer errors across
×
4932
                // connections. We need to look up the error after the peer has
×
4933
                // been disconnected because we write the error in the
×
4934
                // `Disconnect` method.
×
4935
                s.mu.Lock()
×
4936
                if p.ErrorBuffer().Total() > 0 {
×
4937
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
4938
                }
×
4939
                s.mu.Unlock()
×
4940

×
4941
                // Inform the peer notifier of a peer offline event so that it
×
4942
                // can be reported to clients listening for peer events.
×
4943
                var pubKey [33]byte
×
4944
                copy(pubKey[:], pubSer)
×
4945

×
4946
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4947
        }()
4948
}
4949

4950
// ConnectToPeer requests that the server connect to a Lightning Network peer
4951
// at the specified address. This function will *block* until either a
4952
// connection is established, or the initial handshake process fails.
4953
//
4954
// NOTE: This function is safe for concurrent access.
4955
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4956
        perm bool, timeout time.Duration) error {
×
4957

×
4958
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
4959

×
4960
        // Acquire mutex, but use explicit unlocking instead of defer for
×
4961
        // better granularity.  In certain conditions, this method requires
×
4962
        // making an outbound connection to a remote peer, which requires the
×
4963
        // lock to be released, and subsequently reacquired.
×
4964
        s.mu.Lock()
×
4965

×
4966
        // Ensure we're not already connected to this peer.
×
4967
        peer, err := s.findPeerByPubStr(targetPub)
×
4968

×
4969
        // When there's no error it means we already have a connection with this
×
4970
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
4971
        // set, we will ignore the existing connection and continue.
×
4972
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
4973
                s.mu.Unlock()
×
4974
                return &errPeerAlreadyConnected{peer: peer}
×
4975
        }
×
4976

4977
        // Peer was not found, continue to pursue connection with peer.
4978

4979
        // If there's already a pending connection request for this pubkey,
4980
        // then we ignore this request to ensure we don't create a redundant
4981
        // connection.
4982
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
4983
                srvrLog.Warnf("Already have %d persistent connection "+
×
4984
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
4985
        }
×
4986

4987
        // If there's not already a pending or active connection to this node,
4988
        // then instruct the connection manager to attempt to establish a
4989
        // persistent connection to the peer.
4990
        srvrLog.Debugf("Connecting to %v", addr)
×
4991
        if perm {
×
4992
                connReq := &connmgr.ConnReq{
×
4993
                        Addr:      addr,
×
4994
                        Permanent: true,
×
4995
                }
×
4996

×
4997
                // Since the user requested a permanent connection, we'll set
×
4998
                // the entry to true which will tell the server to continue
×
4999
                // reconnecting even if the number of channels with this peer is
×
5000
                // zero.
×
5001
                s.persistentPeers[targetPub] = true
×
5002
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
5003
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
5004
                }
×
5005
                s.persistentConnReqs[targetPub] = append(
×
5006
                        s.persistentConnReqs[targetPub], connReq,
×
5007
                )
×
5008
                s.mu.Unlock()
×
5009

×
5010
                go s.connMgr.Connect(connReq)
×
5011

×
5012
                return nil
×
5013
        }
5014
        s.mu.Unlock()
×
5015

×
5016
        // If we're not making a persistent connection, then we'll attempt to
×
5017
        // connect to the target peer. If the we can't make the connection, or
×
5018
        // the crypto negotiation breaks down, then return an error to the
×
5019
        // caller.
×
5020
        errChan := make(chan error, 1)
×
5021
        s.connectToPeer(addr, errChan, timeout)
×
5022

×
5023
        select {
×
5024
        case err := <-errChan:
×
5025
                return err
×
5026
        case <-s.quit:
×
5027
                return ErrServerShuttingDown
×
5028
        }
5029
}
5030

5031
// connectToPeer establishes a connection to a remote peer. errChan is used to
5032
// notify the caller if the connection attempt has failed. Otherwise, it will be
5033
// closed.
5034
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5035
        errChan chan<- error, timeout time.Duration) {
×
5036

×
5037
        conn, err := brontide.Dial(
×
5038
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
5039
        )
×
5040
        if err != nil {
×
5041
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
5042
                select {
×
5043
                case errChan <- err:
×
5044
                case <-s.quit:
×
5045
                }
5046
                return
×
5047
        }
5048

5049
        close(errChan)
×
5050

×
5051
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
5052
                conn.LocalAddr(), conn.RemoteAddr())
×
5053

×
5054
        s.OutboundPeerConnected(nil, conn)
×
5055
}
5056

5057
// DisconnectPeer sends the request to server to close the connection with peer
5058
// identified by public key.
5059
//
5060
// NOTE: This function is safe for concurrent access.
5061
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
5062
        pubBytes := pubKey.SerializeCompressed()
×
5063
        pubStr := string(pubBytes)
×
5064

×
5065
        s.mu.Lock()
×
5066
        defer s.mu.Unlock()
×
5067

×
5068
        // Check that were actually connected to this peer. If not, then we'll
×
5069
        // exit in an error as we can't disconnect from a peer that we're not
×
5070
        // currently connected to.
×
5071
        peer, err := s.findPeerByPubStr(pubStr)
×
5072
        if err == ErrPeerNotConnected {
×
5073
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
5074
        }
×
5075

5076
        srvrLog.Infof("Disconnecting from %v", peer)
×
5077

×
5078
        s.cancelConnReqs(pubStr, nil)
×
5079

×
5080
        // If this peer was formerly a persistent connection, then we'll remove
×
5081
        // them from this map so we don't attempt to re-connect after we
×
5082
        // disconnect.
×
5083
        delete(s.persistentPeers, pubStr)
×
5084
        delete(s.persistentPeersBackoff, pubStr)
×
5085

×
5086
        // Remove the peer by calling Disconnect. Previously this was done with
×
5087
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
5088
        //
×
5089
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
5090
        // goroutine because we might hold the server's mutex.
×
5091
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
5092

×
5093
        return nil
×
5094
}
5095

5096
// OpenChannel sends a request to the server to open a channel to the specified
5097
// peer identified by nodeKey with the passed channel funding parameters.
5098
//
5099
// NOTE: This function is safe for concurrent access.
5100
func (s *server) OpenChannel(
5101
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
5102

×
5103
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
5104
        // + a ChanOpen update, and we want to make sure the funding process is
×
5105
        // not blocked if the caller is not reading the updates.
×
5106
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
5107
        req.Err = make(chan error, 1)
×
5108

×
5109
        // First attempt to locate the target peer to open a channel with, if
×
5110
        // we're unable to locate the peer then this request will fail.
×
5111
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
5112
        s.mu.RLock()
×
5113
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
5114
        if !ok {
×
5115
                s.mu.RUnlock()
×
5116

×
5117
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5118
                return req.Updates, req.Err
×
5119
        }
×
5120
        req.Peer = peer
×
5121
        s.mu.RUnlock()
×
5122

×
5123
        // We'll wait until the peer is active before beginning the channel
×
5124
        // opening process.
×
5125
        select {
×
5126
        case <-peer.ActiveSignal():
×
5127
        case <-peer.QuitSignal():
×
5128
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5129
                return req.Updates, req.Err
×
5130
        case <-s.quit:
×
5131
                req.Err <- ErrServerShuttingDown
×
5132
                return req.Updates, req.Err
×
5133
        }
5134

5135
        // If the fee rate wasn't specified at this point we fail the funding
5136
        // because of the missing fee rate information. The caller of the
5137
        // `OpenChannel` method needs to make sure that default values for the
5138
        // fee rate are set beforehand.
5139
        if req.FundingFeePerKw == 0 {
×
5140
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5141
                        "the channel opening transaction")
×
5142

×
5143
                return req.Updates, req.Err
×
5144
        }
×
5145

5146
        // Spawn a goroutine to send the funding workflow request to the funding
5147
        // manager. This allows the server to continue handling queries instead
5148
        // of blocking on this request which is exported as a synchronous
5149
        // request to the outside world.
5150
        go s.fundingMgr.InitFundingWorkflow(req)
×
5151

×
5152
        return req.Updates, req.Err
×
5153
}
5154

5155
// Peers returns a slice of all active peers.
5156
//
5157
// NOTE: This function is safe for concurrent access.
5158
func (s *server) Peers() []*peer.Brontide {
×
5159
        s.mu.RLock()
×
5160
        defer s.mu.RUnlock()
×
5161

×
5162
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
5163
        for _, peer := range s.peersByPub {
×
5164
                peers = append(peers, peer)
×
5165
        }
×
5166

5167
        return peers
×
5168
}
5169

5170
// computeNextBackoff uses a truncated exponential backoff to compute the next
5171
// backoff using the value of the exiting backoff. The returned duration is
5172
// randomized in either direction by 1/20 to prevent tight loops from
5173
// stabilizing.
5174
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
5175
        // Double the current backoff, truncating if it exceeds our maximum.
×
5176
        nextBackoff := 2 * currBackoff
×
5177
        if nextBackoff > maxBackoff {
×
5178
                nextBackoff = maxBackoff
×
5179
        }
×
5180

5181
        // Using 1/10 of our duration as a margin, compute a random offset to
5182
        // avoid the nodes entering connection cycles.
5183
        margin := nextBackoff / 10
×
5184

×
5185
        var wiggle big.Int
×
5186
        wiggle.SetUint64(uint64(margin))
×
5187
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5188
                // Randomizing is not mission critical, so we'll just return the
×
5189
                // current backoff.
×
5190
                return nextBackoff
×
5191
        }
×
5192

5193
        // Otherwise add in our wiggle, but subtract out half of the margin so
5194
        // that the backoff can tweaked by 1/20 in either direction.
5195
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5196
}
5197

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

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

×
5206
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
5207
        if err != nil {
×
5208
                return nil, err
×
5209
        }
×
5210

5211
        node, err := s.graphDB.FetchNode(ctx, vertex)
×
5212
        if err != nil {
×
5213
                return nil, err
×
5214
        }
×
5215

5216
        if len(node.Addresses) == 0 {
×
5217
                return nil, errNoAdvertisedAddr
×
5218
        }
×
5219

5220
        return node.Addresses, nil
×
5221
}
5222

5223
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5224
// channel update for a target channel.
5225
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5226
        *lnwire.ChannelUpdate1, error) {
×
5227

×
5228
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
5229
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
5230
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
5231
                if err != nil {
×
5232
                        return nil, err
×
5233
                }
×
5234

5235
                return netann.ExtractChannelUpdate(
×
5236
                        ourPubKey[:], info, edge1, edge2,
×
5237
                )
×
5238
        }
5239
}
5240

5241
// applyChannelUpdate applies the channel update to the different sub-systems of
5242
// the server. The useAlias boolean denotes whether or not to send an alias in
5243
// place of the real SCID.
5244
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5245
        op *wire.OutPoint, useAlias bool) error {
×
5246

×
5247
        var (
×
5248
                peerAlias    *lnwire.ShortChannelID
×
5249
                defaultAlias lnwire.ShortChannelID
×
5250
        )
×
5251

×
5252
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
5253

×
5254
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
5255
        // in the ChannelUpdate if it hasn't been announced yet.
×
5256
        if useAlias {
×
5257
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
5258
                if foundAlias != defaultAlias {
×
5259
                        peerAlias = &foundAlias
×
5260
                }
×
5261
        }
5262

5263
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
5264
                update, discovery.RemoteAlias(peerAlias),
×
5265
        )
×
5266
        select {
×
5267
        case err := <-errChan:
×
5268
                return err
×
5269
        case <-s.quit:
×
5270
                return ErrServerShuttingDown
×
5271
        }
5272
}
5273

5274
// SendCustomMessage sends a custom message to the peer with the specified
5275
// pubkey.
5276
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5277
        data []byte) error {
×
5278

×
5279
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5280
        if err != nil {
×
5281
                return err
×
5282
        }
×
5283

5284
        // We'll wait until the peer is active.
5285
        select {
×
5286
        case <-peer.ActiveSignal():
×
5287
        case <-peer.QuitSignal():
×
5288
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5289
        case <-s.quit:
×
5290
                return ErrServerShuttingDown
×
5291
        }
5292

5293
        msg, err := lnwire.NewCustom(msgType, data)
×
5294
        if err != nil {
×
5295
                return err
×
5296
        }
×
5297

5298
        // Send the message as low-priority. For now we assume that all
5299
        // application-defined message are low priority.
5300
        return peer.SendMessageLazy(true, msg)
×
5301
}
5302

5303
// newSweepPkScriptGen creates closure that generates a new public key script
5304
// which should be used to sweep any funds into the on-chain wallet.
5305
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5306
// (p2wkh) output.
5307
func newSweepPkScriptGen(
5308
        wallet lnwallet.WalletController,
5309
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
5310

×
5311
        return func() fn.Result[lnwallet.AddrWithKey] {
×
5312
                sweepAddr, err := wallet.NewAddress(
×
5313
                        lnwallet.TaprootPubkey, false,
×
5314
                        lnwallet.DefaultAccountName,
×
5315
                )
×
5316
                if err != nil {
×
5317
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5318
                }
×
5319

5320
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
5321
                if err != nil {
×
5322
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5323
                }
×
5324

5325
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
5326
                        wallet, netParams, addr,
×
5327
                )
×
5328
                if err != nil {
×
5329
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5330
                }
×
5331

5332
                return fn.Ok(lnwallet.AddrWithKey{
×
5333
                        DeliveryAddress: addr,
×
5334
                        InternalKey:     internalKeyDesc,
×
5335
                })
×
5336
        }
5337
}
5338

5339
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5340
// finished.
5341
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
5342
        // Get a list of closed channels.
×
5343
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
5344
        if err != nil {
×
5345
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5346
                return nil
×
5347
        }
×
5348

5349
        // Save the SCIDs in a map.
5350
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5351
        for _, c := range channels {
×
5352
                // If the channel is not pending, its FC has been finalized.
×
5353
                if !c.IsPending {
×
5354
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
5355
                }
×
5356
        }
5357

5358
        // Double check whether the reported closed channel has indeed finished
5359
        // closing.
5360
        //
5361
        // NOTE: There are misalignments regarding when a channel's FC is
5362
        // marked as finalized. We double check the pending channels to make
5363
        // sure the returned SCIDs are indeed terminated.
5364
        //
5365
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5366
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
5367
        if err != nil {
×
5368
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5369
                return nil
×
5370
        }
×
5371

5372
        for _, c := range pendings {
×
5373
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5374
                        continue
×
5375
                }
5376

5377
                // If the channel is still reported as pending, remove it from
5378
                // the map.
5379
                delete(closedSCIDs, c.ShortChannelID)
×
5380

×
5381
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5382
                        c.ShortChannelID)
×
5383
        }
5384

5385
        return closedSCIDs
×
5386
}
5387

5388
// getStartingBeat returns the current beat. This is used during the startup to
5389
// initialize blockbeat consumers.
5390
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
5391
        // beat is the current blockbeat.
×
5392
        var beat *chainio.Beat
×
5393

×
5394
        // If the node is configured with nochainbackend mode (remote signer),
×
5395
        // we will skip fetching the best block.
×
5396
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5397
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5398
                        "mode")
×
5399

×
5400
                return &chainio.Beat{}, nil
×
5401
        }
×
5402

5403
        // We should get a notification with the current best block immediately
5404
        // by passing a nil block.
5405
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
5406
        if err != nil {
×
5407
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5408
        }
×
5409
        defer blockEpochs.Cancel()
×
5410

×
5411
        // We registered for the block epochs with a nil request. The notifier
×
5412
        // should send us the current best block immediately. So we need to
×
5413
        // wait for it here because we need to know the current best height.
×
5414
        select {
×
5415
        case bestBlock := <-blockEpochs.Epochs:
×
5416
                srvrLog.Infof("Received initial block %v at height %d",
×
5417
                        bestBlock.Hash, bestBlock.Height)
×
5418

×
5419
                // Update the current blockbeat.
×
5420
                beat = chainio.NewBeat(*bestBlock)
×
5421

5422
        case <-s.quit:
×
5423
                srvrLog.Debug("LND shutting down")
×
5424
        }
5425

5426
        return beat, nil
×
5427
}
5428

5429
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5430
// point has an active RBF chan closer.
5431
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5432
        chanPoint wire.OutPoint) bool {
×
5433

×
5434
        pubBytes := peerPub.SerializeCompressed()
×
5435

×
5436
        s.mu.RLock()
×
5437
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
5438
        s.mu.RUnlock()
×
5439
        if !ok {
×
5440
                return false
×
5441
        }
×
5442

5443
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5444
}
5445

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

×
5454
        // First, we'll attempt to look up the channel based on it's
×
5455
        // ChannelPoint.
×
5456
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
5457
        if err != nil {
×
5458
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5459
        }
×
5460

5461
        // From the channel, we can now get the pubkey of the peer, then use
5462
        // that to eventually get the chan closer.
5463
        peerPub := channel.IdentityPub.SerializeCompressed()
×
5464

×
5465
        // Now that we have the peer pub, we can look up the peer itself.
×
5466
        s.mu.RLock()
×
5467
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
5468
        s.mu.RUnlock()
×
5469
        if !ok {
×
5470
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5471
                        "not online", chanPoint)
×
5472
        }
×
5473

5474
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
5475
                ctx, chanPoint, feeRate, deliveryScript,
×
5476
        )
×
5477
        if err != nil {
×
5478
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5479
                        "%w", err)
×
5480
        }
×
5481

5482
        return closeUpdates, nil
×
5483
}
5484

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

×
5493
        // If the channel is present in the switch, then the request should flow
×
5494
        // through the switch instead.
×
5495
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
5496
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5497
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5498
                        "invalid request", chanPoint)
×
5499
        }
×
5500

5501
        // At this point, we know that the channel isn't present in the link, so
5502
        // we'll check to see if we have an entry in the active chan closer map.
5503
        updates, err := s.attemptCoopRbfFeeBump(
×
5504
                ctx, chanPoint, feeRate, deliveryScript,
×
5505
        )
×
5506
        if err != nil {
×
5507
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5508
                        "ChannelPoint(%v)", chanPoint)
×
5509
        }
×
5510

5511
        return updates, nil
×
5512
}
5513

5514
// setSelfNode configures and sets the server's self node. It sets the node
5515
// announcement, signs it, and updates the source node in the graph. When
5516
// determining values such as color and alias, the method prioritizes values
5517
// set in the config, then values previously persisted on disk, and finally
5518
// falls back to the defaults.
5519
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5520
        listenAddrs []net.Addr) error {
×
5521

×
5522
        // If we were requested to automatically configure port forwarding,
×
5523
        // we'll use the ports that the server will be listening on.
×
5524
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
×
5525
        for _, ip := range s.cfg.ExternalIPs {
×
5526
                externalIPStrings = append(externalIPStrings, ip.String())
×
5527
        }
×
5528
        if s.natTraversal != nil {
×
5529
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5530
                for _, listenAddr := range listenAddrs {
×
5531
                        // At this point, the listen addresses should have
×
5532
                        // already been normalized, so it's safe to ignore the
×
5533
                        // errors.
×
5534
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5535
                        port, _ := strconv.Atoi(portStr)
×
5536

×
5537
                        listenPorts = append(listenPorts, uint16(port))
×
5538
                }
×
5539

5540
                ips, err := s.configurePortForwarding(listenPorts...)
×
5541
                if err != nil {
×
5542
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5543
                                "forwarding using %s: %v",
×
5544
                                s.natTraversal.Name(), err)
×
5545
                } else {
×
5546
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5547
                                "using %s to advertise external IP",
×
5548
                                s.natTraversal.Name())
×
5549
                        externalIPStrings = append(externalIPStrings, ips...)
×
5550
                }
×
5551
        }
5552

5553
        // Normalize the external IP strings to net.Addr.
5554
        addrs, err := lncfg.NormalizeAddresses(
×
5555
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
5556
                s.cfg.net.ResolveTCPAddr,
×
5557
        )
×
5558
        if err != nil {
×
5559
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5560
        }
×
5561

5562
        // To avoid having duplicate addresses, we'll only add addresses from
5563
        // the source node that are not already in our address list yet. We
5564
        // create this map for quick lookup.
5565
        addressMap := make(map[string]struct{}, len(addrs))
×
5566
        // Populate the map with the existing addresses.
×
5567
        for _, existingAddr := range addrs {
×
5568
                addressMap[existingAddr.String()] = struct{}{}
×
5569
        }
×
5570

5571
        // Parse the color from config. We will update this later if the config
5572
        // color is not changed from default (#3399FF) and we have a value in
5573
        // the source node.
5574
        color, err := lncfg.ParseHexColor(s.cfg.Color)
×
5575
        if err != nil {
×
5576
                return fmt.Errorf("unable to parse color: %w", err)
×
5577
        }
×
5578

5579
        var (
×
5580
                alias          = s.cfg.Alias
×
5581
                nodeLastUpdate = time.Now()
×
5582
        )
×
5583

×
5584
        srcNode, err := s.graphDB.SourceNode(ctx)
×
5585
        switch {
×
5586
        case err == nil:
×
5587
                // If we have a source node persisted in the DB already, then we
×
5588
                // just need to make sure that the new LastUpdate time is at
×
5589
                // least one second after the last update time.
×
5590
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
5591
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
5592
                }
×
5593

5594
                // If the color is not changed from default, it means that we
5595
                // didn't specify a different color in the config. We'll use the
5596
                // source node's color.
5597
                if s.cfg.Color == defaultColor {
×
5598
                        color = srcNode.Color
×
5599
                }
×
5600

5601
                // If an alias is not specified in the config, we'll use the
5602
                // source node's alias.
5603
                if alias == "" {
×
5604
                        alias = srcNode.Alias
×
5605
                }
×
5606

5607
                // Append unique addresses from the source node to the address
5608
                // list.
5609
                for _, addr := range srcNode.Addresses {
×
5610
                        if _, found := addressMap[addr.String()]; !found {
×
5611
                                addrs = append(addrs, addr)
×
5612
                                addressMap[addr.String()] = struct{}{}
×
5613
                        }
×
5614
                }
5615

5616
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
5617
                // If an alias is not specified in the config, we'll use the
×
5618
                // default, which is the first 10 bytes of the serialized
×
5619
                // pubkey.
×
5620
                if alias == "" {
×
5621
                        alias = hex.EncodeToString(nodePub[:10])
×
5622
                }
×
5623

5624
        // If the above cases are not matched, then we have an unhandled non
5625
        // nil error.
5626
        default:
×
5627
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5628
        }
5629

5630
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
5631
        if err != nil {
×
5632
                return err
×
5633
        }
×
5634

5635
        // TODO(abdulkbk): potentially find a way to use the source node's
5636
        // features in the self node.
5637
        selfNode := &models.Node{
×
5638
                HaveNodeAnnouncement: true,
×
5639
                LastUpdate:           nodeLastUpdate,
×
5640
                Addresses:            addrs,
×
5641
                Alias:                nodeAlias.String(),
×
5642
                Color:                color,
×
5643
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
5644
        }
×
5645

×
5646
        copy(selfNode.PubKeyBytes[:], nodePub[:])
×
5647

×
5648
        // Based on the disk representation of the node announcement generated
×
5649
        // above, we'll generate a node announcement that can go out on the
×
5650
        // network so we can properly sign it.
×
5651
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
5652
        if err != nil {
×
5653
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5654
        }
×
5655

5656
        // With the announcement generated, we'll sign it to properly
5657
        // authenticate the message on the network.
5658
        authSig, err := netann.SignAnnouncement(
×
5659
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
×
5660
        )
×
5661
        if err != nil {
×
5662
                return fmt.Errorf("unable to generate signature for self node "+
×
5663
                        "announcement: %v", err)
×
5664
        }
×
5665

5666
        selfNode.AuthSigBytes = authSig.Serialize()
×
5667
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
5668
                selfNode.AuthSigBytes,
×
5669
        )
×
5670
        if err != nil {
×
5671
                return err
×
5672
        }
×
5673

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

5680
        s.currentNodeAnn = nodeAnn
×
5681

×
5682
        return nil
×
5683
}
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