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

lightningnetwork / lnd / 19924300449

04 Dec 2025 09:35AM UTC coverage: 53.479% (-1.9%) from 55.404%
19924300449

Pull #10419

github

web-flow
Merge f811805c6 into 20473482d
Pull Request #10419: [docs] Document use-native-sql=true for SQL migration step 2

110496 of 206616 relevant lines covered (53.48%)

21221.61 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
        "image/color"
11
        "math/big"
12
        prand "math/rand"
13
        "net"
14
        "strconv"
15
        "strings"
16
        "sync"
17
        "sync/atomic"
18
        "time"
19

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

207
        case peerStatusTemporary:
×
208
                return "temporary"
×
209

210
        case peerStatusProtected:
×
211
                return "protected"
×
212

213
        default:
×
214
                return "unknown"
×
215
        }
216
}
217

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

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

233
        start sync.Once
234
        stop  sync.Once
235

236
        cfg *Config
237

238
        implCfg *ImplementationCfg
239

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

244
        // identityKeyLoc is the key locator for the above wrapped identity key.
245
        identityKeyLoc keychain.KeyLocator
246

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

251
        chanStatusMgr *netann.ChanStatusManager
252

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

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

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

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

273
        mu sync.RWMutex
274

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

284
        inboundPeers  map[string]*peer.Brontide
285
        outboundPeers map[string]*peer.Brontide
286

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

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

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

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

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

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

325
        cc *chainreg.ChainControl
326

327
        fundingMgr *funding.Manager
328

329
        graphDB *graphdb.ChannelGraph
330

331
        chanStateDB *channeldb.ChannelStateDB
332

333
        addrSource channeldb.AddrSource
334

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

339
        invoicesDB invoices.InvoiceDB
340

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

345
        aliasMgr *aliasmgr.Manager
346

347
        htlcSwitch *htlcswitch.Switch
348

349
        interceptableSwitch *htlcswitch.InterceptableSwitch
350

351
        invoices *invoices.InvoiceRegistry
352

353
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
354

355
        channelNotifier *channelnotifier.ChannelNotifier
356

357
        peerNotifier *peernotifier.PeerNotifier
358

359
        htlcNotifier *htlcswitch.HtlcNotifier
360

361
        witnessBeacon contractcourt.WitnessBeacon
362

363
        breachArbitrator *contractcourt.BreachArbitrator
364

365
        missionController *routing.MissionController
366
        defaultMC         *routing.MissionControl
367

368
        graphBuilder *graph.Builder
369

370
        chanRouter *routing.ChannelRouter
371

372
        controlTower routing.ControlTower
373

374
        authGossiper *discovery.AuthenticatedGossiper
375

376
        localChanMgr *localchans.Manager
377

378
        utxoNursery *contractcourt.UtxoNursery
379

380
        sweeper *sweep.UtxoSweeper
381

382
        chainArb *contractcourt.ChainArbitrator
383

384
        sphinx *hop.OnionProcessor
385

386
        towerClientMgr *wtclient.Manager
387

388
        connMgr *connmgr.ConnManager
389

390
        sigPool *lnwallet.SigPool
391

392
        writePool *pool.Write
393

394
        readPool *pool.Read
395

396
        tlsManager *TLSManager
397

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

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

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

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

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

420
        hostAnn *netann.HostAnnouncer
421

422
        // livenessMonitor monitors that lnd has access to critical resources.
423
        livenessMonitor *healthcheck.Monitor
424

425
        customMessageServer *subscribe.Server
426

427
        onionMessageServer *subscribe.Server
428

429
        // txPublisher is a publisher with fee-bumping capability.
430
        txPublisher *sweep.TxPublisher
431

432
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
433
        // of new blocks.
434
        blockbeatDispatcher *chainio.BlockbeatDispatcher
435

436
        // peerAccessMan implements peer access controls.
437
        peerAccessMan *accessMan
438

439
        quit chan struct{}
440

441
        wg sync.WaitGroup
442
}
443

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

452
        s.wg.Add(1)
×
453
        go func() {
×
454
                defer func() {
×
455
                        graphSub.Cancel()
×
456
                        s.wg.Done()
×
457
                }()
×
458

459
                for {
×
460
                        select {
×
461
                        case <-s.quit:
×
462
                                return
×
463

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

471
                                for _, update := range topChange.NodeUpdates {
×
472
                                        pubKeyStr := string(
×
473
                                                update.IdentityKey.
×
474
                                                        SerializeCompressed(),
×
475
                                        )
×
476

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

486
                                        addrs := make([]*lnwire.NetAddress, 0,
×
487
                                                len(update.Addresses))
×
488

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

499
                                        s.mu.Lock()
×
500

×
501
                                        // Update the stored addresses for this
×
502
                                        // to peer to reflect the new set.
×
503
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
504

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

515
                                        s.mu.Unlock()
×
516

×
517
                                        s.connectToPersistentPeer(pubKeyStr)
×
518
                                }
519
                        }
520
                }
521
        }()
522

523
        return nil
×
524
}
525

526
// CustomMessage is a custom message that is received from a peer.
527
type CustomMessage struct {
528
        // Peer is the peer pubkey
529
        Peer [33]byte
530

531
        // Msg is the custom wire message.
532
        Msg *lnwire.Custom
533
}
534

535
// parseAddr parses an address from its string format to a net.Addr.
536
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
537
        var (
×
538
                host string
×
539
                port int
×
540
        )
×
541

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

559
        if tor.IsOnionHost(host) {
×
560
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
561
        }
×
562

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

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

×
576
        return func(a net.Addr) (net.Conn, error) {
×
577
                lnAddr := a.(*lnwire.NetAddress)
×
578
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
579
        }
×
580
}
581

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

×
595
        var (
×
596
                err         error
×
597
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
598

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

×
606
        netParams := cfg.ActiveNetParams.Params
×
607

×
608
        // Initialize the sphinx router.
×
609
        replayLog := htlcswitch.NewDecayedLog(
×
610
                dbs.DecayedLogDB, cc.ChainNotifier,
×
611
        )
×
612
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
613

×
614
        writeBufferPool := pool.NewWriteBuffer(
×
615
                pool.DefaultWriteBufferGCInterval,
×
616
                pool.DefaultWriteBufferExpiryInterval,
×
617
        )
×
618

×
619
        writePool := pool.NewWrite(
×
620
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
621
        )
×
622

×
623
        readBufferPool := pool.NewReadBuffer(
×
624
                pool.DefaultReadBufferGCInterval,
×
625
                pool.DefaultReadBufferExpiryInterval,
×
626
        )
×
627

×
628
        readPool := pool.NewRead(
×
629
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
630
        )
×
631

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

×
637
                return nil, fmt.Errorf("taproot overlay flag set, but " +
×
638
                        "overlay channels are not supported " +
×
639
                        "in a standalone lnd build")
×
640
        }
×
641

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

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

×
678
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
679

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

×
695
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
696
                        cc.ChainNotifier,
×
697
                ),
×
698
                channelNotifier: channelnotifier.New(
×
699
                        dbs.ChanStateDB.ChannelStateDB(),
×
700
                ),
×
701

×
702
                identityECDH:   nodeKeyECDH,
×
703
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
704
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
705

×
706
                listenAddrs: listenAddrs,
×
707

×
708
                // TODO(roasbeef): derive proper onion key based on rotation
×
709
                // schedule
×
710
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
711

×
712
                torController: torController,
×
713

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

×
724
                peersByPub:                make(map[string]*peer.Brontide),
×
725
                inboundPeers:              make(map[string]*peer.Brontide),
×
726
                outboundPeers:             make(map[string]*peer.Brontide),
×
727
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
728
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
729

×
730
                invoiceHtlcModifier: invoiceHtlcModifier,
×
731

×
732
                customMessageServer: subscribe.NewServer(),
×
733

×
734
                onionMessageServer: subscribe.NewServer(),
×
735

×
736
                tlsManager: tlsManager,
×
737

×
738
                featureMgr: featureMgr,
×
739
                quit:       make(chan struct{}),
×
740
        }
×
741

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

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

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

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

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

766
                s.htlcSwitch.UpdateLinkAliases(link)
×
767

×
768
                return nil
×
769
        }
770

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

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

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

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

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

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

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

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

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

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

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

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

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

889
        nodePubKey := route.NewVertex(nodeKeyDesc.PubKey)
×
890
        // Set the self node which represents our node in the graph.
×
891
        err = s.setSelfNode(ctx, nodePubKey, listenAddrs)
×
892
        if err != nil {
×
893
                return nil, err
×
894
        }
×
895

896
        // The router will get access to the payment ID sequencer, such that it
897
        // can generate unique payment IDs.
898
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
899
        if err != nil {
×
900
                return nil, err
×
901
        }
×
902

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

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

×
924
                        estimator, err = routing.NewAprioriEstimator(
×
925
                                aprioriConfig,
×
926
                        )
×
927
                        if err != nil {
×
928
                                return nil, err
×
929
                        }
×
930

931
                case routing.BimodalEstimatorName:
×
932
                        bCfg := routingConfig.BimodalConfig
×
933
                        bimodalConfig := routing.BimodalConfig{
×
934
                                BimodalNodeWeight: bCfg.NodeWeight,
×
935
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
936
                                        bCfg.Scale,
×
937
                                ),
×
938
                                BimodalDecayTime: bCfg.DecayTime,
×
939
                        }
×
940

×
941
                        estimator, err = routing.NewBimodalEstimator(
×
942
                                bimodalConfig,
×
943
                        )
×
944
                        if err != nil {
×
945
                                return nil, err
×
946
                        }
×
947

948
                default:
×
949
                        return nil, fmt.Errorf("unknown estimator type %v",
×
950
                                routingConfig.ProbabilityEstimatorType)
×
951
                }
952
        }
953

954
        mcCfg := &routing.MissionControlConfig{
×
955
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
956
                Estimator:               estimator,
×
957
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
958
                McFlushInterval:         routingConfig.McFlushInterval,
×
959
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
960
        }
×
961

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

977
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
978
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
979
                int64(routingConfig.AttemptCost),
×
980
                float64(routingConfig.AttemptCostPPM)/10000,
×
981
                routingConfig.MinRouteProbability)
×
982

×
983
        pathFindingConfig := routing.PathFindingConfig{
×
984
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
985
                        routingConfig.AttemptCost,
×
986
                ),
×
987
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
988
                MinProbability: routingConfig.MinRouteProbability,
×
989
        }
×
990

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

×
1003
        s.controlTower = routing.NewControlTower(dbs.PaymentsDB)
×
1004

×
1005
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
1006
                cfg.Routing.StrictZombiePruning
×
1007

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

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

1045
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
1046
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
1047
        if err != nil {
×
1048
                return nil, err
×
1049
        }
×
1050
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
1051
        if err != nil {
×
1052
                return nil, err
×
1053
        }
×
1054

1055
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
1056

×
1057
        s.authGossiper = discovery.New(discovery.Config{
×
1058
                Graph:                 s.graphBuilder,
×
1059
                ChainIO:               s.cc.ChainIO,
×
1060
                Notifier:              s.cc.ChainNotifier,
×
1061
                ChainParams:           s.cfg.ActiveNetParams.Params,
×
1062
                Broadcast:             s.BroadcastMessage,
×
1063
                ChanSeries:            chanSeries,
×
1064
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
1065
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
1066
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
1067
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement1,
×
1068
                        error) {
×
1069

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

1104
        accessCfg := &accessManConfig{
×
1105
                initAccessPerms: func() (map[string]channeldb.ChanCount,
×
1106
                        error) {
×
1107

×
1108
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
×
1109
                        return s.chanStateDB.FetchPermAndTempPeers(
×
1110
                                genesisHash[:],
×
1111
                        )
×
1112
                },
×
1113
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1114
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1115
        }
1116

1117
        peerAccessMan, err := newAccessMan(accessCfg)
×
1118
        if err != nil {
×
1119
                return nil, err
×
1120
        }
×
1121

1122
        s.peerAccessMan = peerAccessMan
×
1123

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

×
1134
                        return s.graphDB.ForEachNodeChannel(ctx, selfVertex,
×
1135
                                func(c *models.ChannelEdgeInfo,
×
1136
                                        e *models.ChannelEdgePolicy,
×
1137
                                        _ *models.ChannelEdgePolicy) error {
×
1138

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

×
1151
                        return s.graphBuilder.AddEdge(ctx, edge)
×
1152
                },
×
1153
        }
1154

1155
        utxnStore, err := contractcourt.NewNurseryStore(
×
1156
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
1157
        )
×
1158
        if err != nil {
×
1159
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1160
                return nil, err
×
1161
        }
×
1162

1163
        sweeperStore, err := sweep.NewSweeperStore(
×
1164
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
1165
        )
×
1166
        if err != nil {
×
1167
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1168
                return nil, err
×
1169
        }
×
1170

1171
        aggregator := sweep.NewBudgetAggregator(
×
1172
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
1173
                s.implCfg.AuxSweeper,
×
1174
        )
×
1175

×
1176
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
1177
                Signer:     cc.Wallet.Cfg.Signer,
×
1178
                Wallet:     cc.Wallet,
×
1179
                Estimator:  cc.FeeEstimator,
×
1180
                Notifier:   cc.ChainNotifier,
×
1181
                AuxSweeper: s.implCfg.AuxSweeper,
×
1182
        })
×
1183

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

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

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

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

1227
        // We will use the following channel to reliably hand off contract
1228
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1229
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
×
1230

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

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

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

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

×
1301
                        // processACK will handle the BreachArbitrator ACKing
×
1302
                        // the event.
×
1303
                        finalErr := make(chan error, 1)
×
1304
                        processACK := func(brarErr error) {
×
1305
                                if brarErr != nil {
×
1306
                                        finalErr <- brarErr
×
1307
                                        return
×
1308
                                }
×
1309

1310
                                // If the BreachArbitrator successfully handled
1311
                                // the event, we can signal that the handoff
1312
                                // was successful.
1313
                                finalErr <- nil
×
1314
                        }
1315

1316
                        event := &contractcourt.ContractBreachEvent{
×
1317
                                ChanPoint:         chanPoint,
×
1318
                                ProcessACK:        processACK,
×
1319
                                BreachRetribution: breachRet,
×
1320
                        }
×
1321

×
1322
                        // Send the contract breach event to the
×
1323
                        // BreachArbitrator.
×
1324
                        select {
×
1325
                        case contractBreaches <- event:
×
1326
                        case <-s.quit:
×
1327
                                return ErrServerShuttingDown
×
1328
                        }
1329

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

1355
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1356
                QueryIncomingCircuit: func(
1357
                        circuit models.CircuitKey) *models.CircuitKey {
×
1358

×
1359
                        // Get the circuit map.
×
1360
                        circuits := s.htlcSwitch.CircuitLookup()
×
1361

×
1362
                        // Lookup the outgoing circuit.
×
1363
                        pc := circuits.LookupOpenCircuit(circuit)
×
1364
                        if pc == nil {
×
1365
                                return nil
×
1366
                        }
×
1367

1368
                        return &pc.Incoming
×
1369
                },
1370
                AuxLeafStore: implCfg.AuxLeafStore,
1371
                AuxSigner:    implCfg.AuxSigner,
1372
                AuxResolver:  implCfg.AuxContractResolver,
1373
        }, dbs.ChanStateDB)
1374

1375
        // Select the configuration and funding parameters for Bitcoin.
1376
        chainCfg := cfg.Bitcoin
×
1377
        minRemoteDelay := funding.MinBtcRemoteDelay
×
1378
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
1379

×
1380
        var chanIDSeed [32]byte
×
1381
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1382
                return nil, err
×
1383
        }
×
1384

1385
        // Wrap the DeleteChannelEdges method so that the funding manager can
1386
        // use it without depending on several layers of indirection.
1387
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
1388
                *models.ChannelEdgePolicy, error) {
×
1389

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

1403
                // Grab our key to find our policy.
1404
                var ourKey [33]byte
×
1405
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1406

×
1407
                var ourPolicy *models.ChannelEdgePolicy
×
1408
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1409
                        ourPolicy = e1
×
1410
                } else {
×
1411
                        ourPolicy = e2
×
1412
                }
×
1413

1414
                if ourPolicy == nil {
×
1415
                        // Something is wrong, so return an error.
×
1416
                        return nil, fmt.Errorf("we don't have an edge")
×
1417
                }
×
1418

1419
                err = s.graphDB.DeleteChannelEdges(
×
1420
                        false, false, scid.ToUint64(),
×
1421
                )
×
1422
                return ourPolicy, err
×
1423
        }
1424

1425
        // For the reservationTimeout and the zombieSweeperInterval different
1426
        // values are set in case we are in a dev environment so enhance test
1427
        // capacilities.
1428
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
1429
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
1430

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

×
1441
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
1442
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
1443

×
1444
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1445
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
1446
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
1447
        }
×
1448

1449
        // Attempt to parse the provided upfront-shutdown address (if any).
1450
        script, err := chancloser.ParseUpfrontShutdownAddress(
×
1451
                cfg.UpfrontShutdownAddr, cfg.ActiveNetParams.Params,
×
1452
        )
×
1453
        if err != nil {
×
1454
                return nil, fmt.Errorf("error parsing upfront shutdown: %w",
×
1455
                        err)
×
1456
        }
×
1457

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

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

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

1504
                        minConf := uint64(3)
×
1505
                        maxConf := uint64(6)
×
1506

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

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

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

1543
                        // If this is a wumbo channel, then we'll require the
1544
                        // max value.
1545
                        if chanAmt > MaxFundingAmount {
×
1546
                                return maxRemoteDelay
×
1547
                        }
×
1548

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

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

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

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

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

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

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

1664
        // Assemble a peer notifier which will provide clients with subscriptions
1665
        // to peer online and offline events.
1666
        s.peerNotifier = peernotifier.New()
×
1667

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

1683
        if cfg.WtClient.Active {
×
1684
                policy := wtpolicy.DefaultPolicy()
×
1685
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
1686

×
1687
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
1688
                // protocol operations on sat/kw.
×
1689
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
1690
                        1000 * cfg.WtClient.SweepFeeRate,
×
1691
                )
×
1692

×
1693
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1694

×
1695
                if err := policy.Validate(); err != nil {
×
1696
                        return nil, err
×
1697
                }
×
1698

1699
                // authDial is the wrapper around the btrontide.Dial for the
1700
                // watchtower.
1701
                authDial := func(localKey keychain.SingleKeyECDH,
×
1702
                        netAddr *lnwire.NetAddress,
×
1703
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
1704

×
1705
                        return brontide.Dial(
×
1706
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1707
                        )
×
1708
                }
×
1709

1710
                // buildBreachRetribution is a call-back that can be used to
1711
                // query the BreachRetribution info and channel type given a
1712
                // channel ID and commitment height.
1713
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
1714
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
1715
                        channeldb.ChannelType, error) {
×
1716

×
1717
                        channel, err := s.chanStateDB.FetchChannelByID(
×
1718
                                nil, chanID,
×
1719
                        )
×
1720
                        if err != nil {
×
1721
                                return nil, 0, err
×
1722
                        }
×
1723

1724
                        br, err := lnwallet.NewBreachRetribution(
×
1725
                                channel, commitHeight, 0, nil,
×
1726
                                implCfg.AuxLeafStore,
×
1727
                                implCfg.AuxContractResolver,
×
1728
                        )
×
1729
                        if err != nil {
×
1730
                                return nil, 0, err
×
1731
                        }
×
1732

1733
                        return br, channel.ChanType, nil
×
1734
                }
1735

1736
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
1737

×
1738
                // Copy the policy for legacy channels and set the blob flag
×
1739
                // signalling support for anchor channels.
×
1740
                anchorPolicy := policy
×
1741
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1742

×
1743
                // Copy the policy for legacy channels and set the blob flag
×
1744
                // signalling support for taproot channels.
×
1745
                taprootPolicy := policy
×
1746
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
1747
                        blob.FlagTaprootChannel,
×
1748
                )
×
1749

×
1750
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1751
                        FetchClosedChannel:     fetchClosedChannel,
×
1752
                        BuildBreachRetribution: buildBreachRetribution,
×
1753
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
1754
                        ChainNotifier:          s.cc.ChainNotifier,
×
1755
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
1756
                                error) {
×
1757

×
1758
                                return s.channelNotifier.
×
1759
                                        SubscribeChannelEvents()
×
1760
                        },
×
1761
                        Signer: cc.Wallet.Cfg.Signer,
1762
                        NewAddress: func() ([]byte, error) {
×
1763
                                addr, err := newSweepPkScriptGen(
×
1764
                                        cc.Wallet, netParams,
×
1765
                                )().Unpack()
×
1766
                                if err != nil {
×
1767
                                        return nil, err
×
1768
                                }
×
1769

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

1786
        if len(cfg.ExternalHosts) != 0 {
×
1787
                advertisedIPs := make(map[string]struct{})
×
1788
                for _, addr := range s.currentNodeAnn.Addresses {
×
1789
                        advertisedIPs[addr.String()] = struct{}{}
×
1790
                }
×
1791

1792
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1793
                        Hosts:         cfg.ExternalHosts,
×
1794
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1795
                        LookupHost: func(host string) (net.Addr, error) {
×
1796
                                return lncfg.ParseAddressString(
×
1797
                                        host, strconv.Itoa(defaultPeerPort),
×
1798
                                        cfg.net.ResolveTCPAddr,
×
1799
                                )
×
1800
                        },
×
1801
                        AdvertisedIPs: advertisedIPs,
1802
                        AnnounceNewIPs: netann.IPAnnouncer(
1803
                                func(modifier ...netann.NodeAnnModifier) (
1804
                                        lnwire.NodeAnnouncement1, error) {
×
1805

×
1806
                                        return s.genNodeAnnouncement(
×
1807
                                                nil, modifier...,
×
1808
                                        )
×
1809
                                }),
×
1810
                })
1811
        }
1812

1813
        // Create liveness monitor.
1814
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1815

×
1816
        listeners := make([]net.Listener, len(listenAddrs))
×
1817
        for i, listenAddr := range listenAddrs {
×
1818
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
1819
                // doesn't need to call the general lndResolveTCP function
×
1820
                // since we are resolving a local address.
×
1821

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

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

×
1853
        // Finally, register the subsystems in blockbeat.
×
1854
        s.registerBlockConsumers()
×
1855

×
1856
        return s, nil
×
1857
}
1858

1859
// UpdateRoutingConfig is a callback function to update the routing config
1860
// values in the main cfg.
1861
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
1862
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
1863

×
1864
        switch c := cfg.Estimator.Config().(type) {
×
1865
        case routing.AprioriConfig:
×
1866
                routerCfg.ProbabilityEstimatorType =
×
1867
                        routing.AprioriEstimatorName
×
1868

×
1869
                targetCfg := routerCfg.AprioriConfig
×
1870
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
1871
                targetCfg.Weight = c.AprioriWeight
×
1872
                targetCfg.CapacityFraction = c.CapacityFraction
×
1873
                targetCfg.HopProbability = c.AprioriHopProbability
×
1874

1875
        case routing.BimodalConfig:
×
1876
                routerCfg.ProbabilityEstimatorType =
×
1877
                        routing.BimodalEstimatorName
×
1878

×
1879
                targetCfg := routerCfg.BimodalConfig
×
1880
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
1881
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
1882
                targetCfg.DecayTime = c.BimodalDecayTime
×
1883
        }
1884

1885
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1886
}
1887

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

1907
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1908
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1909
// may differ from what is on disk.
1910
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1911
        error) {
×
1912

×
1913
        data, err := u.DataToSign()
×
1914
        if err != nil {
×
1915
                return nil, err
×
1916
        }
×
1917

1918
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1919
}
1920

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

×
1934
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
1935
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1936
                srvrLog.Info("Disabling chain backend checks for " +
×
1937
                        "nochainbackend mode")
×
1938

×
1939
                chainBackendAttempts = 0
×
1940
        }
×
1941

1942
        chainHealthCheck := healthcheck.NewObservation(
×
1943
                "chain backend",
×
1944
                cc.HealthCheck,
×
1945
                cfg.HealthChecks.ChainCheck.Interval,
×
1946
                cfg.HealthChecks.ChainCheck.Timeout,
×
1947
                cfg.HealthChecks.ChainCheck.Backoff,
×
1948
                chainBackendAttempts,
×
1949
        )
×
1950

×
1951
        diskCheck := healthcheck.NewObservation(
×
1952
                "disk space",
×
1953
                func() error {
×
1954
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1955
                                cfg.LndDir,
×
1956
                        )
×
1957
                        if err != nil {
×
1958
                                return err
×
1959
                        }
×
1960

1961
                        // If we have more free space than we require,
1962
                        // we return a nil error.
1963
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1964
                                return nil
×
1965
                        }
×
1966

1967
                        return fmt.Errorf("require: %v free space, got: %v",
×
1968
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1969
                                free)
×
1970
                },
1971
                cfg.HealthChecks.DiskCheck.Interval,
1972
                cfg.HealthChecks.DiskCheck.Timeout,
1973
                cfg.HealthChecks.DiskCheck.Backoff,
1974
                cfg.HealthChecks.DiskCheck.Attempts,
1975
        )
1976

1977
        tlsHealthCheck := healthcheck.NewObservation(
×
1978
                "tls",
×
1979
                func() error {
×
1980
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1981
                                s.cc.KeyRing,
×
1982
                        )
×
1983
                        if err != nil {
×
1984
                                return err
×
1985
                        }
×
1986
                        if expired {
×
1987
                                return fmt.Errorf("TLS certificate is "+
×
1988
                                        "expired as of %v", expTime)
×
1989
                        }
×
1990

1991
                        // If the certificate is not outdated, no error needs
1992
                        // to be returned
1993
                        return nil
×
1994
                },
1995
                cfg.HealthChecks.TLSCheck.Interval,
1996
                cfg.HealthChecks.TLSCheck.Timeout,
1997
                cfg.HealthChecks.TLSCheck.Backoff,
1998
                cfg.HealthChecks.TLSCheck.Attempts,
1999
        )
2000

2001
        checks := []*healthcheck.Observation{
×
2002
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
2003
        }
×
2004

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

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

×
2035
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
2036
                        "remote signer connection",
×
2037
                        rpcwallet.HealthCheck(
×
2038
                                s.cfg.RemoteSigner,
×
2039

×
2040
                                // For the health check we might to be even
×
2041
                                // stricter than the initial/normal connect, so
×
2042
                                // we use the health check timeout here.
×
2043
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
2044
                        ),
×
2045
                        cfg.HealthChecks.RemoteSigner.Interval,
×
2046
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
2047
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
2048
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
2049
                )
×
2050
                checks = append(checks, remoteSignerConnectionCheck)
×
2051
        }
×
2052

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

×
2071
                                leader, err := leaderElector.IsLeader(
×
2072
                                        timeoutCtx,
×
2073
                                )
×
2074
                                if err != nil {
×
2075
                                        return fmt.Errorf("unable to check if "+
×
2076
                                                "still leader: %v", err)
×
2077
                                }
×
2078

2079
                                if !leader {
×
2080
                                        srvrLog.Debug("Not the current leader")
×
2081
                                        return fmt.Errorf("not the current " +
×
2082
                                                "leader")
×
2083
                                }
×
2084

2085
                                return nil
×
2086
                        },
2087
                        cfg.HealthChecks.LeaderCheck.Interval,
2088
                        cfg.HealthChecks.LeaderCheck.Timeout,
2089
                        cfg.HealthChecks.LeaderCheck.Backoff,
2090
                        cfg.HealthChecks.LeaderCheck.Attempts,
2091
                )
2092

2093
                checks = append(checks, leaderCheck)
×
2094
        }
2095

2096
        // If we have not disabled all of our health checks, we create a
2097
        // liveness monitor with our configured checks.
2098
        s.livenessMonitor = healthcheck.NewMonitor(
×
2099
                &healthcheck.Config{
×
2100
                        Checks:   checks,
×
2101
                        Shutdown: srvrLog.Criticalf,
×
2102
                },
×
2103
        )
×
2104
}
2105

2106
// Started returns true if the server has been started, and false otherwise.
2107
// NOTE: This function is safe for concurrent access.
2108
func (s *server) Started() bool {
×
2109
        return atomic.LoadInt32(&s.active) != 0
×
2110
}
×
2111

2112
// cleaner is used to aggregate "cleanup" functions during an operation that
2113
// starts several subsystems. In case one of the subsystem fails to start
2114
// and a proper resource cleanup is required, the "run" method achieves this
2115
// by running all these added "cleanup" functions.
2116
type cleaner []func() error
2117

2118
// add is used to add a cleanup function to be called when
2119
// the run function is executed.
2120
func (c cleaner) add(cleanup func() error) cleaner {
×
2121
        return append(c, cleanup)
×
2122
}
×
2123

2124
// run is used to run all the previousely added cleanup functions.
2125
func (c cleaner) run() {
×
2126
        for i := len(c) - 1; i >= 0; i-- {
×
2127
                if err := c[i](); err != nil {
×
2128
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2129
                }
×
2130
        }
2131
}
2132

2133
// Start starts the main daemon server, all requested listeners, and any helper
2134
// goroutines.
2135
// NOTE: This function is safe for concurrent access.
2136
//
2137
//nolint:funlen
2138
func (s *server) Start(ctx context.Context) error {
×
2139
        var startErr error
×
2140

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

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

2153
                cleanup = cleanup.add(s.onionMessageServer.Stop)
×
2154
                if err := s.onionMessageServer.Start(); err != nil {
×
2155
                        startErr = err
×
2156
                        return
×
2157
                }
×
2158

2159
                if s.hostAnn != nil {
×
2160
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2161
                        if err := s.hostAnn.Start(); err != nil {
×
2162
                                startErr = err
×
2163
                                return
×
2164
                        }
×
2165
                }
2166

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

2175
                // Start the notification server. This is used so channel
2176
                // management goroutines can be notified when a funding
2177
                // transaction reaches a sufficient number of confirmations, or
2178
                // when the input for the funding transaction is spent in an
2179
                // attempt at an uncooperative close by the counterparty.
2180
                cleanup = cleanup.add(s.sigPool.Stop)
×
2181
                if err := s.sigPool.Start(); err != nil {
×
2182
                        startErr = err
×
2183
                        return
×
2184
                }
×
2185

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

2192
                cleanup = cleanup.add(s.readPool.Stop)
×
2193
                if err := s.readPool.Start(); err != nil {
×
2194
                        startErr = err
×
2195
                        return
×
2196
                }
×
2197

2198
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2199
                if err := s.cc.ChainNotifier.Start(); err != nil {
×
2200
                        startErr = err
×
2201
                        return
×
2202
                }
×
2203

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

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

2216
                cleanup = cleanup.add(func() error {
×
2217
                        return s.peerNotifier.Stop()
×
2218
                })
×
2219
                if err := s.peerNotifier.Start(); err != nil {
×
2220
                        startErr = err
×
2221
                        return
×
2222
                }
×
2223

2224
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
2225
                if err := s.htlcNotifier.Start(); err != nil {
×
2226
                        startErr = err
×
2227
                        return
×
2228
                }
×
2229

2230
                if s.towerClientMgr != nil {
×
2231
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
2232
                        if err := s.towerClientMgr.Start(); err != nil {
×
2233
                                startErr = err
×
2234
                                return
×
2235
                        }
×
2236
                }
2237

2238
                beat, err := s.getStartingBeat()
×
2239
                if err != nil {
×
2240
                        startErr = err
×
2241
                        return
×
2242
                }
×
2243

2244
                cleanup = cleanup.add(s.txPublisher.Stop)
×
2245
                if err := s.txPublisher.Start(beat); err != nil {
×
2246
                        startErr = err
×
2247
                        return
×
2248
                }
×
2249

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2350
                cleanup.add(func() error {
×
2351
                        s.missionController.StopStoreTickers()
×
2352
                        return nil
×
2353
                })
×
2354
                s.missionController.RunStoreTickers()
×
2355

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

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

2397
                if s.torController != nil {
×
2398
                        cleanup = cleanup.add(s.torController.Stop)
×
2399
                        if err := s.createNewHiddenService(ctx); err != nil {
×
2400
                                startErr = err
×
2401
                                return
×
2402
                        }
×
2403
                }
2404

2405
                if s.natTraversal != nil {
×
2406
                        s.wg.Add(1)
×
2407
                        go s.watchExternalIP()
×
2408
                }
×
2409

2410
                // Start connmgr last to prevent connections before init.
2411
                cleanup = cleanup.add(func() error {
×
2412
                        s.connMgr.Stop()
×
2413
                        return nil
×
2414
                })
×
2415

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

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

2445
                        peerAddr := &lnwire.NetAddress{
×
2446
                                IdentityKey: parsedPubkey,
×
2447
                                Address:     addr,
×
2448
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
2449
                        }
×
2450

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

2463
                // Subscribe to NodeAnnouncements that advertise new addresses
2464
                // our persistent peers.
2465
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2466
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2467
                                "addr: %v", err)
×
2468

×
2469
                        startErr = err
×
2470
                        return
×
2471
                }
×
2472

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

×
2482
                        startErr = err
×
2483
                        return
×
2484
                }
×
2485

2486
                if err := s.establishPersistentConnections(ctx); err != nil {
×
2487
                        srvrLog.Errorf("Failed to establish persistent "+
×
2488
                                "connections: %v", err)
×
2489
                }
×
2490

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

2500
                        result := make([][2]string, len(tuples))
×
2501
                        for idx, tuple := range tuples {
×
2502
                                tuple = strings.TrimSpace(tuple)
×
2503
                                if len(tuple) == 0 {
×
2504
                                        return
×
2505
                                }
×
2506

2507
                                servers := strings.Split(tuple, ",")
×
2508
                                if len(servers) > 2 || len(servers) == 0 {
×
2509
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2510
                                                "seed tuple: %v", servers)
×
2511
                                        return
×
2512
                                }
×
2513

2514
                                copy(result[idx][:], servers)
×
2515
                        }
2516

2517
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2518
                }
2519

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

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

2558
                        s.wg.Add(1)
×
2559
                        go s.peerBootstrapper(
×
2560
                                ctx, defaultMinPeers, bootstrappers,
×
2561
                        )
×
2562
                } else {
×
2563
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2564
                }
×
2565

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

2577
                // Set the active flag now that we've completed the full
2578
                // startup.
2579
                atomic.StoreInt32(&s.active, 1)
×
2580
        })
2581

2582
        if startErr != nil {
×
2583
                cleanup.run()
×
2584
        }
×
2585
        return startErr
×
2586
}
2587

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

×
2596
                ctx := context.Background()
×
2597

×
2598
                close(s.quit)
×
2599

×
2600
                // Shutdown connMgr first to prevent conns during shutdown.
×
2601
                s.connMgr.Stop()
×
2602

×
2603
                // Stop dispatching blocks to other systems immediately.
×
2604
                s.blockbeatDispatcher.Stop()
×
2605

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

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

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

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

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

2723
                if s.hostAnn != nil {
×
2724
                        if err := s.hostAnn.Stop(); err != nil {
×
2725
                                srvrLog.Warnf("unable to shut down host "+
×
2726
                                        "annoucner: %v", err)
×
2727
                        }
×
2728
                }
2729

2730
                if s.livenessMonitor != nil {
×
2731
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2732
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2733
                                        "monitor: %v", err)
×
2734
                        }
×
2735
                }
2736

2737
                // Wait for all lingering goroutines to quit.
2738
                srvrLog.Debug("Waiting for server to shutdown...")
×
2739
                s.wg.Wait()
×
2740

×
2741
                srvrLog.Debug("Stopping buffer pools...")
×
2742
                s.sigPool.Stop()
×
2743
                s.writePool.Stop()
×
2744
                s.readPool.Stop()
×
2745
        })
2746

2747
        return nil
×
2748
}
2749

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

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

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

2775
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2776
                externalIPs = append(externalIPs, hostIP)
×
2777
        }
2778

2779
        return externalIPs, nil
×
2780
}
2781

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

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

×
2806
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2807
        // up by the server.
×
2808
        defer s.removePortForwarding()
×
2809

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

2817
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2818

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

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

2849
                        if ip.Equal(s.lastDetectedIP) {
×
2850
                                continue
×
2851
                        }
2852

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

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

2870
                                newAddrs = append(newAddrs, addr)
×
2871
                        }
2872

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

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

×
2889
                        for _, addr := range currentNodeAnn.Addresses {
×
2890
                                host, _, err := net.SplitHostPort(addr.String())
×
2891
                                if err != nil {
×
2892
                                        srvrLog.Debugf("Unable to determine "+
×
2893
                                                "host from address %v: %v",
×
2894
                                                addr, err)
×
2895
                                        continue
×
2896
                                }
2897

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

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

2918
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2919
                        if err != nil {
×
2920
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2921
                                        "announcement to peers: %v", err)
×
2922
                                continue
×
2923
                        }
2924

2925
                        // Finally, update the last IP seen to the current one.
2926
                        s.lastDetectedIP = ip
×
2927
                case <-s.quit:
×
2928
                        break out
×
2929
                }
2930
        }
2931
}
2932

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

×
2939
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2940

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

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

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

×
2966
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2967
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2968
                        )
×
2969
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2970
                }
×
2971
        }
2972

2973
        return bootStrappers, nil
×
2974
}
2975

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

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

×
2988
        // We should ignore ourselves from bootstrapping.
×
2989
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2990
        ignore[selfKey] = struct{}{}
×
2991

×
2992
        // Ignore all connected peers.
×
2993
        for _, peer := range s.peersByPub {
×
2994
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2995
                ignore[nID] = struct{}{}
×
2996
        }
×
2997

2998
        // Ignore all persistent peers as they have a dedicated reconnecting
2999
        // process.
3000
        for pubKeyStr := range s.persistentPeers {
×
3001
                var nID autopilot.NodeID
×
3002
                copy(nID[:], []byte(pubKeyStr))
×
3003
                ignore[nID] = struct{}{}
×
3004
        }
×
3005

3006
        return ignore
×
3007
}
3008

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

×
3017
        defer s.wg.Done()
×
3018

×
3019
        // Before we continue, init the ignore peers map.
×
3020
        ignoreList := s.createBootstrapIgnorePeers()
×
3021

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

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

×
3033
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3034
        // see if we've reached our minimum number of peers.
×
3035
        sampleTicker := time.NewTicker(backOff)
×
3036
        defer sampleTicker.Stop()
×
3037

×
3038
        // We'll use the number of attempts and errors to determine if we need
×
3039
        // to increase the time between discovery epochs.
×
3040
        var epochErrors uint32 // To be used atomically.
×
3041
        var epochAttempts uint32
×
3042

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

×
3054
                        // If we have enough peers, then we can loop back
×
3055
                        // around to the next round as we're done here.
×
3056
                        if numActivePeers >= numTargetPeers {
×
3057
                                continue
×
3058
                        }
3059

3060
                        // If all of our attempts failed during this last back
3061
                        // off period, then will increase our backoff to 5
3062
                        // minute ceiling to avoid an excessive number of
3063
                        // queries
3064
                        //
3065
                        // TODO(roasbeef): add reverse policy too?
3066

3067
                        if epochAttempts > 0 &&
×
3068
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3069

×
3070
                                sampleTicker.Stop()
×
3071

×
3072
                                backOff *= 2
×
3073
                                if backOff > bootstrapBackOffCeiling {
×
3074
                                        backOff = bootstrapBackOffCeiling
×
3075
                                }
×
3076

3077
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3078
                                        "%v", backOff)
×
3079
                                sampleTicker = time.NewTicker(backOff)
×
3080
                                continue
×
3081
                        }
3082

3083
                        atomic.StoreUint32(&epochErrors, 0)
×
3084
                        epochAttempts = 0
×
3085

×
3086
                        // Since we know need more peers, we'll compute the
×
3087
                        // exact number we need to reach our threshold.
×
3088
                        numNeeded := numTargetPeers - numActivePeers
×
3089

×
3090
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3091
                                "peers", numNeeded)
×
3092

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

×
3101
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3102
                                ctx, ignoreList, numNeeded*2, bootstrappers...,
×
3103
                        )
×
3104
                        if err != nil {
×
3105
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3106
                                        "peers: %v", err)
×
3107
                                continue
×
3108
                        }
3109

3110
                        // Finally, we'll launch a new goroutine for each
3111
                        // prospective peer candidates.
3112
                        for _, addr := range peerAddrs {
×
3113
                                epochAttempts++
×
3114

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

3129
                                                srvrLog.Errorf("Unable to "+
×
3130
                                                        "connect to %v: %v",
×
3131
                                                        a, err)
×
3132
                                                atomic.AddUint32(&epochErrors, 1)
×
3133
                                        case <-s.quit:
×
3134
                                        }
3135
                                }(addr)
3136
                        }
3137
                case <-s.quit:
×
3138
                        return
×
3139
                }
3140
        }
3141
}
3142

3143
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3144
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3145
// query back off each time we encounter a failure.
3146
const bootstrapBackOffCeiling = time.Minute * 5
3147

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

×
3155
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3156
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3157

×
3158
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3159
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3160
        var delaySignal <-chan time.Time
×
3161
        delayTime := time.Second * 2
×
3162

×
3163
        // As want to be more aggressive, we'll use a lower back off celling
×
3164
        // then the main peer bootstrap logic.
×
3165
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3166

×
3167
        for attempts := 0; ; attempts++ {
×
3168
                // Check if the server has been requested to shut down in order
×
3169
                // to prevent blocking.
×
3170
                if s.Stopped() {
×
3171
                        return
×
3172
                }
×
3173

3174
                // We can exit our aggressive initial peer bootstrapping stage
3175
                // if we've reached out target number of peers.
3176
                s.mu.RLock()
×
3177
                numActivePeers := uint32(len(s.peersByPub))
×
3178
                s.mu.RUnlock()
×
3179

×
3180
                if numActivePeers >= numTargetPeers {
×
3181
                        return
×
3182
                }
×
3183

3184
                if attempts > 0 {
×
3185
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3186
                                "bootstrap peers (attempt #%v)", delayTime,
×
3187
                                attempts)
×
3188

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

3199
                        // After our delay, we'll double the time we wait up to
3200
                        // the max back off period.
3201
                        delayTime *= 2
×
3202
                        if delayTime > backOffCeiling {
×
3203
                                delayTime = backOffCeiling
×
3204
                        }
×
3205
                }
3206

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

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

×
3227
                                errChan := make(chan error, 1)
×
3228
                                go s.connectToPeer(
×
3229
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3230
                                )
×
3231

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

3255
                wg.Wait()
×
3256
        }
3257
}
3258

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

3271
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3272
        if err != nil {
×
3273
                return err
×
3274
        }
×
3275

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

×
3288
        switch {
×
3289
        case s.cfg.Tor.V2:
×
3290
                onionCfg.Type = tor.V2
×
3291
        case s.cfg.Tor.V3:
×
3292
                onionCfg.Type = tor.V3
×
3293
        }
3294

3295
        addr, err := s.torController.AddOnion(onionCfg)
×
3296
        if err != nil {
×
3297
                return err
×
3298
        }
×
3299

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

3312
        // Finally, we'll update the on-disk version of our announcement so it
3313
        // will eventually propagate to nodes in the network.
3314
        selfNode := models.NewV1Node(
×
3315
                route.NewVertex(s.identityECDH.PubKey()), &models.NodeV1Fields{
×
3316
                        Addresses:    newNodeAnn.Addresses,
×
3317
                        Features:     newNodeAnn.Features,
×
3318
                        AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3319
                        Color:        newNodeAnn.RGBColor,
×
3320
                        Alias:        newNodeAnn.Alias.String(),
×
3321
                        LastUpdate:   time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3322
                },
×
3323
        )
×
3324

×
3325
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3326
                return fmt.Errorf("can't set self node: %w", err)
×
3327
        }
×
3328

3329
        return nil
×
3330
}
3331

3332
// findChannel finds a channel given a public key and ChannelID. It is an
3333
// optimization that is quicker than seeking for a channel given only the
3334
// ChannelID.
3335
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3336
        *channeldb.OpenChannel, error) {
×
3337

×
3338
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3339
        if err != nil {
×
3340
                return nil, err
×
3341
        }
×
3342

3343
        for _, channel := range nodeChans {
×
3344
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3345
                        return channel, nil
×
3346
                }
×
3347
        }
3348

3349
        return nil, fmt.Errorf("unable to find channel")
×
3350
}
3351

3352
// getNodeAnnouncement fetches the current, fully signed node announcement.
3353
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement1 {
×
3354
        s.mu.Lock()
×
3355
        defer s.mu.Unlock()
×
3356

×
3357
        return *s.currentNodeAnn
×
3358
}
×
3359

3360
// genNodeAnnouncement generates and returns the current fully signed node
3361
// announcement. The time stamp of the announcement will be updated in order
3362
// to ensure it propagates through the network.
3363
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3364
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement1, error) {
×
3365

×
3366
        s.mu.Lock()
×
3367
        defer s.mu.Unlock()
×
3368

×
3369
        // Create a shallow copy of the current node announcement to work on.
×
3370
        // This ensures the original announcement remains unchanged
×
3371
        // until the new announcement is fully signed and valid.
×
3372
        newNodeAnn := *s.currentNodeAnn
×
3373

×
3374
        // First, try to update our feature manager with the updated set of
×
3375
        // features.
×
3376
        if features != nil {
×
3377
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
3378
                        feature.SetNodeAnn: features,
×
3379
                }
×
3380
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
3381
                if err != nil {
×
3382
                        return lnwire.NodeAnnouncement1{}, err
×
3383
                }
×
3384

3385
                // If we could successfully update our feature manager, add
3386
                // an update modifier to include these new features to our
3387
                // set.
3388
                modifiers = append(
×
3389
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3390
                )
×
3391
        }
3392

3393
        // Always update the timestamp when refreshing to ensure the update
3394
        // propagates.
3395
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3396

×
3397
        // Apply the requested changes to the node announcement.
×
3398
        for _, modifier := range modifiers {
×
3399
                modifier(&newNodeAnn)
×
3400
        }
×
3401

3402
        // The modifiers may have added duplicate addresses, so we need to
3403
        // de-duplicate them here.
3404
        uniqueAddrs := map[string]struct{}{}
×
3405
        dedupedAddrs := make([]net.Addr, 0)
×
3406
        for _, addr := range newNodeAnn.Addresses {
×
3407
                if _, ok := uniqueAddrs[addr.String()]; !ok {
×
3408
                        uniqueAddrs[addr.String()] = struct{}{}
×
3409
                        dedupedAddrs = append(dedupedAddrs, addr)
×
3410
                }
×
3411
        }
3412
        newNodeAnn.Addresses = dedupedAddrs
×
3413

×
3414
        // Sign a new update after applying all of the passed modifiers.
×
3415
        err := netann.SignNodeAnnouncement(
×
3416
                s.nodeSigner, s.identityKeyLoc, &newNodeAnn,
×
3417
        )
×
3418
        if err != nil {
×
3419
                return lnwire.NodeAnnouncement1{}, err
×
3420
        }
×
3421

3422
        // If signing succeeds, update the current announcement.
3423
        *s.currentNodeAnn = newNodeAnn
×
3424

×
3425
        return *s.currentNodeAnn, nil
×
3426
}
3427

3428
// updateAndBroadcastSelfNode generates a new node announcement
3429
// applying the giving modifiers and updating the time stamp
3430
// to ensure it propagates through the network. Then it broadcasts
3431
// it to the network.
3432
func (s *server) updateAndBroadcastSelfNode(ctx context.Context,
3433
        features *lnwire.RawFeatureVector,
3434
        modifiers ...netann.NodeAnnModifier) error {
×
3435

×
3436
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
3437
        if err != nil {
×
3438
                return fmt.Errorf("unable to generate new node "+
×
3439
                        "announcement: %v", err)
×
3440
        }
×
3441

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

3450
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
3451
        selfNode.Addresses = newNodeAnn.Addresses
×
3452
        selfNode.Alias = fn.Some(newNodeAnn.Alias.String())
×
3453
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
3454
        selfNode.Color = fn.Some(newNodeAnn.RGBColor)
×
3455
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
3456

×
3457
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3458

×
3459
        if err := s.graphDB.SetSourceNode(ctx, selfNode); err != nil {
×
3460
                return fmt.Errorf("can't set self node: %w", err)
×
3461
        }
×
3462

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

3471
        return nil
×
3472
}
3473

3474
type nodeAddresses struct {
3475
        pubKey    *btcec.PublicKey
3476
        addresses []net.Addr
3477
}
3478

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

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

3497
        for _, node := range linkNodes {
×
3498
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
3499
                nodeAddrs := &nodeAddresses{
×
3500
                        pubKey:    node.IdentityPub,
×
3501
                        addresses: node.Addresses,
×
3502
                }
×
3503
                nodeAddrsMap[pubStr] = nodeAddrs
×
3504
        }
×
3505

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

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

3523
                pubStr := string(channelPeer.PubKeyBytes[:])
×
3524

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

3534
                        // We'll only attempt to connect to Tor addresses if Tor
3535
                        // outbound support is enabled.
3536
                        case *tor.OnionAddr:
×
3537
                                if s.cfg.Tor.Active {
×
3538
                                        addrSet[addr.String()] = addr
×
3539
                                }
×
3540
                        }
3541
                }
3542

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

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

3563
                // Construct a slice of the deduped addresses.
3564
                var addrs []net.Addr
×
3565
                for _, addr := range addrSet {
×
3566
                        addrs = append(addrs, addr)
×
3567
                }
×
3568

3569
                n := &nodeAddresses{
×
3570
                        addresses: addrs,
×
3571
                }
×
3572
                n.pubKey, err = channelPeer.PubKey()
×
3573
                if err != nil {
×
3574
                        return err
×
3575
                }
×
3576

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

×
3589
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3590
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3591

×
3592
                        return err
×
3593
                }
×
3594
        }
3595

3596
        // Combine the addresses from the link nodes and the channel graph.
3597
        for pubStr, nodeAddr := range graphAddrs {
×
3598
                nodeAddrsMap[pubStr] = nodeAddr
×
3599
        }
×
3600

3601
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
3602
                len(nodeAddrsMap))
×
3603

×
3604
        // Acquire and hold server lock until all persistent connection requests
×
3605
        // have been recorded and sent to the connection manager.
×
3606
        s.mu.Lock()
×
3607
        defer s.mu.Unlock()
×
3608

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

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

×
3632
                        s.persistentPeerAddrs[pubStr] = append(
×
3633
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3634
                }
×
3635

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

×
3646
                        go s.connectToPersistentPeer(pubStr)
×
3647
                } else {
×
3648
                        go s.delayInitialReconnect(pubStr)
×
3649
                }
×
3650

3651
                numOutboundConns++
×
3652
        }
3653

3654
        return nil
×
3655
}
3656

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

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

×
3676
        s.mu.Lock()
×
3677
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3678
                delete(s.persistentPeers, pubKeyStr)
×
3679
                delete(s.persistentPeersBackoff, pubKeyStr)
×
3680
                delete(s.persistentPeerAddrs, pubKeyStr)
×
3681
                s.cancelConnReqs(pubKeyStr, nil)
×
3682
                s.mu.Unlock()
×
3683

×
3684
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
3685
                        "peer has no open channels", compressedPubKey)
×
3686

×
3687
                return
×
3688
        }
×
3689
        s.mu.Unlock()
×
3690
}
3691

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

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

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

3732
                peers = append(peers, sPeer)
×
3733
        }
3734
        s.mu.RUnlock()
×
3735

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

×
3743
                // Dispatch a go routine to enqueue all messages to this peer.
×
3744
                wg.Add(1)
×
3745
                s.wg.Add(1)
×
3746
                go func(p lnpeer.Peer) {
×
3747
                        defer s.wg.Done()
×
3748
                        defer wg.Done()
×
3749

×
3750
                        p.SendMessageLazy(false, msgs...)
×
3751
                }(sPeer)
×
3752
        }
3753

3754
        // Wait for all messages to have been dispatched before returning to
3755
        // caller.
3756
        wg.Wait()
×
3757

×
3758
        return nil
×
3759
}
3760

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

×
3768
        s.mu.Lock()
×
3769

×
3770
        // Compute the target peer's identifier.
×
3771
        pubStr := string(peerKey[:])
×
3772

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

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

3795
                // Connected, can return early.
3796
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
3797

×
3798
                select {
×
3799
                case peerChan <- peer:
×
3800
                case <-s.quit:
×
3801
                }
3802

3803
                return
×
3804
        }
3805

3806
        // Not connected, store this listener such that it can be notified when
3807
        // the peer comes online.
3808
        s.peerConnectedListeners[pubStr] = append(
×
3809
                s.peerConnectedListeners[pubStr], peerChan,
×
3810
        )
×
3811
        s.mu.Unlock()
×
3812
}
3813

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

×
3821
        c := make(chan struct{})
×
3822

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

3832
        // Otherwise, the peer is online, so we'll keep track of the channel to
3833
        // trigger the notification once the server detects the peer
3834
        // disconnects.
3835
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
3836
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
3837
        )
×
3838

×
3839
        return c
×
3840
}
3841

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

×
3851
        pubStr := string(peerKey.SerializeCompressed())
×
3852

×
3853
        return s.findPeerByPubStr(pubStr)
×
3854
}
×
3855

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

×
3865
        return s.findPeerByPubStr(pubStr)
×
3866
}
×
3867

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

3876
        return peer, nil
×
3877
}
3878

3879
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3880
// exponential backoff. If no previous backoff was known, the default is
3881
// returned.
3882
func (s *server) nextPeerBackoff(pubStr string,
3883
        startTime time.Time) time.Duration {
×
3884

×
3885
        // Now, determine the appropriate backoff to use for the retry.
×
3886
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
3887
        if !ok {
×
3888
                // If an existing backoff was unknown, use the default.
×
3889
                return s.cfg.MinBackoff
×
3890
        }
×
3891

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

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

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

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

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

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

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

3951
        nodePub := conn.(*brontide.Conn).RemotePub()
×
3952
        pubSer := nodePub.SerializeCompressed()
×
3953
        pubStr := string(pubSer)
×
3954

×
3955
        var pubBytes [33]byte
×
3956
        copy(pubBytes[:], pubSer)
×
3957

×
3958
        s.mu.Lock()
×
3959
        defer s.mu.Unlock()
×
3960

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

×
3968
                conn.Close()
×
3969
                return
×
3970
        }
×
3971

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

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

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

3997
        case nil:
×
3998
                ctx := btclog.WithCtx(
×
3999
                        context.TODO(),
×
4000
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
4001
                )
×
4002

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

×
4012
                        srvrLog.WarnS(ctx, "Received inbound connection from "+
×
4013
                                "peer, but already have outbound "+
×
4014
                                "connection, dropping conn",
×
4015
                                fmt.Errorf("already have outbound conn"))
×
4016
                        conn.Close()
×
4017
                        return
×
4018
                }
×
4019

4020
                // Otherwise, if we should drop the connection, then we'll
4021
                // disconnect our already connected peer.
4022
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4023

×
4024
                s.cancelConnReqs(pubStr, nil)
×
4025

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

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

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

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

×
4054
        s.mu.Lock()
×
4055
        defer s.mu.Unlock()
×
4056

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

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

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

×
4083
                if connReq != nil {
×
4084
                        s.connMgr.Remove(connReq.ID())
×
4085
                }
×
4086

4087
                conn.Close()
×
4088
                return
×
4089
        }
4090

4091
        srvrLog.Infof("Established outbound connection to: %x@%v", pubStr,
×
4092
                conn.RemoteAddr())
×
4093

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

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

4117
        case nil:
×
4118
                ctx := btclog.WithCtx(
×
4119
                        context.TODO(),
×
4120
                        lnutils.LogPubKey("peer", connectedPeer.IdentityKey()),
×
4121
                )
×
4122

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

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

4143
                // Otherwise, _their_ connection should be dropped. So we'll
4144
                // disconnect the peer and send the now obsolete peer to the
4145
                // server for garbage collection.
4146
                srvrLog.DebugS(ctx, "Disconnecting stale connection")
×
4147

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

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

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

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

4187
        for _, connReq := range connReqs {
×
4188
                srvrLog.Tracef("Canceling %s:", connReqs)
×
4189

×
4190
                // Atomically capture the current request identifier.
×
4191
                connID := connReq.ID()
×
4192

×
4193
                // Skip any zero IDs, this indicates the request has not
×
4194
                // yet been schedule.
×
4195
                if connID == UnassignedConnID {
×
4196
                        continue
×
4197
                }
4198

4199
                // Skip a particular connection ID if instructed.
4200
                if skip != nil && connID == *skip {
×
4201
                        continue
×
4202
                }
4203

4204
                s.connMgr.Remove(connID)
×
4205
        }
4206

4207
        delete(s.persistentConnReqs, pubStr)
×
4208
}
4209

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

×
4216
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4217
                Peer: peer,
×
4218
                Msg:  msg,
×
4219
        })
×
4220
}
×
4221

4222
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4223
// messages.
4224
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4225
        return s.customMessageServer.Subscribe()
×
4226
}
×
4227

4228
// SubscribeOnionMessages subscribes to a stream of incoming onion messages.
4229
func (s *server) SubscribeOnionMessages() (*subscribe.Client, error) {
×
4230
        return s.onionMessageServer.Subscribe()
×
4231
}
×
4232

4233
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4234
// the channelNotifier's NotifyOpenChannelEvent.
4235
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4236
        remotePub *btcec.PublicKey) {
×
4237

×
4238
        // Call newOpenChan to update the access manager's maps for this peer.
×
4239
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
×
4240
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4241
                        "channel[%v] open", remotePub.SerializeCompressed(), op)
×
4242
        }
×
4243

4244
        // Notify subscribers about this open channel event.
4245
        s.channelNotifier.NotifyOpenChannelEvent(op)
×
4246
}
4247

4248
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4249
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4250
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4251
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) {
×
4252

×
4253
        // Call newPendingOpenChan to update the access manager's maps for this
×
4254
        // peer.
×
4255
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
×
4256
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4257
                        "channel[%v] pending open",
×
4258
                        remotePub.SerializeCompressed(), op)
×
4259
        }
×
4260

4261
        // Notify subscribers about this event.
4262
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
×
4263
}
4264

4265
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4266
// calls the channelNotifier's NotifyFundingTimeout.
4267
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4268
        remotePub *btcec.PublicKey) {
×
4269

×
4270
        // Call newPendingCloseChan to potentially demote the peer.
×
4271
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
×
4272
        if err != nil {
×
4273
                srvrLog.Errorf("Failed to update peer[%x] access status after "+
×
4274
                        "channel[%v] pending close",
×
4275
                        remotePub.SerializeCompressed(), op)
×
4276
        }
×
4277

4278
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
×
4279
                // If we encounter an error while attempting to disconnect the
×
4280
                // peer, log the error.
×
4281
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4282
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4283
                }
×
4284
        }
4285

4286
        // Notify subscribers about this event.
4287
        s.channelNotifier.NotifyFundingTimeout(op)
×
4288
}
4289

4290
// peerConnected is a function that handles initialization a newly connected
4291
// peer by adding it to the server's global list of all active peers, and
4292
// starting all the goroutines the peer needs to function properly. The inbound
4293
// boolean should be true if the peer initiated the connection to us.
4294
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4295
        inbound bool) {
×
4296

×
4297
        brontideConn := conn.(*brontide.Conn)
×
4298
        addr := conn.RemoteAddr()
×
4299
        pubKey := brontideConn.RemotePub()
×
4300

×
4301
        // Only restrict access for inbound connections, which means if the
×
4302
        // remote node's public key is banned or the restricted slots are used
×
4303
        // up, we will drop the connection.
×
4304
        //
×
4305
        // TODO(yy): Consider perform this check in
×
4306
        // `peerAccessMan.addPeerAccess`.
×
4307
        access, err := s.peerAccessMan.assignPeerPerms(pubKey)
×
4308
        if inbound && err != nil {
×
4309
                pubSer := pubKey.SerializeCompressed()
×
4310

×
4311
                // Clean up the persistent peer maps if we're dropping this
×
4312
                // connection.
×
4313
                s.bannedPersistentPeerConnection(string(pubSer))
×
4314

×
4315
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4316
                        "of restricted-access connection slots: %v.", pubSer,
×
4317
                        err)
×
4318

×
4319
                conn.Close()
×
4320

×
4321
                return
×
4322
        }
×
4323

4324
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
4325
                pubKey.SerializeCompressed(), addr, inbound)
×
4326

×
4327
        peerAddr := &lnwire.NetAddress{
×
4328
                IdentityKey: pubKey,
×
4329
                Address:     addr,
×
4330
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4331
        }
×
4332

×
4333
        // With the brontide connection established, we'll now craft the feature
×
4334
        // vectors to advertise to the remote node.
×
4335
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
4336
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
4337

×
4338
        // Lookup past error caches for the peer in the server. If no buffer is
×
4339
        // found, create a fresh buffer.
×
4340
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
4341
        errBuffer, ok := s.peerErrors[pkStr]
×
4342
        if !ok {
×
4343
                var err error
×
4344
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
4345
                if err != nil {
×
4346
                        srvrLog.Errorf("unable to create peer %v", err)
×
4347
                        return
×
4348
                }
×
4349
        }
4350

4351
        // If we directly set the peer.Config TowerClient member to the
4352
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4353
        // the peer.Config's TowerClient member will not evaluate to nil even
4354
        // though the underlying value is nil. To avoid this gotcha which can
4355
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4356
        // TowerClient if needed.
4357
        var towerClient wtclient.ClientManager
×
4358
        if s.towerClientMgr != nil {
×
4359
                towerClient = s.towerClientMgr
×
4360
        }
×
4361

4362
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
4363
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
4364

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

×
4409
                        return s.genNodeAnnouncement(nil)
×
4410
                },
×
4411

4412
                PongBuf: s.pongBuf,
4413

4414
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4415

4416
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4417

4418
                FundingManager: s.fundingMgr,
4419

4420
                Hodl:                    s.cfg.Hodl,
4421
                UnsafeReplay:            s.cfg.UnsafeReplay,
4422
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4423
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4424
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4425
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4426
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4427
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4428
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4429
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4430
                HandleCustomMessage:    s.handleCustomMessage,
4431
                GetAliases:             s.aliasMgr.GetAliases,
4432
                RequestAlias:           s.aliasMgr.RequestAlias,
4433
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4434
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4435
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4436
                QuiescenceTimeout:      s.cfg.Htlcswitch.QuiescenceTimeout,
4437
                MaxFeeExposure:         thresholdMSats,
4438
                Quit:                   s.quit,
4439
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4440
                AuxSigner:              s.implCfg.AuxSigner,
4441
                MsgRouter:              s.implCfg.MsgRouter,
4442
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4443
                AuxResolver:            s.implCfg.AuxContractResolver,
4444
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4445
                AuxChannelNegotiator:   s.implCfg.AuxChannelNegotiator,
4446
                ShouldFwdExpEndorsement: func() bool {
×
4447
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
4448
                                return false
×
4449
                        }
×
4450

4451
                        return clock.NewDefaultClock().Now().Before(
×
4452
                                EndorsementExperimentEnd,
×
4453
                        )
×
4454
                },
4455
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4456
        }
4457

4458
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
4459
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
4460

×
4461
        p := peer.NewBrontide(pCfg)
×
4462

×
4463
        // Update the access manager with the access permission for this peer.
×
4464
        s.peerAccessMan.addPeerAccess(pubKey, access, inbound)
×
4465

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

×
4469
        s.addPeer(p)
×
4470

×
4471
        // Once we have successfully added the peer to the server, we can
×
4472
        // delete the previous error buffer from the server's map of error
×
4473
        // buffers.
×
4474
        delete(s.peerErrors, pkStr)
×
4475

×
4476
        // Dispatch a goroutine to asynchronously start the peer. This process
×
4477
        // includes sending and receiving Init messages, which would be a DOS
×
4478
        // vector if we held the server's mutex throughout the procedure.
×
4479
        s.wg.Add(1)
×
4480
        go s.peerInitializer(p)
×
4481
}
4482

4483
// addPeer adds the passed peer to the server's global state of all active
4484
// peers.
4485
func (s *server) addPeer(p *peer.Brontide) {
×
4486
        if p == nil {
×
4487
                return
×
4488
        }
×
4489

4490
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4491

×
4492
        // Ignore new peers if we're shutting down.
×
4493
        if s.Stopped() {
×
4494
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4495
                        pubBytes)
×
4496
                p.Disconnect(ErrServerShuttingDown)
×
4497

×
4498
                return
×
4499
        }
×
4500

4501
        // Track the new peer in our indexes so we can quickly look it up either
4502
        // according to its public key, or its peer ID.
4503
        // TODO(roasbeef): pipe all requests through to the
4504
        // queryHandler/peerManager
4505

4506
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4507
        // be human-readable.
4508
        pubStr := string(pubBytes)
×
4509

×
4510
        s.peersByPub[pubStr] = p
×
4511

×
4512
        if p.Inbound() {
×
4513
                s.inboundPeers[pubStr] = p
×
4514
        } else {
×
4515
                s.outboundPeers[pubStr] = p
×
4516
        }
×
4517

4518
        // Inform the peer notifier of a peer online event so that it can be reported
4519
        // to clients listening for peer events.
4520
        var pubKey [33]byte
×
4521
        copy(pubKey[:], pubBytes)
×
4522
}
4523

4524
// peerInitializer asynchronously starts a newly connected peer after it has
4525
// been added to the server's peer map. This method sets up a
4526
// peerTerminationWatcher for the given peer, and ensures that it executes even
4527
// if the peer failed to start. In the event of a successful connection, this
4528
// method reads the negotiated, local feature-bits and spawns the appropriate
4529
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4530
// be signaled of the new peer once the method returns.
4531
//
4532
// NOTE: This MUST be launched as a goroutine.
4533
func (s *server) peerInitializer(p *peer.Brontide) {
×
4534
        defer s.wg.Done()
×
4535

×
4536
        pubBytes := p.IdentityKey().SerializeCompressed()
×
4537

×
4538
        // Avoid initializing peers while the server is exiting.
×
4539
        if s.Stopped() {
×
4540
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4541
                        pubBytes)
×
4542
                return
×
4543
        }
×
4544

4545
        // Create a channel that will be used to signal a successful start of
4546
        // the link. This prevents the peer termination watcher from beginning
4547
        // its duty too early.
4548
        ready := make(chan struct{})
×
4549

×
4550
        // Before starting the peer, launch a goroutine to watch for the
×
4551
        // unexpected termination of this peer, which will ensure all resources
×
4552
        // are properly cleaned up, and re-establish persistent connections when
×
4553
        // necessary. The peer termination watcher will be short circuited if
×
4554
        // the peer is ever added to the ignorePeerTermination map, indicating
×
4555
        // that the server has already handled the removal of this peer.
×
4556
        s.wg.Add(1)
×
4557
        go s.peerTerminationWatcher(p, ready)
×
4558

×
4559
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
4560
        // will unblock the peerTerminationWatcher.
×
4561
        if err := p.Start(); err != nil {
×
4562
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4563

×
4564
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4565
                return
×
4566
        }
×
4567

4568
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4569
        // was successful, and to begin watching the peer's wait group.
4570
        close(ready)
×
4571

×
4572
        s.mu.Lock()
×
4573
        defer s.mu.Unlock()
×
4574

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

×
4578
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
4579
        // route.Vertex as the key type of peerConnectedListeners.
×
4580
        pubStr := string(pubBytes)
×
4581
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
4582
                select {
×
4583
                case peerChan <- p:
×
4584
                case <-s.quit:
×
4585
                        return
×
4586
                }
4587
        }
4588
        delete(s.peerConnectedListeners, pubStr)
×
4589

×
4590
        // Since the peer has been fully initialized, now it's time to notify
×
4591
        // the RPC about the peer online event.
×
4592
        s.peerNotifier.NotifyPeerOnline([33]byte(pubBytes))
×
4593
}
4594

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

×
4609
        ctx := btclog.WithCtx(
×
4610
                context.TODO(), lnutils.LogPubKey("peer", p.IdentityKey()),
×
4611
        )
×
4612

×
4613
        p.WaitForDisconnect(ready)
×
4614

×
4615
        srvrLog.DebugS(ctx, "Peer has been disconnected")
×
4616

×
4617
        // If the server is exiting then we can bail out early ourselves as all
×
4618
        // the other sub-systems will already be shutting down.
×
4619
        if s.Stopped() {
×
4620
                srvrLog.DebugS(ctx, "Server quitting, exit early for peer")
×
4621
                return
×
4622
        }
×
4623

4624
        // Next, we'll cancel all pending funding reservations with this node.
4625
        // If we tried to initiate any funding flows that haven't yet finished,
4626
        // then we need to unlock those committed outputs so they're still
4627
        // available for use.
4628
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
4629

×
4630
        pubKey := p.IdentityKey()
×
4631

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

×
4636
        // Tell the switch to remove all links associated with this peer.
×
4637
        // Passing nil as the target link indicates that all links associated
×
4638
        // with this interface should be closed.
×
4639
        //
×
4640
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
4641
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
4642
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4643
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4644
        }
×
4645

4646
        for _, link := range links {
×
4647
                s.htlcSwitch.RemoveLink(link.ChanID())
×
4648
        }
×
4649

4650
        s.mu.Lock()
×
4651
        defer s.mu.Unlock()
×
4652

×
4653
        // If there were any notification requests for when this peer
×
4654
        // disconnected, we can trigger them now.
×
4655
        srvrLog.DebugS(ctx, "Notifying that peer is offline")
×
4656
        pubStr := string(pubKey.SerializeCompressed())
×
4657
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
4658
                close(offlineChan)
×
4659
        }
×
4660
        delete(s.peerDisconnectedListeners, pubStr)
×
4661

×
4662
        // If the server has already removed this peer, we can short circuit the
×
4663
        // peer termination watcher and skip cleanup.
×
4664
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4665
                delete(s.ignorePeerTermination, p)
×
4666

×
4667
                pubKey := p.PubKey()
×
4668
                pubStr := string(pubKey[:])
×
4669

×
4670
                // If a connection callback is present, we'll go ahead and
×
4671
                // execute it now that previous peer has fully disconnected. If
×
4672
                // the callback is not present, this likely implies the peer was
×
4673
                // purposefully disconnected via RPC, and that no reconnect
×
4674
                // should be attempted.
×
4675
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4676
                if ok {
×
4677
                        delete(s.scheduledPeerConnection, pubStr)
×
4678
                        connCallback()
×
4679
                }
×
4680
                return
×
4681
        }
4682

4683
        // First, cleanup any remaining state the server has regarding the peer
4684
        // in question.
4685
        s.removePeerUnsafe(ctx, p)
×
4686

×
4687
        // Next, check to see if this is a persistent peer or not.
×
4688
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
4689
                return
×
4690
        }
×
4691

4692
        // Get the last address that we used to connect to the peer.
4693
        addrs := []net.Addr{
×
4694
                p.NetAddress().Address,
×
4695
        }
×
4696

×
4697
        // We'll ensure that we locate all the peers advertised addresses for
×
4698
        // reconnection purposes.
×
4699
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(ctx, pubKey)
×
4700
        switch {
×
4701
        // We found advertised addresses, so use them.
4702
        case err == nil:
×
4703
                addrs = advertisedAddrs
×
4704

4705
        // The peer doesn't have an advertised address.
4706
        case err == errNoAdvertisedAddr:
×
4707
                // If it is an outbound peer then we fall back to the existing
×
4708
                // peer address.
×
4709
                if !p.Inbound() {
×
4710
                        break
×
4711
                }
4712

4713
                // Fall back to the existing peer address if
4714
                // we're not accepting connections over Tor.
4715
                if s.torController == nil {
×
4716
                        break
×
4717
                }
4718

4719
                // If we are, the peer's address won't be known
4720
                // to us (we'll see a private address, which is
4721
                // the address used by our onion service to dial
4722
                // to lnd), so we don't have enough information
4723
                // to attempt a reconnect.
4724
                srvrLog.DebugS(ctx, "Ignoring reconnection attempt "+
×
4725
                        "to inbound peer without advertised address")
×
4726
                return
×
4727

4728
        // We came across an error retrieving an advertised
4729
        // address, log it, and fall back to the existing peer
4730
        // address.
4731
        default:
×
4732
                srvrLog.ErrorS(ctx, "Unable to retrieve advertised "+
×
4733
                        "address for peer", err)
×
4734
        }
4735

4736
        // Make an easy lookup map so that we can check if an address
4737
        // is already in the address list that we have stored for this peer.
4738
        existingAddrs := make(map[string]bool)
×
4739
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
4740
                existingAddrs[addr.String()] = true
×
4741
        }
×
4742

4743
        // Add any missing addresses for this peer to persistentPeerAddr.
4744
        for _, addr := range addrs {
×
4745
                if existingAddrs[addr.String()] {
×
4746
                        continue
×
4747
                }
4748

4749
                s.persistentPeerAddrs[pubStr] = append(
×
4750
                        s.persistentPeerAddrs[pubStr],
×
4751
                        &lnwire.NetAddress{
×
4752
                                IdentityKey: p.IdentityKey(),
×
4753
                                Address:     addr,
×
4754
                                ChainNet:    p.NetAddress().ChainNet,
×
4755
                        },
×
4756
                )
×
4757
        }
4758

4759
        // Record the computed backoff in the backoff map.
4760
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
4761
        s.persistentPeersBackoff[pubStr] = backoff
×
4762

×
4763
        // Initialize a retry canceller for this peer if one does not
×
4764
        // exist.
×
4765
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
4766
        if !ok {
×
4767
                cancelChan = make(chan struct{})
×
4768
                s.persistentRetryCancels[pubStr] = cancelChan
×
4769
        }
×
4770

4771
        // We choose not to wait group this go routine since the Connect
4772
        // call can stall for arbitrarily long if we shutdown while an
4773
        // outbound connection attempt is being made.
4774
        go func() {
×
4775
                srvrLog.DebugS(ctx, "Scheduling connection "+
×
4776
                        "re-establishment to persistent peer",
×
4777
                        "reconnecting_in", backoff)
×
4778

×
4779
                select {
×
4780
                case <-time.After(backoff):
×
4781
                case <-cancelChan:
×
4782
                        return
×
4783
                case <-s.quit:
×
4784
                        return
×
4785
                }
4786

4787
                srvrLog.DebugS(ctx, "Attempting to re-establish persistent "+
×
4788
                        "connection")
×
4789

×
4790
                s.connectToPersistentPeer(pubStr)
×
4791
        }()
4792
}
4793

4794
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4795
// to connect to the peer. It creates connection requests if there are
4796
// currently none for a given address and it removes old connection requests
4797
// if the associated address is no longer in the latest address list for the
4798
// peer.
4799
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
4800
        s.mu.Lock()
×
4801
        defer s.mu.Unlock()
×
4802

×
4803
        // Create an easy lookup map of the addresses we have stored for the
×
4804
        // peer. We will remove entries from this map if we have existing
×
4805
        // connection requests for the associated address and then any leftover
×
4806
        // entries will indicate which addresses we should create new
×
4807
        // connection requests for.
×
4808
        addrMap := make(map[string]*lnwire.NetAddress)
×
4809
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
4810
                addrMap[addr.String()] = addr
×
4811
        }
×
4812

4813
        // Go through each of the existing connection requests and
4814
        // check if they correspond to the latest set of addresses. If
4815
        // there is a connection requests that does not use one of the latest
4816
        // advertised addresses then remove that connection request.
4817
        var updatedConnReqs []*connmgr.ConnReq
×
4818
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
4819
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
4820

×
4821
                switch _, ok := addrMap[lnAddr]; ok {
×
4822
                // If the existing connection request is using one of the
4823
                // latest advertised addresses for the peer then we add it to
4824
                // updatedConnReqs and remove the associated address from
4825
                // addrMap so that we don't recreate this connReq later on.
4826
                case true:
×
4827
                        updatedConnReqs = append(
×
4828
                                updatedConnReqs, connReq,
×
4829
                        )
×
4830
                        delete(addrMap, lnAddr)
×
4831

4832
                // If the existing connection request is using an address that
4833
                // is not one of the latest advertised addresses for the peer
4834
                // then we remove the connecting request from the connection
4835
                // manager.
4836
                case false:
×
4837
                        srvrLog.Info(
×
4838
                                "Removing conn req:", connReq.Addr.String(),
×
4839
                        )
×
4840
                        s.connMgr.Remove(connReq.ID())
×
4841
                }
4842
        }
4843

4844
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
4845

×
4846
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
4847
        if !ok {
×
4848
                cancelChan = make(chan struct{})
×
4849
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
4850
        }
×
4851

4852
        // Any addresses left in addrMap are new ones that we have not made
4853
        // connection requests for. So create new connection requests for those.
4854
        // If there is more than one address in the address map, stagger the
4855
        // creation of the connection requests for those.
4856
        go func() {
×
4857
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
4858
                defer ticker.Stop()
×
4859

×
4860
                for _, addr := range addrMap {
×
4861
                        // Send the persistent connection request to the
×
4862
                        // connection manager, saving the request itself so we
×
4863
                        // can cancel/restart the process as needed.
×
4864
                        connReq := &connmgr.ConnReq{
×
4865
                                Addr:      addr,
×
4866
                                Permanent: true,
×
4867
                        }
×
4868

×
4869
                        s.mu.Lock()
×
4870
                        s.persistentConnReqs[pubKeyStr] = append(
×
4871
                                s.persistentConnReqs[pubKeyStr], connReq,
×
4872
                        )
×
4873
                        s.mu.Unlock()
×
4874

×
4875
                        srvrLog.Debugf("Attempting persistent connection to "+
×
4876
                                "channel peer %v", addr)
×
4877

×
4878
                        go s.connMgr.Connect(connReq)
×
4879

×
4880
                        select {
×
4881
                        case <-s.quit:
×
4882
                                return
×
4883
                        case <-cancelChan:
×
4884
                                return
×
4885
                        case <-ticker.C:
×
4886
                        }
4887
                }
4888
        }()
4889
}
4890

4891
// removePeerUnsafe removes the passed peer from the server's state of all
4892
// active peers.
4893
//
4894
// NOTE: Server mutex must be held when calling this function.
4895
func (s *server) removePeerUnsafe(ctx context.Context, p *peer.Brontide) {
×
4896
        if p == nil {
×
4897
                return
×
4898
        }
×
4899

4900
        srvrLog.DebugS(ctx, "Removing peer")
×
4901

×
4902
        // Exit early if we have already been instructed to shutdown, the peers
×
4903
        // will be disconnected in the server shutdown process.
×
4904
        if s.Stopped() {
×
4905
                return
×
4906
        }
×
4907

4908
        // Capture the peer's public key and string representation.
4909
        pKey := p.PubKey()
×
4910
        pubSer := pKey[:]
×
4911
        pubStr := string(pubSer)
×
4912

×
4913
        delete(s.peersByPub, pubStr)
×
4914

×
4915
        if p.Inbound() {
×
4916
                delete(s.inboundPeers, pubStr)
×
4917
        } else {
×
4918
                delete(s.outboundPeers, pubStr)
×
4919
        }
×
4920

4921
        // When removing the peer we make sure to disconnect it asynchronously
4922
        // to avoid blocking the main server goroutine because it is holding the
4923
        // server's mutex. Disconnecting the peer might block and wait until the
4924
        // peer has fully started up. This can happen if an inbound and outbound
4925
        // race condition occurs.
4926
        s.wg.Add(1)
×
4927
        go func() {
×
4928
                defer s.wg.Done()
×
4929

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

×
4932
                // If this peer had an active persistent connection request,
×
4933
                // remove it.
×
4934
                if p.ConnReq() != nil {
×
4935
                        s.connMgr.Remove(p.ConnReq().ID())
×
4936
                }
×
4937

4938
                // Remove the peer's access permission from the access manager.
4939
                peerPubStr := string(p.IdentityKey().SerializeCompressed())
×
4940
                s.peerAccessMan.removePeerAccess(ctx, peerPubStr)
×
4941

×
4942
                // Copy the peer's error buffer across to the server if it has
×
4943
                // any items in it so that we can restore peer errors across
×
4944
                // connections. We need to look up the error after the peer has
×
4945
                // been disconnected because we write the error in the
×
4946
                // `Disconnect` method.
×
4947
                s.mu.Lock()
×
4948
                if p.ErrorBuffer().Total() > 0 {
×
4949
                        s.peerErrors[pubStr] = p.ErrorBuffer()
×
4950
                }
×
4951
                s.mu.Unlock()
×
4952

×
4953
                // Inform the peer notifier of a peer offline event so that it
×
4954
                // can be reported to clients listening for peer events.
×
4955
                var pubKey [33]byte
×
4956
                copy(pubKey[:], pubSer)
×
4957

×
4958
                s.peerNotifier.NotifyPeerOffline(pubKey)
×
4959
        }()
4960
}
4961

4962
// ConnectToPeer requests that the server connect to a Lightning Network peer
4963
// at the specified address. This function will *block* until either a
4964
// connection is established, or the initial handshake process fails.
4965
//
4966
// NOTE: This function is safe for concurrent access.
4967
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4968
        perm bool, timeout time.Duration) error {
×
4969

×
4970
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
4971

×
4972
        // Acquire mutex, but use explicit unlocking instead of defer for
×
4973
        // better granularity.  In certain conditions, this method requires
×
4974
        // making an outbound connection to a remote peer, which requires the
×
4975
        // lock to be released, and subsequently reacquired.
×
4976
        s.mu.Lock()
×
4977

×
4978
        // Ensure we're not already connected to this peer.
×
4979
        peer, err := s.findPeerByPubStr(targetPub)
×
4980

×
4981
        // When there's no error it means we already have a connection with this
×
4982
        // peer. If this is a dev environment with the `--unsafeconnect` flag
×
4983
        // set, we will ignore the existing connection and continue.
×
4984
        if err == nil && !s.cfg.Dev.GetUnsafeConnect() {
×
4985
                s.mu.Unlock()
×
4986
                return &errPeerAlreadyConnected{peer: peer}
×
4987
        }
×
4988

4989
        // Peer was not found, continue to pursue connection with peer.
4990

4991
        // If there's already a pending connection request for this pubkey,
4992
        // then we ignore this request to ensure we don't create a redundant
4993
        // connection.
4994
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
4995
                srvrLog.Warnf("Already have %d persistent connection "+
×
4996
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
4997
        }
×
4998

4999
        // If there's not already a pending or active connection to this node,
5000
        // then instruct the connection manager to attempt to establish a
5001
        // persistent connection to the peer.
5002
        srvrLog.Debugf("Connecting to %v", addr)
×
5003
        if perm {
×
5004
                connReq := &connmgr.ConnReq{
×
5005
                        Addr:      addr,
×
5006
                        Permanent: true,
×
5007
                }
×
5008

×
5009
                // Since the user requested a permanent connection, we'll set
×
5010
                // the entry to true which will tell the server to continue
×
5011
                // reconnecting even if the number of channels with this peer is
×
5012
                // zero.
×
5013
                s.persistentPeers[targetPub] = true
×
5014
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
5015
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
5016
                }
×
5017
                s.persistentConnReqs[targetPub] = append(
×
5018
                        s.persistentConnReqs[targetPub], connReq,
×
5019
                )
×
5020
                s.mu.Unlock()
×
5021

×
5022
                go s.connMgr.Connect(connReq)
×
5023

×
5024
                return nil
×
5025
        }
5026
        s.mu.Unlock()
×
5027

×
5028
        // If we're not making a persistent connection, then we'll attempt to
×
5029
        // connect to the target peer. If the we can't make the connection, or
×
5030
        // the crypto negotiation breaks down, then return an error to the
×
5031
        // caller.
×
5032
        errChan := make(chan error, 1)
×
5033
        s.connectToPeer(addr, errChan, timeout)
×
5034

×
5035
        select {
×
5036
        case err := <-errChan:
×
5037
                return err
×
5038
        case <-s.quit:
×
5039
                return ErrServerShuttingDown
×
5040
        }
5041
}
5042

5043
// connectToPeer establishes a connection to a remote peer. errChan is used to
5044
// notify the caller if the connection attempt has failed. Otherwise, it will be
5045
// closed.
5046
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5047
        errChan chan<- error, timeout time.Duration) {
×
5048

×
5049
        conn, err := brontide.Dial(
×
5050
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
5051
        )
×
5052
        if err != nil {
×
5053
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
5054
                select {
×
5055
                case errChan <- err:
×
5056
                case <-s.quit:
×
5057
                }
5058
                return
×
5059
        }
5060

5061
        close(errChan)
×
5062

×
5063
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
5064
                conn.LocalAddr(), conn.RemoteAddr())
×
5065

×
5066
        s.OutboundPeerConnected(nil, conn)
×
5067
}
5068

5069
// DisconnectPeer sends the request to server to close the connection with peer
5070
// identified by public key.
5071
//
5072
// NOTE: This function is safe for concurrent access.
5073
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
5074
        pubBytes := pubKey.SerializeCompressed()
×
5075
        pubStr := string(pubBytes)
×
5076

×
5077
        s.mu.Lock()
×
5078
        defer s.mu.Unlock()
×
5079

×
5080
        // Check that were actually connected to this peer. If not, then we'll
×
5081
        // exit in an error as we can't disconnect from a peer that we're not
×
5082
        // currently connected to.
×
5083
        peer, err := s.findPeerByPubStr(pubStr)
×
5084
        if err == ErrPeerNotConnected {
×
5085
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
5086
        }
×
5087

5088
        srvrLog.Infof("Disconnecting from %v", peer)
×
5089

×
5090
        s.cancelConnReqs(pubStr, nil)
×
5091

×
5092
        // If this peer was formerly a persistent connection, then we'll remove
×
5093
        // them from this map so we don't attempt to re-connect after we
×
5094
        // disconnect.
×
5095
        delete(s.persistentPeers, pubStr)
×
5096
        delete(s.persistentPeersBackoff, pubStr)
×
5097

×
5098
        // Remove the peer by calling Disconnect. Previously this was done with
×
5099
        // removePeerUnsafe, which bypassed the peerTerminationWatcher.
×
5100
        //
×
5101
        // NOTE: We call it in a goroutine to avoid blocking the main server
×
5102
        // goroutine because we might hold the server's mutex.
×
5103
        go peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
5104

×
5105
        return nil
×
5106
}
5107

5108
// OpenChannel sends a request to the server to open a channel to the specified
5109
// peer identified by nodeKey with the passed channel funding parameters.
5110
//
5111
// NOTE: This function is safe for concurrent access.
5112
func (s *server) OpenChannel(
5113
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
5114

×
5115
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
5116
        // + a ChanOpen update, and we want to make sure the funding process is
×
5117
        // not blocked if the caller is not reading the updates.
×
5118
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
5119
        req.Err = make(chan error, 1)
×
5120

×
5121
        // First attempt to locate the target peer to open a channel with, if
×
5122
        // we're unable to locate the peer then this request will fail.
×
5123
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
5124
        s.mu.RLock()
×
5125
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
5126
        if !ok {
×
5127
                s.mu.RUnlock()
×
5128

×
5129
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5130
                return req.Updates, req.Err
×
5131
        }
×
5132
        req.Peer = peer
×
5133
        s.mu.RUnlock()
×
5134

×
5135
        // We'll wait until the peer is active before beginning the channel
×
5136
        // opening process.
×
5137
        select {
×
5138
        case <-peer.ActiveSignal():
×
5139
        case <-peer.QuitSignal():
×
5140
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5141
                return req.Updates, req.Err
×
5142
        case <-s.quit:
×
5143
                req.Err <- ErrServerShuttingDown
×
5144
                return req.Updates, req.Err
×
5145
        }
5146

5147
        // If the fee rate wasn't specified at this point we fail the funding
5148
        // because of the missing fee rate information. The caller of the
5149
        // `OpenChannel` method needs to make sure that default values for the
5150
        // fee rate are set beforehand.
5151
        if req.FundingFeePerKw == 0 {
×
5152
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5153
                        "the channel opening transaction")
×
5154

×
5155
                return req.Updates, req.Err
×
5156
        }
×
5157

5158
        // Spawn a goroutine to send the funding workflow request to the funding
5159
        // manager. This allows the server to continue handling queries instead
5160
        // of blocking on this request which is exported as a synchronous
5161
        // request to the outside world.
5162
        go s.fundingMgr.InitFundingWorkflow(req)
×
5163

×
5164
        return req.Updates, req.Err
×
5165
}
5166

5167
// Peers returns a slice of all active peers.
5168
//
5169
// NOTE: This function is safe for concurrent access.
5170
func (s *server) Peers() []*peer.Brontide {
×
5171
        s.mu.RLock()
×
5172
        defer s.mu.RUnlock()
×
5173

×
5174
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
5175
        for _, peer := range s.peersByPub {
×
5176
                peers = append(peers, peer)
×
5177
        }
×
5178

5179
        return peers
×
5180
}
5181

5182
// computeNextBackoff uses a truncated exponential backoff to compute the next
5183
// backoff using the value of the exiting backoff. The returned duration is
5184
// randomized in either direction by 1/20 to prevent tight loops from
5185
// stabilizing.
5186
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
5187
        // Double the current backoff, truncating if it exceeds our maximum.
×
5188
        nextBackoff := 2 * currBackoff
×
5189
        if nextBackoff > maxBackoff {
×
5190
                nextBackoff = maxBackoff
×
5191
        }
×
5192

5193
        // Using 1/10 of our duration as a margin, compute a random offset to
5194
        // avoid the nodes entering connection cycles.
5195
        margin := nextBackoff / 10
×
5196

×
5197
        var wiggle big.Int
×
5198
        wiggle.SetUint64(uint64(margin))
×
5199
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5200
                // Randomizing is not mission critical, so we'll just return the
×
5201
                // current backoff.
×
5202
                return nextBackoff
×
5203
        }
×
5204

5205
        // Otherwise add in our wiggle, but subtract out half of the margin so
5206
        // that the backoff can tweaked by 1/20 in either direction.
5207
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5208
}
5209

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

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

×
5218
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
5219
        if err != nil {
×
5220
                return nil, err
×
5221
        }
×
5222

5223
        node, err := s.graphDB.FetchNode(ctx, vertex)
×
5224
        if err != nil {
×
5225
                return nil, err
×
5226
        }
×
5227

5228
        if len(node.Addresses) == 0 {
×
5229
                return nil, errNoAdvertisedAddr
×
5230
        }
×
5231

5232
        return node.Addresses, nil
×
5233
}
5234

5235
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5236
// channel update for a target channel.
5237
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5238
        *lnwire.ChannelUpdate1, error) {
×
5239

×
5240
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
5241
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
5242
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
5243
                if err != nil {
×
5244
                        return nil, err
×
5245
                }
×
5246

5247
                return netann.ExtractChannelUpdate(
×
5248
                        ourPubKey[:], info, edge1, edge2,
×
5249
                )
×
5250
        }
5251
}
5252

5253
// applyChannelUpdate applies the channel update to the different sub-systems of
5254
// the server. The useAlias boolean denotes whether or not to send an alias in
5255
// place of the real SCID.
5256
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5257
        op *wire.OutPoint, useAlias bool) error {
×
5258

×
5259
        var (
×
5260
                peerAlias    *lnwire.ShortChannelID
×
5261
                defaultAlias lnwire.ShortChannelID
×
5262
        )
×
5263

×
5264
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
5265

×
5266
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
5267
        // in the ChannelUpdate if it hasn't been announced yet.
×
5268
        if useAlias {
×
5269
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
5270
                if foundAlias != defaultAlias {
×
5271
                        peerAlias = &foundAlias
×
5272
                }
×
5273
        }
5274

5275
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
5276
                update, discovery.RemoteAlias(peerAlias),
×
5277
        )
×
5278
        select {
×
5279
        case err := <-errChan:
×
5280
                return err
×
5281
        case <-s.quit:
×
5282
                return ErrServerShuttingDown
×
5283
        }
5284
}
5285

5286
// SendCustomMessage sends a custom message to the peer with the specified
5287
// pubkey.
5288
func (s *server) SendCustomMessage(ctx context.Context, peerPub [33]byte,
5289
        msgType lnwire.MessageType, data []byte) error {
×
5290

×
5291
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5292
        if err != nil {
×
5293
                return err
×
5294
        }
×
5295

5296
        // We'll wait until the peer is active, but also listen for
5297
        // cancellation.
5298
        select {
×
5299
        case <-peer.ActiveSignal():
×
5300
        case <-peer.QuitSignal():
×
5301
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5302
        case <-s.quit:
×
5303
                return ErrServerShuttingDown
×
5304
        case <-ctx.Done():
×
5305
                return ctx.Err()
×
5306
        }
5307

5308
        msg, err := lnwire.NewCustom(msgType, data)
×
5309
        if err != nil {
×
5310
                return err
×
5311
        }
×
5312

5313
        // Send the message as low-priority. For now we assume that all
5314
        // application-defined message are low priority.
5315
        return peer.SendMessageLazy(true, msg)
×
5316
}
5317

5318
// SendOnionMessage sends a custom message to the peer with the specified
5319
// pubkey.
5320
// TODO(gijs): change this message to include path finding.
5321
func (s *server) SendOnionMessage(ctx context.Context, peerPub [33]byte,
5322
        pathKey *btcec.PublicKey, onion []byte) error {
×
5323

×
5324
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
5325
        if err != nil {
×
5326
                return err
×
5327
        }
×
5328

5329
        // We'll wait until the peer is active, but also listen for
5330
        // cancellation.
5331
        select {
×
5332
        case <-peer.ActiveSignal():
×
5333
        case <-peer.QuitSignal():
×
5334
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5335
        case <-s.quit:
×
5336
                return ErrServerShuttingDown
×
5337
        case <-ctx.Done():
×
5338
                return ctx.Err()
×
5339
        }
5340

5341
        msg := lnwire.NewOnionMessage(pathKey, onion)
×
5342

×
5343
        // Send the message as low-priority. For now we assume that all
×
5344
        // application-defined message are low priority.
×
5345
        return peer.SendMessageLazy(true, msg)
×
5346
}
5347

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

×
5356
        return func() fn.Result[lnwallet.AddrWithKey] {
×
5357
                sweepAddr, err := wallet.NewAddress(
×
5358
                        lnwallet.TaprootPubkey, false,
×
5359
                        lnwallet.DefaultAccountName,
×
5360
                )
×
5361
                if err != nil {
×
5362
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5363
                }
×
5364

5365
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
5366
                if err != nil {
×
5367
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5368
                }
×
5369

5370
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
5371
                        wallet, netParams, addr,
×
5372
                )
×
5373
                if err != nil {
×
5374
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5375
                }
×
5376

5377
                return fn.Ok(lnwallet.AddrWithKey{
×
5378
                        DeliveryAddress: addr,
×
5379
                        InternalKey:     internalKeyDesc,
×
5380
                })
×
5381
        }
5382
}
5383

5384
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5385
// finished.
5386
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
5387
        // Get a list of closed channels.
×
5388
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
5389
        if err != nil {
×
5390
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5391
                return nil
×
5392
        }
×
5393

5394
        // Save the SCIDs in a map.
5395
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
5396
        for _, c := range channels {
×
5397
                // If the channel is not pending, its FC has been finalized.
×
5398
                if !c.IsPending {
×
5399
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
5400
                }
×
5401
        }
5402

5403
        // Double check whether the reported closed channel has indeed finished
5404
        // closing.
5405
        //
5406
        // NOTE: There are misalignments regarding when a channel's FC is
5407
        // marked as finalized. We double check the pending channels to make
5408
        // sure the returned SCIDs are indeed terminated.
5409
        //
5410
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5411
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
5412
        if err != nil {
×
5413
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5414
                return nil
×
5415
        }
×
5416

5417
        for _, c := range pendings {
×
5418
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
5419
                        continue
×
5420
                }
5421

5422
                // If the channel is still reported as pending, remove it from
5423
                // the map.
5424
                delete(closedSCIDs, c.ShortChannelID)
×
5425

×
5426
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5427
                        c.ShortChannelID)
×
5428
        }
5429

5430
        return closedSCIDs
×
5431
}
5432

5433
// getStartingBeat returns the current beat. This is used during the startup to
5434
// initialize blockbeat consumers.
5435
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
5436
        // beat is the current blockbeat.
×
5437
        var beat *chainio.Beat
×
5438

×
5439
        // If the node is configured with nochainbackend mode (remote signer),
×
5440
        // we will skip fetching the best block.
×
5441
        if s.cfg.Bitcoin.Node == "nochainbackend" {
×
5442
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5443
                        "mode")
×
5444

×
5445
                return &chainio.Beat{}, nil
×
5446
        }
×
5447

5448
        // We should get a notification with the current best block immediately
5449
        // by passing a nil block.
5450
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
5451
        if err != nil {
×
5452
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5453
        }
×
5454
        defer blockEpochs.Cancel()
×
5455

×
5456
        // We registered for the block epochs with a nil request. The notifier
×
5457
        // should send us the current best block immediately. So we need to
×
5458
        // wait for it here because we need to know the current best height.
×
5459
        select {
×
5460
        case bestBlock := <-blockEpochs.Epochs:
×
5461
                srvrLog.Infof("Received initial block %v at height %d",
×
5462
                        bestBlock.Hash, bestBlock.Height)
×
5463

×
5464
                // Update the current blockbeat.
×
5465
                beat = chainio.NewBeat(*bestBlock)
×
5466

5467
        case <-s.quit:
×
5468
                srvrLog.Debug("LND shutting down")
×
5469
        }
5470

5471
        return beat, nil
×
5472
}
5473

5474
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5475
// point has an active RBF chan closer.
5476
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5477
        chanPoint wire.OutPoint) bool {
×
5478

×
5479
        pubBytes := peerPub.SerializeCompressed()
×
5480

×
5481
        s.mu.RLock()
×
5482
        targetPeer, ok := s.peersByPub[string(pubBytes)]
×
5483
        s.mu.RUnlock()
×
5484
        if !ok {
×
5485
                return false
×
5486
        }
×
5487

5488
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
×
5489
}
5490

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

×
5499
        // First, we'll attempt to look up the channel based on it's
×
5500
        // ChannelPoint.
×
5501
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
×
5502
        if err != nil {
×
5503
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5504
        }
×
5505

5506
        // From the channel, we can now get the pubkey of the peer, then use
5507
        // that to eventually get the chan closer.
5508
        peerPub := channel.IdentityPub.SerializeCompressed()
×
5509

×
5510
        // Now that we have the peer pub, we can look up the peer itself.
×
5511
        s.mu.RLock()
×
5512
        targetPeer, ok := s.peersByPub[string(peerPub)]
×
5513
        s.mu.RUnlock()
×
5514
        if !ok {
×
5515
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5516
                        "not online", chanPoint)
×
5517
        }
×
5518

5519
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
×
5520
                ctx, chanPoint, feeRate, deliveryScript,
×
5521
        )
×
5522
        if err != nil {
×
5523
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5524
                        "%w", err)
×
5525
        }
×
5526

5527
        return closeUpdates, nil
×
5528
}
5529

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

×
5538
        // If the channel is present in the switch, then the request should flow
×
5539
        // through the switch instead.
×
5540
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
5541
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
×
5542
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5543
                        "invalid request", chanPoint)
×
5544
        }
×
5545

5546
        // At this point, we know that the channel isn't present in the link, so
5547
        // we'll check to see if we have an entry in the active chan closer map.
5548
        updates, err := s.attemptCoopRbfFeeBump(
×
5549
                ctx, chanPoint, feeRate, deliveryScript,
×
5550
        )
×
5551
        if err != nil {
×
5552
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5553
                        "ChannelPoint(%v)", chanPoint)
×
5554
        }
×
5555

5556
        return updates, nil
×
5557
}
5558

5559
// setSelfNode configures and sets the server's self node. It sets the node
5560
// announcement, signs it, and updates the source node in the graph. When
5561
// determining values such as color and alias, the method prioritizes values
5562
// set in the config, then values previously persisted on disk, and finally
5563
// falls back to the defaults.
5564
func (s *server) setSelfNode(ctx context.Context, nodePub route.Vertex,
5565
        listenAddrs []net.Addr) error {
×
5566

×
5567
        // If we were requested to automatically configure port forwarding,
×
5568
        // we'll use the ports that the server will be listening on.
×
5569
        externalIPStrings := make([]string, 0, len(s.cfg.ExternalIPs))
×
5570
        for _, ip := range s.cfg.ExternalIPs {
×
5571
                externalIPStrings = append(externalIPStrings, ip.String())
×
5572
        }
×
5573
        if s.natTraversal != nil {
×
5574
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
5575
                for _, listenAddr := range listenAddrs {
×
5576
                        // At this point, the listen addresses should have
×
5577
                        // already been normalized, so it's safe to ignore the
×
5578
                        // errors.
×
5579
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
5580
                        port, _ := strconv.Atoi(portStr)
×
5581

×
5582
                        listenPorts = append(listenPorts, uint16(port))
×
5583
                }
×
5584

5585
                ips, err := s.configurePortForwarding(listenPorts...)
×
5586
                if err != nil {
×
5587
                        srvrLog.Errorf("Unable to automatically set up port "+
×
5588
                                "forwarding using %s: %v",
×
5589
                                s.natTraversal.Name(), err)
×
5590
                } else {
×
5591
                        srvrLog.Infof("Automatically set up port forwarding "+
×
5592
                                "using %s to advertise external IP",
×
5593
                                s.natTraversal.Name())
×
5594
                        externalIPStrings = append(externalIPStrings, ips...)
×
5595
                }
×
5596
        }
5597

5598
        // Normalize the external IP strings to net.Addr.
5599
        addrs, err := lncfg.NormalizeAddresses(
×
5600
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
5601
                s.cfg.net.ResolveTCPAddr,
×
5602
        )
×
5603
        if err != nil {
×
5604
                return fmt.Errorf("unable to normalize addresses: %w", err)
×
5605
        }
×
5606

5607
        // Parse the color from config. We will update this later if the config
5608
        // color is not changed from default (#3399FF) and we have a value in
5609
        // the source node.
5610
        nodeColor, err := lncfg.ParseHexColor(s.cfg.Color)
×
5611
        if err != nil {
×
5612
                return fmt.Errorf("unable to parse color: %w", err)
×
5613
        }
×
5614

5615
        var (
×
5616
                alias          = s.cfg.Alias
×
5617
                nodeLastUpdate = time.Now()
×
5618
        )
×
5619

×
5620
        srcNode, err := s.graphDB.SourceNode(ctx)
×
5621
        switch {
×
5622
        case err == nil:
×
5623
                // If we have a source node persisted in the DB already, then we
×
5624
                // just need to make sure that the new LastUpdate time is at
×
5625
                // least one second after the last update time.
×
5626
                if srcNode.LastUpdate.Second() >= nodeLastUpdate.Second() {
×
5627
                        nodeLastUpdate = srcNode.LastUpdate.Add(time.Second)
×
5628
                }
×
5629

5630
                // If the color is not changed from default, it means that we
5631
                // didn't specify a different color in the config. We'll use the
5632
                // source node's color.
5633
                if s.cfg.Color == defaultColor {
×
5634
                        srcNode.Color.WhenSome(func(rgba color.RGBA) {
×
5635
                                nodeColor = rgba
×
5636
                        })
×
5637
                }
5638

5639
                // If an alias is not specified in the config, we'll use the
5640
                // source node's alias.
5641
                if alias == "" {
×
5642
                        srcNode.Alias.WhenSome(func(s string) {
×
5643
                                alias = s
×
5644
                        })
×
5645
                }
5646

5647
                // If the `externalip` is not specified in the config, it means
5648
                // `addrs` will be empty, we'll use the source node's addresses.
5649
                if len(s.cfg.ExternalIPs) == 0 {
×
5650
                        addrs = srcNode.Addresses
×
5651
                }
×
5652

5653
        case errors.Is(err, graphdb.ErrSourceNodeNotSet):
×
5654
                // If an alias is not specified in the config, we'll use the
×
5655
                // default, which is the first 10 bytes of the serialized
×
5656
                // pubkey.
×
5657
                if alias == "" {
×
5658
                        alias = hex.EncodeToString(nodePub[:10])
×
5659
                }
×
5660

5661
        // If the above cases are not matched, then we have an unhandled non
5662
        // nil error.
5663
        default:
×
5664
                return fmt.Errorf("unable to fetch source node: %w", err)
×
5665
        }
5666

5667
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
5668
        if err != nil {
×
5669
                return err
×
5670
        }
×
5671

5672
        // TODO(abdulkbk): potentially find a way to use the source node's
5673
        // features in the self node.
5674
        selfNode := models.NewV1Node(
×
5675
                nodePub, &models.NodeV1Fields{
×
5676
                        Alias:      nodeAlias.String(),
×
5677
                        Color:      nodeColor,
×
5678
                        LastUpdate: nodeLastUpdate,
×
5679
                        Addresses:  addrs,
×
5680
                        Features:   s.featureMgr.GetRaw(feature.SetNodeAnn),
×
5681
                },
×
5682
        )
×
5683

×
5684
        // Based on the disk representation of the node announcement generated
×
5685
        // above, we'll generate a node announcement that can go out on the
×
5686
        // network so we can properly sign it.
×
5687
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
5688
        if err != nil {
×
5689
                return fmt.Errorf("unable to gen self node ann: %w", err)
×
5690
        }
×
5691

5692
        // With the announcement generated, we'll sign it to properly
5693
        // authenticate the message on the network.
5694
        authSig, err := netann.SignAnnouncement(
×
5695
                s.nodeSigner, s.identityKeyLoc, nodeAnn,
×
5696
        )
×
5697
        if err != nil {
×
5698
                return fmt.Errorf("unable to generate signature for self node "+
×
5699
                        "announcement: %v", err)
×
5700
        }
×
5701

5702
        selfNode.AuthSigBytes = authSig.Serialize()
×
5703
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
5704
                selfNode.AuthSigBytes,
×
5705
        )
×
5706
        if err != nil {
×
5707
                return err
×
5708
        }
×
5709

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

5716
        s.currentNodeAnn = nodeAnn
×
5717

×
5718
        return nil
×
5719
}
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