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

lightningnetwork / lnd / 15155511119

21 May 2025 06:52AM UTC coverage: 57.389% (-11.6%) from 68.996%
15155511119

Pull #9844

github

web-flow
Merge 8658c8597 into c52a6ddeb
Pull Request #9844: Refactor Payment PR 3

346 of 493 new or added lines in 4 files covered. (70.18%)

30172 existing lines in 456 files now uncovered.

95441 of 166305 relevant lines covered (57.39%)

0.61 hits per line

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

63.95
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

198
// peerSlotStatus determines whether a peer gets access to one of our free
199
// slots or gets to bypass this safety mechanism.
200
type peerSlotStatus struct {
201
        // state determines which privileges the peer has with our server.
202
        state peerAccessStatus
203
}
204

205
// server is the main server of the Lightning Network Daemon. The server houses
206
// global state pertaining to the wallet, database, and the rpcserver.
207
// Additionally, the server is also used as a central messaging bus to interact
208
// with any of its companion objects.
209
type server struct {
210
        active   int32 // atomic
211
        stopping int32 // atomic
212

213
        start sync.Once
214
        stop  sync.Once
215

216
        cfg *Config
217

218
        implCfg *ImplementationCfg
219

220
        // identityECDH is an ECDH capable wrapper for the private key used
221
        // to authenticate any incoming connections.
222
        identityECDH keychain.SingleKeyECDH
223

224
        // identityKeyLoc is the key locator for the above wrapped identity key.
225
        identityKeyLoc keychain.KeyLocator
226

227
        // nodeSigner is an implementation of the MessageSigner implementation
228
        // that's backed by the identity private key of the running lnd node.
229
        nodeSigner *netann.NodeSigner
230

231
        chanStatusMgr *netann.ChanStatusManager
232

233
        // listenAddrs is the list of addresses the server is currently
234
        // listening on.
235
        listenAddrs []net.Addr
236

237
        // torController is a client that will communicate with a locally
238
        // running Tor server. This client will handle initiating and
239
        // authenticating the connection to the Tor server, automatically
240
        // creating and setting up onion services, etc.
241
        torController *tor.Controller
242

243
        // natTraversal is the specific NAT traversal technique used to
244
        // automatically set up port forwarding rules in order to advertise to
245
        // the network that the node is accepting inbound connections.
246
        natTraversal nat.Traversal
247

248
        // lastDetectedIP is the last IP detected by the NAT traversal technique
249
        // above. This IP will be watched periodically in a goroutine in order
250
        // to handle dynamic IP changes.
251
        lastDetectedIP net.IP
252

253
        mu sync.RWMutex
254

255
        // peersByPub is a map of the active peers.
256
        //
257
        // NOTE: The key used here is the raw bytes of the peer's public key to
258
        // string conversion, which means it cannot be printed using `%s` as it
259
        // will just print the binary.
260
        //
261
        // TODO(yy): Use the hex string instead.
262
        peersByPub map[string]*peer.Brontide
263

264
        inboundPeers  map[string]*peer.Brontide
265
        outboundPeers map[string]*peer.Brontide
266

267
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
268
        peerDisconnectedListeners map[string][]chan<- struct{}
269

270
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
271
        // will continue to send messages even if there are no active channels
272
        // and the value below is false. Once it's pruned, all its connections
273
        // will be closed, thus the Brontide.Start will return an error.
274
        persistentPeers        map[string]bool
275
        persistentPeersBackoff map[string]time.Duration
276
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
277
        persistentConnReqs     map[string][]*connmgr.ConnReq
278
        persistentRetryCancels map[string]chan struct{}
279

280
        // peerErrors keeps a set of peer error buffers for peers that have
281
        // disconnected from us. This allows us to track historic peer errors
282
        // over connections. The string of the peer's compressed pubkey is used
283
        // as a key for this map.
284
        peerErrors map[string]*queue.CircularBuffer
285

286
        // ignorePeerTermination tracks peers for which the server has initiated
287
        // a disconnect. Adding a peer to this map causes the peer termination
288
        // watcher to short circuit in the event that peers are purposefully
289
        // disconnected.
290
        ignorePeerTermination map[*peer.Brontide]struct{}
291

292
        // scheduledPeerConnection maps a pubkey string to a callback that
293
        // should be executed in the peerTerminationWatcher the prior peer with
294
        // the same pubkey exits.  This allows the server to wait until the
295
        // prior peer has cleaned up successfully, before adding the new peer
296
        // intended to replace it.
297
        scheduledPeerConnection map[string]func()
298

299
        // pongBuf is a shared pong reply buffer we'll use across all active
300
        // peer goroutines. We know the max size of a pong message
301
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
302
        // avoid allocations each time we need to send a pong message.
303
        pongBuf []byte
304

305
        cc *chainreg.ChainControl
306

307
        fundingMgr *funding.Manager
308

309
        graphDB *graphdb.ChannelGraph
310

311
        chanStateDB *channeldb.ChannelStateDB
312

313
        addrSource channeldb.AddrSource
314

315
        // miscDB is the DB that contains all "other" databases within the main
316
        // channel DB that haven't been separated out yet.
317
        miscDB *channeldb.DB
318

319
        invoicesDB invoices.InvoiceDB
320

321
        // paymentsDB is the DB that contains all functions for managing
322
        // payments.
323
        paymentsDB pymtpkg.PaymentDB
324

325
        aliasMgr *aliasmgr.Manager
326

327
        htlcSwitch *htlcswitch.Switch
328

329
        interceptableSwitch *htlcswitch.InterceptableSwitch
330

331
        invoices *invoices.InvoiceRegistry
332

333
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
334

335
        channelNotifier *channelnotifier.ChannelNotifier
336

337
        peerNotifier *peernotifier.PeerNotifier
338

339
        htlcNotifier *htlcswitch.HtlcNotifier
340

341
        witnessBeacon contractcourt.WitnessBeacon
342

343
        breachArbitrator *contractcourt.BreachArbitrator
344

345
        missionController *routing.MissionController
346
        defaultMC         *routing.MissionControl
347

348
        graphBuilder *graph.Builder
349

350
        chanRouter *routing.ChannelRouter
351

352
        controlTower routing.ControlTower
353

354
        authGossiper *discovery.AuthenticatedGossiper
355

356
        localChanMgr *localchans.Manager
357

358
        utxoNursery *contractcourt.UtxoNursery
359

360
        sweeper *sweep.UtxoSweeper
361

362
        chainArb *contractcourt.ChainArbitrator
363

364
        sphinx *hop.OnionProcessor
365

366
        towerClientMgr *wtclient.Manager
367

368
        connMgr *connmgr.ConnManager
369

370
        sigPool *lnwallet.SigPool
371

372
        writePool *pool.Write
373

374
        readPool *pool.Read
375

376
        tlsManager *TLSManager
377

378
        // featureMgr dispatches feature vectors for various contexts within the
379
        // daemon.
380
        featureMgr *feature.Manager
381

382
        // currentNodeAnn is the node announcement that has been broadcast to
383
        // the network upon startup, if the attributes of the node (us) has
384
        // changed since last start.
385
        currentNodeAnn *lnwire.NodeAnnouncement
386

387
        // chansToRestore is the set of channels that upon starting, the server
388
        // should attempt to restore/recover.
389
        chansToRestore walletunlocker.ChannelsToRecover
390

391
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
392
        // backups are consistent at all times. It interacts with the
393
        // channelNotifier to be notified of newly opened and closed channels.
394
        chanSubSwapper *chanbackup.SubSwapper
395

396
        // chanEventStore tracks the behaviour of channels and their remote peers to
397
        // provide insights into their health and performance.
398
        chanEventStore *chanfitness.ChannelEventStore
399

400
        hostAnn *netann.HostAnnouncer
401

402
        // livenessMonitor monitors that lnd has access to critical resources.
403
        livenessMonitor *healthcheck.Monitor
404

405
        customMessageServer *subscribe.Server
406

407
        // txPublisher is a publisher with fee-bumping capability.
408
        txPublisher *sweep.TxPublisher
409

410
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
411
        // of new blocks.
412
        blockbeatDispatcher *chainio.BlockbeatDispatcher
413

414
        // peerAccessMan implements peer access controls.
415
        peerAccessMan *accessMan
416

417
        quit chan struct{}
418

419
        wg sync.WaitGroup
420
}
421

422
// updatePersistentPeerAddrs subscribes to topology changes and stores
423
// advertised addresses for any NodeAnnouncements from our persisted peers.
424
func (s *server) updatePersistentPeerAddrs() error {
1✔
425
        graphSub, err := s.graphDB.SubscribeTopology()
1✔
426
        if err != nil {
1✔
427
                return err
×
428
        }
×
429

430
        s.wg.Add(1)
1✔
431
        go func() {
2✔
432
                defer func() {
2✔
433
                        graphSub.Cancel()
1✔
434
                        s.wg.Done()
1✔
435
                }()
1✔
436

437
                for {
2✔
438
                        select {
1✔
439
                        case <-s.quit:
1✔
440
                                return
1✔
441

442
                        case topChange, ok := <-graphSub.TopologyChanges:
1✔
443
                                // If the router is shutting down, then we will
1✔
444
                                // as well.
1✔
445
                                if !ok {
1✔
446
                                        return
×
447
                                }
×
448

449
                                for _, update := range topChange.NodeUpdates {
2✔
450
                                        pubKeyStr := string(
1✔
451
                                                update.IdentityKey.
1✔
452
                                                        SerializeCompressed(),
1✔
453
                                        )
1✔
454

1✔
455
                                        // We only care about updates from
1✔
456
                                        // our persistentPeers.
1✔
457
                                        s.mu.RLock()
1✔
458
                                        _, ok := s.persistentPeers[pubKeyStr]
1✔
459
                                        s.mu.RUnlock()
1✔
460
                                        if !ok {
2✔
461
                                                continue
1✔
462
                                        }
463

464
                                        addrs := make([]*lnwire.NetAddress, 0,
1✔
465
                                                len(update.Addresses))
1✔
466

1✔
467
                                        for _, addr := range update.Addresses {
2✔
468
                                                addrs = append(addrs,
1✔
469
                                                        &lnwire.NetAddress{
1✔
470
                                                                IdentityKey: update.IdentityKey,
1✔
471
                                                                Address:     addr,
1✔
472
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
473
                                                        },
1✔
474
                                                )
1✔
475
                                        }
1✔
476

477
                                        s.mu.Lock()
1✔
478

1✔
479
                                        // Update the stored addresses for this
1✔
480
                                        // to peer to reflect the new set.
1✔
481
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
1✔
482

1✔
483
                                        // If there are no outstanding
1✔
484
                                        // connection requests for this peer
1✔
485
                                        // then our work is done since we are
1✔
486
                                        // not currently trying to connect to
1✔
487
                                        // them.
1✔
488
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
2✔
489
                                                s.mu.Unlock()
1✔
490
                                                continue
1✔
491
                                        }
492

493
                                        s.mu.Unlock()
1✔
494

1✔
495
                                        s.connectToPersistentPeer(pubKeyStr)
1✔
496
                                }
497
                        }
498
                }
499
        }()
500

501
        return nil
1✔
502
}
503

504
// CustomMessage is a custom message that is received from a peer.
505
type CustomMessage struct {
506
        // Peer is the peer pubkey
507
        Peer [33]byte
508

509
        // Msg is the custom wire message.
510
        Msg *lnwire.Custom
511
}
512

513
// parseAddr parses an address from its string format to a net.Addr.
514
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
1✔
515
        var (
1✔
516
                host string
1✔
517
                port int
1✔
518
        )
1✔
519

1✔
520
        // Split the address into its host and port components.
1✔
521
        h, p, err := net.SplitHostPort(address)
1✔
522
        if err != nil {
1✔
523
                // If a port wasn't specified, we'll assume the address only
×
524
                // contains the host so we'll use the default port.
×
525
                host = address
×
526
                port = defaultPeerPort
×
527
        } else {
1✔
528
                // Otherwise, we'll note both the host and ports.
1✔
529
                host = h
1✔
530
                portNum, err := strconv.Atoi(p)
1✔
531
                if err != nil {
1✔
532
                        return nil, err
×
533
                }
×
534
                port = portNum
1✔
535
        }
536

537
        if tor.IsOnionHost(host) {
1✔
538
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
539
        }
×
540

541
        // If the host is part of a TCP address, we'll use the network
542
        // specific ResolveTCPAddr function in order to resolve these
543
        // addresses over Tor in order to prevent leaking your real IP
544
        // address.
545
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
1✔
546
        return netCfg.ResolveTCPAddr("tcp", hostPort)
1✔
547
}
548

549
// noiseDial is a factory function which creates a connmgr compliant dialing
550
// function by returning a closure which includes the server's identity key.
551
func noiseDial(idKey keychain.SingleKeyECDH,
552
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
1✔
553

1✔
554
        return func(a net.Addr) (net.Conn, error) {
2✔
555
                lnAddr := a.(*lnwire.NetAddress)
1✔
556
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
1✔
557
        }
1✔
558
}
559

560
// newServer creates a new instance of the server which is to listen using the
561
// passed listener address.
562
func newServer(cfg *Config, listenAddrs []net.Addr,
563
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
564
        nodeKeyDesc *keychain.KeyDescriptor,
565
        chansToRestore walletunlocker.ChannelsToRecover,
566
        chanPredicate chanacceptor.ChannelAcceptor,
567
        torController *tor.Controller, tlsManager *TLSManager,
568
        leaderElector cluster.LeaderElector,
569
        implCfg *ImplementationCfg) (*server, error) {
1✔
570

1✔
571
        var (
1✔
572
                err         error
1✔
573
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
1✔
574

1✔
575
                // We just derived the full descriptor, so we know the public
1✔
576
                // key is set on it.
1✔
577
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
1✔
578
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
1✔
579
                )
1✔
580
        )
1✔
581

1✔
582
        var serializedPubKey [33]byte
1✔
583
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
584

1✔
585
        netParams := cfg.ActiveNetParams.Params
1✔
586

1✔
587
        // Initialize the sphinx router.
1✔
588
        replayLog := htlcswitch.NewDecayedLog(
1✔
589
                dbs.DecayedLogDB, cc.ChainNotifier,
1✔
590
        )
1✔
591
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
1✔
592

1✔
593
        writeBufferPool := pool.NewWriteBuffer(
1✔
594
                pool.DefaultWriteBufferGCInterval,
1✔
595
                pool.DefaultWriteBufferExpiryInterval,
1✔
596
        )
1✔
597

1✔
598
        writePool := pool.NewWrite(
1✔
599
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
1✔
600
        )
1✔
601

1✔
602
        readBufferPool := pool.NewReadBuffer(
1✔
603
                pool.DefaultReadBufferGCInterval,
1✔
604
                pool.DefaultReadBufferExpiryInterval,
1✔
605
        )
1✔
606

1✔
607
        readPool := pool.NewRead(
1✔
608
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
1✔
609
        )
1✔
610

1✔
611
        // If the taproot overlay flag is set, but we don't have an aux funding
1✔
612
        // controller, then we'll exit as this is incompatible.
1✔
613
        if cfg.ProtocolOptions.TaprootOverlayChans &&
1✔
614
                implCfg.AuxFundingController.IsNone() {
1✔
615

×
616
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
617
                        "aux controllers")
×
618
        }
×
619

620
        //nolint:ll
621
        featureMgr, err := feature.NewManager(feature.Config{
1✔
622
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
1✔
623
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
1✔
624
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
1✔
625
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
1✔
626
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
1✔
627
                NoKeysend:                 !cfg.AcceptKeySend,
1✔
628
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
1✔
629
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
1✔
630
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
1✔
631
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
1✔
632
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
1✔
633
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
1✔
634
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
1✔
635
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
1✔
636
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
1✔
637
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
1✔
638
        })
1✔
639
        if err != nil {
1✔
640
                return nil, err
×
641
        }
×
642

643
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
1✔
644
        registryConfig := invoices.RegistryConfig{
1✔
645
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
1✔
646
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
1✔
647
                Clock:                       clock.NewDefaultClock(),
1✔
648
                AcceptKeySend:               cfg.AcceptKeySend,
1✔
649
                AcceptAMP:                   cfg.AcceptAMP,
1✔
650
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
1✔
651
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
1✔
652
                KeysendHoldTime:             cfg.KeysendHoldTime,
1✔
653
                HtlcInterceptor:             invoiceHtlcModifier,
1✔
654
        }
1✔
655

1✔
656
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
1✔
657

1✔
658
        s := &server{
1✔
659
                cfg:            cfg,
1✔
660
                implCfg:        implCfg,
1✔
661
                graphDB:        dbs.GraphDB,
1✔
662
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
1✔
663
                addrSource:     addrSource,
1✔
664
                miscDB:         dbs.ChanStateDB,
1✔
665
                invoicesDB:     dbs.InvoiceDB,
1✔
666
                paymentsDB:     dbs.PaymentDB,
1✔
667
                cc:             cc,
1✔
668
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
1✔
669
                writePool:      writePool,
1✔
670
                readPool:       readPool,
1✔
671
                chansToRestore: chansToRestore,
1✔
672

1✔
673
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
1✔
674
                        cc.ChainNotifier,
1✔
675
                ),
1✔
676
                channelNotifier: channelnotifier.New(
1✔
677
                        dbs.ChanStateDB.ChannelStateDB(),
1✔
678
                ),
1✔
679

1✔
680
                identityECDH:   nodeKeyECDH,
1✔
681
                identityKeyLoc: nodeKeyDesc.KeyLocator,
1✔
682
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
1✔
683

1✔
684
                listenAddrs: listenAddrs,
1✔
685

1✔
686
                // TODO(roasbeef): derive proper onion key based on rotation
1✔
687
                // schedule
1✔
688
                sphinx: hop.NewOnionProcessor(sphinxRouter),
1✔
689

1✔
690
                torController: torController,
1✔
691

1✔
692
                persistentPeers:         make(map[string]bool),
1✔
693
                persistentPeersBackoff:  make(map[string]time.Duration),
1✔
694
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
1✔
695
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
1✔
696
                persistentRetryCancels:  make(map[string]chan struct{}),
1✔
697
                peerErrors:              make(map[string]*queue.CircularBuffer),
1✔
698
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
1✔
699
                scheduledPeerConnection: make(map[string]func()),
1✔
700
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
1✔
701

1✔
702
                peersByPub:                make(map[string]*peer.Brontide),
1✔
703
                inboundPeers:              make(map[string]*peer.Brontide),
1✔
704
                outboundPeers:             make(map[string]*peer.Brontide),
1✔
705
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
1✔
706
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
1✔
707

1✔
708
                invoiceHtlcModifier: invoiceHtlcModifier,
1✔
709

1✔
710
                customMessageServer: subscribe.NewServer(),
1✔
711

1✔
712
                tlsManager: tlsManager,
1✔
713

1✔
714
                featureMgr: featureMgr,
1✔
715
                quit:       make(chan struct{}),
1✔
716
        }
1✔
717

1✔
718
        // Start the low-level services once they are initialized.
1✔
719
        //
1✔
720
        // TODO(yy): break the server startup into four steps,
1✔
721
        // 1. init the low-level services.
1✔
722
        // 2. start the low-level services.
1✔
723
        // 3. init the high-level services.
1✔
724
        // 4. start the high-level services.
1✔
725
        if err := s.startLowLevelServices(); err != nil {
1✔
726
                return nil, err
×
727
        }
×
728

729
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
1✔
730
        if err != nil {
1✔
731
                return nil, err
×
732
        }
×
733

734
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
1✔
735
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
1✔
736
                uint32(currentHeight), currentHash, cc.ChainNotifier,
1✔
737
        )
1✔
738
        s.invoices = invoices.NewRegistry(
1✔
739
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
1✔
740
        )
1✔
741

1✔
742
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
1✔
743

1✔
744
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
1✔
745
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
1✔
746

1✔
747
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
2✔
748
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
1✔
749
                if err != nil {
1✔
750
                        return err
×
751
                }
×
752

753
                s.htlcSwitch.UpdateLinkAliases(link)
1✔
754

1✔
755
                return nil
1✔
756
        }
757

758
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
1✔
759
        if err != nil {
1✔
760
                return nil, err
×
761
        }
×
762

763
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
1✔
764
                DB:                   dbs.ChanStateDB,
1✔
765
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1✔
766
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
1✔
767
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
1✔
768
                LocalChannelClose: func(pubKey []byte,
1✔
769
                        request *htlcswitch.ChanClose) {
2✔
770

1✔
771
                        peer, err := s.FindPeerByPubStr(string(pubKey))
1✔
772
                        if err != nil {
1✔
773
                                srvrLog.Errorf("unable to close channel, peer"+
×
774
                                        " with %v id can't be found: %v",
×
775
                                        pubKey, err,
×
776
                                )
×
777
                                return
×
778
                        }
×
779

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

815
        s.witnessBeacon = newPreimageBeacon(
1✔
816
                dbs.ChanStateDB.NewWitnessCache(),
1✔
817
                s.interceptableSwitch.ForwardPacket,
1✔
818
        )
1✔
819

1✔
820
        chanStatusMgrCfg := &netann.ChanStatusConfig{
1✔
821
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
1✔
822
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
1✔
823
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
1✔
824
                OurPubKey:                nodeKeyDesc.PubKey,
1✔
825
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
1✔
826
                MessageSigner:            s.nodeSigner,
1✔
827
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
1✔
828
                ApplyChannelUpdate:       s.applyChannelUpdate,
1✔
829
                DB:                       s.chanStateDB,
1✔
830
                Graph:                    dbs.GraphDB,
1✔
831
        }
1✔
832

1✔
833
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
1✔
834
        if err != nil {
1✔
835
                return nil, err
×
836
        }
×
837
        s.chanStatusMgr = chanStatusMgr
1✔
838

1✔
839
        // If enabled, use either UPnP or NAT-PMP to automatically configure
1✔
840
        // port forwarding for users behind a NAT.
1✔
841
        if cfg.NAT {
1✔
842
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
843

×
844
                discoveryTimeout := time.Duration(10 * time.Second)
×
845

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

×
860
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
861
                                "enabled device")
×
862

×
863
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
864
                        if err != nil {
×
865
                                err := fmt.Errorf("unable to discover a "+
×
866
                                        "NAT-PMP enabled device on the local "+
×
867
                                        "network: %v", err)
×
868
                                srvrLog.Error(err)
×
869
                                return nil, err
×
870
                        }
×
871

872
                        s.natTraversal = pmp
×
873
                }
874
        }
875

876
        // If we were requested to automatically configure port forwarding,
877
        // we'll use the ports that the server will be listening on.
878
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
1✔
879
        for idx, ip := range cfg.ExternalIPs {
2✔
880
                externalIPStrings[idx] = ip.String()
1✔
881
        }
1✔
882
        if s.natTraversal != nil {
1✔
883
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
884
                for _, listenAddr := range listenAddrs {
×
885
                        // At this point, the listen addresses should have
×
886
                        // already been normalized, so it's safe to ignore the
×
887
                        // errors.
×
888
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
889
                        port, _ := strconv.Atoi(portStr)
×
890

×
891
                        listenPorts = append(listenPorts, uint16(port))
×
892
                }
×
893

894
                ips, err := s.configurePortForwarding(listenPorts...)
×
895
                if err != nil {
×
896
                        srvrLog.Errorf("Unable to automatically set up port "+
×
897
                                "forwarding using %s: %v",
×
898
                                s.natTraversal.Name(), err)
×
899
                } else {
×
900
                        srvrLog.Infof("Automatically set up port forwarding "+
×
901
                                "using %s to advertise external IP",
×
902
                                s.natTraversal.Name())
×
903
                        externalIPStrings = append(externalIPStrings, ips...)
×
904
                }
×
905
        }
906

907
        // If external IP addresses have been specified, add those to the list
908
        // of this server's addresses.
909
        externalIPs, err := lncfg.NormalizeAddresses(
1✔
910
                externalIPStrings, strconv.Itoa(defaultPeerPort),
1✔
911
                cfg.net.ResolveTCPAddr,
1✔
912
        )
1✔
913
        if err != nil {
1✔
914
                return nil, err
×
915
        }
×
916

917
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
1✔
918
        selfAddrs = append(selfAddrs, externalIPs...)
1✔
919

1✔
920
        // We'll now reconstruct a node announcement based on our current
1✔
921
        // configuration so we can send it out as a sort of heart beat within
1✔
922
        // the network.
1✔
923
        //
1✔
924
        // We'll start by parsing the node color from configuration.
1✔
925
        color, err := lncfg.ParseHexColor(cfg.Color)
1✔
926
        if err != nil {
1✔
927
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
928
                return nil, err
×
929
        }
×
930

931
        // If no alias is provided, default to first 10 characters of public
932
        // key.
933
        alias := cfg.Alias
1✔
934
        if alias == "" {
2✔
935
                alias = hex.EncodeToString(serializedPubKey[:10])
1✔
936
        }
1✔
937
        nodeAlias, err := lnwire.NewNodeAlias(alias)
1✔
938
        if err != nil {
1✔
939
                return nil, err
×
940
        }
×
941
        selfNode := &models.LightningNode{
1✔
942
                HaveNodeAnnouncement: true,
1✔
943
                LastUpdate:           time.Now(),
1✔
944
                Addresses:            selfAddrs,
1✔
945
                Alias:                nodeAlias.String(),
1✔
946
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
1✔
947
                Color:                color,
1✔
948
        }
1✔
949
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
950

1✔
951
        // Based on the disk representation of the node announcement generated
1✔
952
        // above, we'll generate a node announcement that can go out on the
1✔
953
        // network so we can properly sign it.
1✔
954
        nodeAnn, err := selfNode.NodeAnnouncement(false)
1✔
955
        if err != nil {
1✔
956
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
957
        }
×
958

959
        // With the announcement generated, we'll sign it to properly
960
        // authenticate the message on the network.
961
        authSig, err := netann.SignAnnouncement(
1✔
962
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
1✔
963
        )
1✔
964
        if err != nil {
1✔
965
                return nil, fmt.Errorf("unable to generate signature for "+
×
966
                        "self node announcement: %v", err)
×
967
        }
×
968
        selfNode.AuthSigBytes = authSig.Serialize()
1✔
969
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
1✔
970
                selfNode.AuthSigBytes,
1✔
971
        )
1✔
972
        if err != nil {
1✔
973
                return nil, err
×
974
        }
×
975

976
        // Finally, we'll update the representation on disk, and update our
977
        // cached in-memory version as well.
978
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
1✔
979
                return nil, fmt.Errorf("can't set self node: %w", err)
×
980
        }
×
981
        s.currentNodeAnn = nodeAnn
1✔
982

1✔
983
        // The router will get access to the payment ID sequencer, such that it
1✔
984
        // can generate unique payment IDs.
1✔
985
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
1✔
986
        if err != nil {
1✔
987
                return nil, err
×
988
        }
×
989

990
        // Instantiate mission control with config from the sub server.
991
        //
992
        // TODO(joostjager): When we are further in the process of moving to sub
993
        // servers, the mission control instance itself can be moved there too.
994
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
1✔
995

1✔
996
        // We only initialize a probability estimator if there's no custom one.
1✔
997
        var estimator routing.Estimator
1✔
998
        if cfg.Estimator != nil {
1✔
999
                estimator = cfg.Estimator
×
1000
        } else {
1✔
1001
                switch routingConfig.ProbabilityEstimatorType {
1✔
1002
                case routing.AprioriEstimatorName:
1✔
1003
                        aCfg := routingConfig.AprioriConfig
1✔
1004
                        aprioriConfig := routing.AprioriConfig{
1✔
1005
                                AprioriHopProbability: aCfg.HopProbability,
1✔
1006
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
1✔
1007
                                AprioriWeight:         aCfg.Weight,
1✔
1008
                                CapacityFraction:      aCfg.CapacityFraction,
1✔
1009
                        }
1✔
1010

1✔
1011
                        estimator, err = routing.NewAprioriEstimator(
1✔
1012
                                aprioriConfig,
1✔
1013
                        )
1✔
1014
                        if err != nil {
1✔
1015
                                return nil, err
×
1016
                        }
×
1017

1018
                case routing.BimodalEstimatorName:
×
1019
                        bCfg := routingConfig.BimodalConfig
×
1020
                        bimodalConfig := routing.BimodalConfig{
×
1021
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1022
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1023
                                        bCfg.Scale,
×
1024
                                ),
×
1025
                                BimodalDecayTime: bCfg.DecayTime,
×
1026
                        }
×
1027

×
1028
                        estimator, err = routing.NewBimodalEstimator(
×
1029
                                bimodalConfig,
×
1030
                        )
×
1031
                        if err != nil {
×
1032
                                return nil, err
×
1033
                        }
×
1034

1035
                default:
×
1036
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1037
                                routingConfig.ProbabilityEstimatorType)
×
1038
                }
1039
        }
1040

1041
        mcCfg := &routing.MissionControlConfig{
1✔
1042
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
1✔
1043
                Estimator:               estimator,
1✔
1044
                MaxMcHistory:            routingConfig.MaxMcHistory,
1✔
1045
                McFlushInterval:         routingConfig.McFlushInterval,
1✔
1046
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
1✔
1047
        }
1✔
1048

1✔
1049
        s.missionController, err = routing.NewMissionController(
1✔
1050
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
1✔
1051
        )
1✔
1052
        if err != nil {
1✔
1053
                return nil, fmt.Errorf("can't create mission control "+
×
1054
                        "manager: %w", err)
×
1055
        }
×
1056
        s.defaultMC, err = s.missionController.GetNamespacedStore(
1✔
1057
                routing.DefaultMissionControlNamespace,
1✔
1058
        )
1✔
1059
        if err != nil {
1✔
1060
                return nil, fmt.Errorf("can't create mission control in the "+
×
1061
                        "default namespace: %w", err)
×
1062
        }
×
1063

1064
        srvrLog.Debugf("Instantiating payment session source with config: "+
1✔
1065
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
1✔
1066
                int64(routingConfig.AttemptCost),
1✔
1067
                float64(routingConfig.AttemptCostPPM)/10000,
1✔
1068
                routingConfig.MinRouteProbability)
1✔
1069

1✔
1070
        pathFindingConfig := routing.PathFindingConfig{
1✔
1071
                AttemptCost: lnwire.NewMSatFromSatoshis(
1✔
1072
                        routingConfig.AttemptCost,
1✔
1073
                ),
1✔
1074
                AttemptCostPPM: routingConfig.AttemptCostPPM,
1✔
1075
                MinProbability: routingConfig.MinRouteProbability,
1✔
1076
        }
1✔
1077

1✔
1078
        sourceNode, err := dbs.GraphDB.SourceNode()
1✔
1079
        if err != nil {
1✔
1080
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1081
        }
×
1082
        paymentSessionSource := &routing.SessionSource{
1✔
1083
                GraphSessionFactory: dbs.GraphDB,
1✔
1084
                SourceNode:          sourceNode,
1✔
1085
                MissionControl:      s.defaultMC,
1✔
1086
                GetLink:             s.htlcSwitch.GetLinkByShortID,
1✔
1087
                PathFindingConfig:   pathFindingConfig,
1✔
1088
        }
1✔
1089

1✔
1090
        s.controlTower = routing.NewControlTower(dbs.PaymentDB)
1✔
1091

1✔
1092
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
1✔
1093
                cfg.Routing.StrictZombiePruning
1✔
1094

1✔
1095
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
1✔
1096
                SelfNode:            selfNode.PubKeyBytes,
1✔
1097
                Graph:               dbs.GraphDB,
1✔
1098
                Chain:               cc.ChainIO,
1✔
1099
                ChainView:           cc.ChainView,
1✔
1100
                Notifier:            cc.ChainNotifier,
1✔
1101
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
1✔
1102
                GraphPruneInterval:  time.Hour,
1✔
1103
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
1✔
1104
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
1✔
1105
                StrictZombiePruning: strictPruning,
1✔
1106
                IsAlias:             aliasmgr.IsAlias,
1✔
1107
        })
1✔
1108
        if err != nil {
1✔
1109
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1110
        }
×
1111

1112
        s.chanRouter, err = routing.New(routing.Config{
1✔
1113
                SelfNode:           selfNode.PubKeyBytes,
1✔
1114
                RoutingGraph:       dbs.GraphDB,
1✔
1115
                Chain:              cc.ChainIO,
1✔
1116
                Payer:              s.htlcSwitch,
1✔
1117
                Control:            s.controlTower,
1✔
1118
                MissionControl:     s.defaultMC,
1✔
1119
                SessionSource:      paymentSessionSource,
1✔
1120
                GetLink:            s.htlcSwitch.GetLinkByShortID,
1✔
1121
                NextPaymentID:      sequencer.NextID,
1✔
1122
                PathFindingConfig:  pathFindingConfig,
1✔
1123
                Clock:              clock.NewDefaultClock(),
1✔
1124
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
1✔
1125
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
1✔
1126
                TrafficShaper:      implCfg.TrafficShaper,
1✔
1127
        })
1✔
1128
        if err != nil {
1✔
1129
                return nil, fmt.Errorf("can't create router: %w", err)
×
1130
        }
×
1131

1132
        chanSeries := discovery.NewChanSeries(s.graphDB)
1✔
1133
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
1✔
1134
        if err != nil {
1✔
1135
                return nil, err
×
1136
        }
×
1137
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
1✔
1138
        if err != nil {
1✔
1139
                return nil, err
×
1140
        }
×
1141

1142
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
1✔
1143

1✔
1144
        s.authGossiper = discovery.New(discovery.Config{
1✔
1145
                Graph:                 s.graphBuilder,
1✔
1146
                ChainIO:               s.cc.ChainIO,
1✔
1147
                Notifier:              s.cc.ChainNotifier,
1✔
1148
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
1✔
1149
                Broadcast:             s.BroadcastMessage,
1✔
1150
                ChanSeries:            chanSeries,
1✔
1151
                NotifyWhenOnline:      s.NotifyWhenOnline,
1✔
1152
                NotifyWhenOffline:     s.NotifyWhenOffline,
1✔
1153
                FetchSelfAnnouncement: s.getNodeAnnouncement,
1✔
1154
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
1✔
1155
                        error) {
1✔
1156

×
1157
                        return s.genNodeAnnouncement(nil)
×
1158
                },
×
1159
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1160
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1161
                RetransmitTicker:        ticker.New(time.Minute * 30),
1162
                RebroadcastInterval:     time.Hour * 24,
1163
                WaitingProofStore:       waitingProofStore,
1164
                MessageStore:            gossipMessageStore,
1165
                AnnSigner:               s.nodeSigner,
1166
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1167
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1168
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1169
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1170
                MinimumBatchSize:        10,
1171
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1172
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1173
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1174
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1175
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1176
                IsAlias:                 aliasmgr.IsAlias,
1177
                SignAliasUpdate:         s.signAliasUpdate,
1178
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1179
                GetAlias:                s.aliasMgr.GetPeerAlias,
1180
                FindChannel:             s.findChannel,
1181
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1182
                ScidCloser:              scidCloserMan,
1183
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1184
                MsgRateBytes:            cfg.Gossip.MsgRateBytes,
1185
                MsgBurstBytes:           cfg.Gossip.MsgBurstBytes,
1186
        }, nodeKeyDesc)
1187

1188
        accessCfg := &accessManConfig{
1✔
1189
                initAccessPerms: func() (map[string]channeldb.ChanCount,
1✔
1190
                        error) {
2✔
1191

1✔
1192
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
1✔
1193
                        return s.chanStateDB.FetchPermAndTempPeers(
1✔
1194
                                genesisHash[:],
1✔
1195
                        )
1✔
1196
                },
1✔
1197
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1198
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1199
        }
1200

1201
        peerAccessMan, err := newAccessMan(accessCfg)
1✔
1202
        if err != nil {
1✔
1203
                return nil, err
×
1204
        }
×
1205

1206
        s.peerAccessMan = peerAccessMan
1✔
1207

1✔
1208
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
1✔
1209
        //nolint:ll
1✔
1210
        s.localChanMgr = &localchans.Manager{
1✔
1211
                SelfPub:              nodeKeyDesc.PubKey,
1✔
1212
                DefaultRoutingPolicy: cc.RoutingPolicy,
1✔
1213
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
1✔
1214
                        *models.ChannelEdgePolicy) error) error {
2✔
1215

1✔
1216
                        return s.graphDB.ForEachNodeChannel(selfVertex,
1✔
1217
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
1✔
1218
                                        e *models.ChannelEdgePolicy,
1✔
1219
                                        _ *models.ChannelEdgePolicy) error {
2✔
1220

1✔
1221
                                        // NOTE: The invoked callback here may
1✔
1222
                                        // receive a nil channel policy.
1✔
1223
                                        return cb(c, e)
1✔
1224
                                },
1✔
1225
                        )
1226
                },
1227
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1228
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1229
                FetchChannel:              s.chanStateDB.FetchChannel,
1230
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1231
                        return s.graphBuilder.AddEdge(edge)
×
1232
                },
×
1233
        }
1234

1235
        utxnStore, err := contractcourt.NewNurseryStore(
1✔
1236
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
1✔
1237
        )
1✔
1238
        if err != nil {
1✔
1239
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1240
                return nil, err
×
1241
        }
×
1242

1243
        sweeperStore, err := sweep.NewSweeperStore(
1✔
1244
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
1✔
1245
        )
1✔
1246
        if err != nil {
1✔
1247
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1248
                return nil, err
×
1249
        }
×
1250

1251
        aggregator := sweep.NewBudgetAggregator(
1✔
1252
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
1✔
1253
                s.implCfg.AuxSweeper,
1✔
1254
        )
1✔
1255

1✔
1256
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
1✔
1257
                Signer:     cc.Wallet.Cfg.Signer,
1✔
1258
                Wallet:     cc.Wallet,
1✔
1259
                Estimator:  cc.FeeEstimator,
1✔
1260
                Notifier:   cc.ChainNotifier,
1✔
1261
                AuxSweeper: s.implCfg.AuxSweeper,
1✔
1262
        })
1✔
1263

1✔
1264
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
1✔
1265
                FeeEstimator: cc.FeeEstimator,
1✔
1266
                GenSweepScript: newSweepPkScriptGen(
1✔
1267
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
1✔
1268
                ),
1✔
1269
                Signer:               cc.Wallet.Cfg.Signer,
1✔
1270
                Wallet:               newSweeperWallet(cc.Wallet),
1✔
1271
                Mempool:              cc.MempoolNotifier,
1✔
1272
                Notifier:             cc.ChainNotifier,
1✔
1273
                Store:                sweeperStore,
1✔
1274
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
1✔
1275
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
1✔
1276
                Aggregator:           aggregator,
1✔
1277
                Publisher:            s.txPublisher,
1✔
1278
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
1✔
1279
        })
1✔
1280

1✔
1281
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
1✔
1282
                ChainIO:             cc.ChainIO,
1✔
1283
                ConfDepth:           1,
1✔
1284
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
1✔
1285
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
1✔
1286
                Notifier:            cc.ChainNotifier,
1✔
1287
                PublishTransaction:  cc.Wallet.PublishTransaction,
1✔
1288
                Store:               utxnStore,
1✔
1289
                SweepInput:          s.sweeper.SweepInput,
1✔
1290
                Budget:              s.cfg.Sweeper.Budget,
1✔
1291
        })
1✔
1292

1✔
1293
        // Construct a closure that wraps the htlcswitch's CloseLink method.
1✔
1294
        closeLink := func(chanPoint *wire.OutPoint,
1✔
1295
                closureType contractcourt.ChannelCloseType) {
2✔
1296
                // TODO(conner): Properly respect the update and error channels
1✔
1297
                // returned by CloseLink.
1✔
1298

1✔
1299
                // Instruct the switch to close the channel.  Provide no close out
1✔
1300
                // delivery script or target fee per kw because user input is not
1✔
1301
                // available when the remote peer closes the channel.
1✔
1302
                s.htlcSwitch.CloseLink(
1✔
1303
                        context.Background(), chanPoint, closureType, 0, 0, nil,
1✔
1304
                )
1✔
1305
        }
1✔
1306

1307
        // We will use the following channel to reliably hand off contract
1308
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1309
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
1✔
1310

1✔
1311
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
1✔
1312
                &contractcourt.BreachConfig{
1✔
1313
                        CloseLink: closeLink,
1✔
1314
                        DB:        s.chanStateDB,
1✔
1315
                        Estimator: s.cc.FeeEstimator,
1✔
1316
                        GenSweepScript: newSweepPkScriptGen(
1✔
1317
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
1✔
1318
                        ),
1✔
1319
                        Notifier:           cc.ChainNotifier,
1✔
1320
                        PublishTransaction: cc.Wallet.PublishTransaction,
1✔
1321
                        ContractBreaches:   contractBreaches,
1✔
1322
                        Signer:             cc.Wallet.Cfg.Signer,
1✔
1323
                        Store: contractcourt.NewRetributionStore(
1✔
1324
                                dbs.ChanStateDB,
1✔
1325
                        ),
1✔
1326
                        AuxSweeper: s.implCfg.AuxSweeper,
1✔
1327
                },
1✔
1328
        )
1✔
1329

1✔
1330
        //nolint:ll
1✔
1331
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
1✔
1332
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
1✔
1333
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
1✔
1334
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
1✔
1335
                NewSweepAddr: func() ([]byte, error) {
1✔
1336
                        addr, err := newSweepPkScriptGen(
×
1337
                                cc.Wallet, netParams,
×
1338
                        )().Unpack()
×
1339
                        if err != nil {
×
1340
                                return nil, err
×
1341
                        }
×
1342

1343
                        return addr.DeliveryAddress, nil
×
1344
                },
1345
                PublishTx: cc.Wallet.PublishTransaction,
1346
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
1✔
1347
                        for _, msg := range msgs {
2✔
1348
                                err := s.htlcSwitch.ProcessContractResolution(msg)
1✔
1349
                                if err != nil {
1✔
1350
                                        return err
×
1351
                                }
×
1352
                        }
1353
                        return nil
1✔
1354
                },
1355
                IncubateOutputs: func(chanPoint wire.OutPoint,
1356
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1357
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1358
                        broadcastHeight uint32,
1359
                        deadlineHeight fn.Option[int32]) error {
1✔
1360

1✔
1361
                        return s.utxoNursery.IncubateOutputs(
1✔
1362
                                chanPoint, outHtlcRes, inHtlcRes,
1✔
1363
                                broadcastHeight, deadlineHeight,
1✔
1364
                        )
1✔
1365
                },
1✔
1366
                PreimageDB:   s.witnessBeacon,
1367
                Notifier:     cc.ChainNotifier,
1368
                Mempool:      cc.MempoolNotifier,
1369
                Signer:       cc.Wallet.Cfg.Signer,
1370
                FeeEstimator: cc.FeeEstimator,
1371
                ChainIO:      cc.ChainIO,
1372
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
1✔
1373
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
1374
                        s.htlcSwitch.RemoveLink(chanID)
1✔
1375
                        return nil
1✔
1376
                },
1✔
1377
                IsOurAddress: cc.Wallet.IsOurAddress,
1378
                ContractBreach: func(chanPoint wire.OutPoint,
1379
                        breachRet *lnwallet.BreachRetribution) error {
1✔
1380

1✔
1381
                        // processACK will handle the BreachArbitrator ACKing
1✔
1382
                        // the event.
1✔
1383
                        finalErr := make(chan error, 1)
1✔
1384
                        processACK := func(brarErr error) {
2✔
1385
                                if brarErr != nil {
1✔
1386
                                        finalErr <- brarErr
×
1387
                                        return
×
1388
                                }
×
1389

1390
                                // If the BreachArbitrator successfully handled
1391
                                // the event, we can signal that the handoff
1392
                                // was successful.
1393
                                finalErr <- nil
1✔
1394
                        }
1395

1396
                        event := &contractcourt.ContractBreachEvent{
1✔
1397
                                ChanPoint:         chanPoint,
1✔
1398
                                ProcessACK:        processACK,
1✔
1399
                                BreachRetribution: breachRet,
1✔
1400
                        }
1✔
1401

1✔
1402
                        // Send the contract breach event to the
1✔
1403
                        // BreachArbitrator.
1✔
1404
                        select {
1✔
1405
                        case contractBreaches <- event:
1✔
1406
                        case <-s.quit:
×
1407
                                return ErrServerShuttingDown
×
1408
                        }
1409

1410
                        // We'll wait for a final error to be available from
1411
                        // the BreachArbitrator.
1412
                        select {
1✔
1413
                        case err := <-finalErr:
1✔
1414
                                return err
1✔
1415
                        case <-s.quit:
×
1416
                                return ErrServerShuttingDown
×
1417
                        }
1418
                },
1419
                DisableChannel: func(chanPoint wire.OutPoint) error {
1✔
1420
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
1✔
1421
                },
1✔
1422
                Sweeper:                       s.sweeper,
1423
                Registry:                      s.invoices,
1424
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1425
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1426
                OnionProcessor:                s.sphinx,
1427
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1428
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1429
                Clock:                         clock.NewDefaultClock(),
1430
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1431
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1432
                HtlcNotifier:                  s.htlcNotifier,
1433
                Budget:                        *s.cfg.Sweeper.Budget,
1434

1435
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1436
                QueryIncomingCircuit: func(
1437
                        circuit models.CircuitKey) *models.CircuitKey {
1✔
1438

1✔
1439
                        // Get the circuit map.
1✔
1440
                        circuits := s.htlcSwitch.CircuitLookup()
1✔
1441

1✔
1442
                        // Lookup the outgoing circuit.
1✔
1443
                        pc := circuits.LookupOpenCircuit(circuit)
1✔
1444
                        if pc == nil {
2✔
1445
                                return nil
1✔
1446
                        }
1✔
1447

1448
                        return &pc.Incoming
1✔
1449
                },
1450
                AuxLeafStore: implCfg.AuxLeafStore,
1451
                AuxSigner:    implCfg.AuxSigner,
1452
                AuxResolver:  implCfg.AuxContractResolver,
1453
        }, dbs.ChanStateDB)
1454

1455
        // Select the configuration and funding parameters for Bitcoin.
1456
        chainCfg := cfg.Bitcoin
1✔
1457
        minRemoteDelay := funding.MinBtcRemoteDelay
1✔
1458
        maxRemoteDelay := funding.MaxBtcRemoteDelay
1✔
1459

1✔
1460
        var chanIDSeed [32]byte
1✔
1461
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
1✔
1462
                return nil, err
×
1463
        }
×
1464

1465
        // Wrap the DeleteChannelEdges method so that the funding manager can
1466
        // use it without depending on several layers of indirection.
1467
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
1✔
1468
                *models.ChannelEdgePolicy, error) {
2✔
1469

1✔
1470
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
1✔
1471
                        scid.ToUint64(),
1✔
1472
                )
1✔
1473
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
1✔
1474
                        // This is unlikely but there is a slim chance of this
×
1475
                        // being hit if lnd was killed via SIGKILL and the
×
1476
                        // funding manager was stepping through the delete
×
1477
                        // alias edge logic.
×
1478
                        return nil, nil
×
1479
                } else if err != nil {
1✔
1480
                        return nil, err
×
1481
                }
×
1482

1483
                // Grab our key to find our policy.
1484
                var ourKey [33]byte
1✔
1485
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
1✔
1486

1✔
1487
                var ourPolicy *models.ChannelEdgePolicy
1✔
1488
                if info != nil && info.NodeKey1Bytes == ourKey {
2✔
1489
                        ourPolicy = e1
1✔
1490
                } else {
2✔
1491
                        ourPolicy = e2
1✔
1492
                }
1✔
1493

1494
                if ourPolicy == nil {
1✔
1495
                        // Something is wrong, so return an error.
×
1496
                        return nil, fmt.Errorf("we don't have an edge")
×
1497
                }
×
1498

1499
                err = s.graphDB.DeleteChannelEdges(
1✔
1500
                        false, false, scid.ToUint64(),
1✔
1501
                )
1✔
1502
                return ourPolicy, err
1✔
1503
        }
1504

1505
        // For the reservationTimeout and the zombieSweeperInterval different
1506
        // values are set in case we are in a dev environment so enhance test
1507
        // capacilities.
1508
        reservationTimeout := chanfunding.DefaultReservationTimeout
1✔
1509
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
1✔
1510

1✔
1511
        // Get the development config for funding manager. If we are not in
1✔
1512
        // development mode, this would be nil.
1✔
1513
        var devCfg *funding.DevConfig
1✔
1514
        if lncfg.IsDevBuild() {
2✔
1515
                devCfg = &funding.DevConfig{
1✔
1516
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
1✔
1517
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
1✔
1518
                                GetMaxWaitNumBlocksFundingConf(),
1✔
1519
                }
1✔
1520

1✔
1521
                reservationTimeout = cfg.Dev.GetReservationTimeout()
1✔
1522
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
1✔
1523

1✔
1524
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
1✔
1525
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
1✔
1526
                        devCfg, reservationTimeout, zombieSweeperInterval)
1✔
1527
        }
1✔
1528

1529
        //nolint:ll
1530
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
1✔
1531
                Dev:                devCfg,
1✔
1532
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
1✔
1533
                IDKey:              nodeKeyDesc.PubKey,
1✔
1534
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
1✔
1535
                Wallet:             cc.Wallet,
1✔
1536
                PublishTransaction: cc.Wallet.PublishTransaction,
1✔
1537
                UpdateLabel: func(hash chainhash.Hash, label string) error {
2✔
1538
                        return cc.Wallet.LabelTransaction(hash, label, true)
1✔
1539
                },
1✔
1540
                Notifier:     cc.ChainNotifier,
1541
                ChannelDB:    s.chanStateDB,
1542
                FeeEstimator: cc.FeeEstimator,
1543
                SignMessage:  cc.MsgSigner.SignMessage,
1544
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1545
                        error) {
1✔
1546

1✔
1547
                        return s.genNodeAnnouncement(nil)
1✔
1548
                },
1✔
1549
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1550
                NotifyWhenOnline:     s.NotifyWhenOnline,
1551
                TempChanIDSeed:       chanIDSeed,
1552
                FindChannel:          s.findChannel,
1553
                DefaultRoutingPolicy: cc.RoutingPolicy,
1554
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1555
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1556
                        pushAmt lnwire.MilliSatoshi) uint16 {
1✔
1557
                        // For large channels we increase the number
1✔
1558
                        // of confirmations we require for the
1✔
1559
                        // channel to be considered open. As it is
1✔
1560
                        // always the responder that gets to choose
1✔
1561
                        // value, the pushAmt is value being pushed
1✔
1562
                        // to us. This means we have more to lose
1✔
1563
                        // in the case this gets re-orged out, and
1✔
1564
                        // we will require more confirmations before
1✔
1565
                        // we consider it open.
1✔
1566

1✔
1567
                        // In case the user has explicitly specified
1✔
1568
                        // a default value for the number of
1✔
1569
                        // confirmations, we use it.
1✔
1570
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
1✔
1571
                        if defaultConf != 0 {
2✔
1572
                                return defaultConf
1✔
1573
                        }
1✔
1574

1575
                        minConf := uint64(3)
×
1576
                        maxConf := uint64(6)
×
1577

×
1578
                        // If this is a wumbo channel, then we'll require the
×
1579
                        // max amount of confirmations.
×
1580
                        if chanAmt > MaxFundingAmount {
×
1581
                                return uint16(maxConf)
×
1582
                        }
×
1583

1584
                        // If not we return a value scaled linearly
1585
                        // between 3 and 6, depending on channel size.
1586
                        // TODO(halseth): Use 1 as minimum?
1587
                        maxChannelSize := uint64(
×
1588
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1589
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1590
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1591
                        if conf < minConf {
×
1592
                                conf = minConf
×
1593
                        }
×
1594
                        if conf > maxConf {
×
1595
                                conf = maxConf
×
1596
                        }
×
1597
                        return uint16(conf)
×
1598
                },
1599
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
1✔
1600
                        // We scale the remote CSV delay (the time the
1✔
1601
                        // remote have to claim funds in case of a unilateral
1✔
1602
                        // close) linearly from minRemoteDelay blocks
1✔
1603
                        // for small channels, to maxRemoteDelay blocks
1✔
1604
                        // for channels of size MaxFundingAmount.
1✔
1605

1✔
1606
                        // In case the user has explicitly specified
1✔
1607
                        // a default value for the remote delay, we
1✔
1608
                        // use it.
1✔
1609
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
1✔
1610
                        if defaultDelay > 0 {
2✔
1611
                                return defaultDelay
1✔
1612
                        }
1✔
1613

1614
                        // If this is a wumbo channel, then we'll require the
1615
                        // max value.
1616
                        if chanAmt > MaxFundingAmount {
×
1617
                                return maxRemoteDelay
×
1618
                        }
×
1619

1620
                        // If not we scale according to channel size.
1621
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1622
                                chanAmt / MaxFundingAmount)
×
1623
                        if delay < minRemoteDelay {
×
1624
                                delay = minRemoteDelay
×
1625
                        }
×
1626
                        if delay > maxRemoteDelay {
×
1627
                                delay = maxRemoteDelay
×
1628
                        }
×
1629
                        return delay
×
1630
                },
1631
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1632
                        peerKey *btcec.PublicKey) error {
1✔
1633

1✔
1634
                        // First, we'll mark this new peer as a persistent peer
1✔
1635
                        // for re-connection purposes. If the peer is not yet
1✔
1636
                        // tracked or the user hasn't requested it to be perm,
1✔
1637
                        // we'll set false to prevent the server from continuing
1✔
1638
                        // to connect to this peer even if the number of
1✔
1639
                        // channels with this peer is zero.
1✔
1640
                        s.mu.Lock()
1✔
1641
                        pubStr := string(peerKey.SerializeCompressed())
1✔
1642
                        if _, ok := s.persistentPeers[pubStr]; !ok {
2✔
1643
                                s.persistentPeers[pubStr] = false
1✔
1644
                        }
1✔
1645
                        s.mu.Unlock()
1✔
1646

1✔
1647
                        // With that taken care of, we'll send this channel to
1✔
1648
                        // the chain arb so it can react to on-chain events.
1✔
1649
                        return s.chainArb.WatchNewChannel(channel)
1✔
1650
                },
1651
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
1✔
1652
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
1✔
1653
                        return s.htlcSwitch.UpdateShortChanID(cid)
1✔
1654
                },
1✔
1655
                RequiredRemoteChanReserve: func(chanAmt,
1656
                        dustLimit btcutil.Amount) btcutil.Amount {
1✔
1657

1✔
1658
                        // By default, we'll require the remote peer to maintain
1✔
1659
                        // at least 1% of the total channel capacity at all
1✔
1660
                        // times. If this value ends up dipping below the dust
1✔
1661
                        // limit, then we'll use the dust limit itself as the
1✔
1662
                        // reserve as required by BOLT #2.
1✔
1663
                        reserve := chanAmt / 100
1✔
1664
                        if reserve < dustLimit {
2✔
1665
                                reserve = dustLimit
1✔
1666
                        }
1✔
1667

1668
                        return reserve
1✔
1669
                },
1670
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
1✔
1671
                        // By default, we'll allow the remote peer to fully
1✔
1672
                        // utilize the full bandwidth of the channel, minus our
1✔
1673
                        // required reserve.
1✔
1674
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
1✔
1675
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
1✔
1676
                },
1✔
1677
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
1✔
1678
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
2✔
1679
                                return cfg.DefaultRemoteMaxHtlcs
1✔
1680
                        }
1✔
1681

1682
                        // By default, we'll permit them to utilize the full
1683
                        // channel bandwidth.
1684
                        return uint16(input.MaxHTLCNumber / 2)
×
1685
                },
1686
                ZombieSweeperInterval:         zombieSweeperInterval,
1687
                ReservationTimeout:            reservationTimeout,
1688
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1689
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1690
                MaxPendingChannels:            cfg.MaxPendingChannels,
1691
                RejectPush:                    cfg.RejectPush,
1692
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1693
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1694
                OpenChannelPredicate:          chanPredicate,
1695
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1696
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1697
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1698
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1699
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1700
                DeleteAliasEdge:      deleteAliasEdge,
1701
                AliasManager:         s.aliasMgr,
1702
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1703
                AuxFundingController: implCfg.AuxFundingController,
1704
                AuxSigner:            implCfg.AuxSigner,
1705
                AuxResolver:          implCfg.AuxContractResolver,
1706
        })
1707
        if err != nil {
1✔
1708
                return nil, err
×
1709
        }
×
1710

1711
        // Next, we'll assemble the sub-system that will maintain an on-disk
1712
        // static backup of the latest channel state.
1713
        chanNotifier := &channelNotifier{
1✔
1714
                chanNotifier: s.channelNotifier,
1✔
1715
                addrs:        s.addrSource,
1✔
1716
        }
1✔
1717
        backupFile := chanbackup.NewMultiFile(
1✔
1718
                cfg.BackupFilePath, cfg.NoBackupArchive,
1✔
1719
        )
1✔
1720
        startingChans, err := chanbackup.FetchStaticChanBackups(
1✔
1721
                s.chanStateDB, s.addrSource,
1✔
1722
        )
1✔
1723
        if err != nil {
1✔
1724
                return nil, err
×
1725
        }
×
1726
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
1✔
1727
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
1✔
1728
        )
1✔
1729
        if err != nil {
1✔
1730
                return nil, err
×
1731
        }
×
1732

1733
        // Assemble a peer notifier which will provide clients with subscriptions
1734
        // to peer online and offline events.
1735
        s.peerNotifier = peernotifier.New()
1✔
1736

1✔
1737
        // Create a channel event store which monitors all open channels.
1✔
1738
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
1✔
1739
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
2✔
1740
                        return s.channelNotifier.SubscribeChannelEvents()
1✔
1741
                },
1✔
1742
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
1✔
1743
                        return s.peerNotifier.SubscribePeerEvents()
1✔
1744
                },
1✔
1745
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1746
                Clock:           clock.NewDefaultClock(),
1747
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1748
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1749
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1750
        })
1751

1752
        if cfg.WtClient.Active {
2✔
1753
                policy := wtpolicy.DefaultPolicy()
1✔
1754
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
1✔
1755

1✔
1756
                // We expose the sweep fee rate in sat/vbyte, but the tower
1✔
1757
                // protocol operations on sat/kw.
1✔
1758
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
1✔
1759
                        1000 * cfg.WtClient.SweepFeeRate,
1✔
1760
                )
1✔
1761

1✔
1762
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
1✔
1763

1✔
1764
                if err := policy.Validate(); err != nil {
1✔
1765
                        return nil, err
×
1766
                }
×
1767

1768
                // authDial is the wrapper around the btrontide.Dial for the
1769
                // watchtower.
1770
                authDial := func(localKey keychain.SingleKeyECDH,
1✔
1771
                        netAddr *lnwire.NetAddress,
1✔
1772
                        dialer tor.DialFunc) (wtserver.Peer, error) {
2✔
1773

1✔
1774
                        return brontide.Dial(
1✔
1775
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
1✔
1776
                        )
1✔
1777
                }
1✔
1778

1779
                // buildBreachRetribution is a call-back that can be used to
1780
                // query the BreachRetribution info and channel type given a
1781
                // channel ID and commitment height.
1782
                buildBreachRetribution := func(chanID lnwire.ChannelID,
1✔
1783
                        commitHeight uint64) (*lnwallet.BreachRetribution,
1✔
1784
                        channeldb.ChannelType, error) {
2✔
1785

1✔
1786
                        channel, err := s.chanStateDB.FetchChannelByID(
1✔
1787
                                nil, chanID,
1✔
1788
                        )
1✔
1789
                        if err != nil {
1✔
1790
                                return nil, 0, err
×
1791
                        }
×
1792

1793
                        br, err := lnwallet.NewBreachRetribution(
1✔
1794
                                channel, commitHeight, 0, nil,
1✔
1795
                                implCfg.AuxLeafStore,
1✔
1796
                                implCfg.AuxContractResolver,
1✔
1797
                        )
1✔
1798
                        if err != nil {
1✔
1799
                                return nil, 0, err
×
1800
                        }
×
1801

1802
                        return br, channel.ChanType, nil
1✔
1803
                }
1804

1805
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
1✔
1806

1✔
1807
                // Copy the policy for legacy channels and set the blob flag
1✔
1808
                // signalling support for anchor channels.
1✔
1809
                anchorPolicy := policy
1✔
1810
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
1✔
1811

1✔
1812
                // Copy the policy for legacy channels and set the blob flag
1✔
1813
                // signalling support for taproot channels.
1✔
1814
                taprootPolicy := policy
1✔
1815
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
1✔
1816
                        blob.FlagTaprootChannel,
1✔
1817
                )
1✔
1818

1✔
1819
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
1✔
1820
                        FetchClosedChannel:     fetchClosedChannel,
1✔
1821
                        BuildBreachRetribution: buildBreachRetribution,
1✔
1822
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
1✔
1823
                        ChainNotifier:          s.cc.ChainNotifier,
1✔
1824
                        SubscribeChannelEvents: func() (subscribe.Subscription,
1✔
1825
                                error) {
2✔
1826

1✔
1827
                                return s.channelNotifier.
1✔
1828
                                        SubscribeChannelEvents()
1✔
1829
                        },
1✔
1830
                        Signer: cc.Wallet.Cfg.Signer,
1831
                        NewAddress: func() ([]byte, error) {
1✔
1832
                                addr, err := newSweepPkScriptGen(
1✔
1833
                                        cc.Wallet, netParams,
1✔
1834
                                )().Unpack()
1✔
1835
                                if err != nil {
1✔
1836
                                        return nil, err
×
1837
                                }
×
1838

1839
                                return addr.DeliveryAddress, nil
1✔
1840
                        },
1841
                        SecretKeyRing:      s.cc.KeyRing,
1842
                        Dial:               cfg.net.Dial,
1843
                        AuthDial:           authDial,
1844
                        DB:                 dbs.TowerClientDB,
1845
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1846
                        MinBackoff:         10 * time.Second,
1847
                        MaxBackoff:         5 * time.Minute,
1848
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1849
                }, policy, anchorPolicy, taprootPolicy)
1850
                if err != nil {
1✔
1851
                        return nil, err
×
1852
                }
×
1853
        }
1854

1855
        if len(cfg.ExternalHosts) != 0 {
1✔
1856
                advertisedIPs := make(map[string]struct{})
×
1857
                for _, addr := range s.currentNodeAnn.Addresses {
×
1858
                        advertisedIPs[addr.String()] = struct{}{}
×
1859
                }
×
1860

1861
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1862
                        Hosts:         cfg.ExternalHosts,
×
1863
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1864
                        LookupHost: func(host string) (net.Addr, error) {
×
1865
                                return lncfg.ParseAddressString(
×
1866
                                        host, strconv.Itoa(defaultPeerPort),
×
1867
                                        cfg.net.ResolveTCPAddr,
×
1868
                                )
×
1869
                        },
×
1870
                        AdvertisedIPs: advertisedIPs,
1871
                        AnnounceNewIPs: netann.IPAnnouncer(
1872
                                func(modifier ...netann.NodeAnnModifier) (
1873
                                        lnwire.NodeAnnouncement, error) {
×
1874

×
1875
                                        return s.genNodeAnnouncement(
×
1876
                                                nil, modifier...,
×
1877
                                        )
×
1878
                                }),
×
1879
                })
1880
        }
1881

1882
        // Create liveness monitor.
1883
        s.createLivenessMonitor(cfg, cc, leaderElector)
1✔
1884

1✔
1885
        listeners := make([]net.Listener, len(listenAddrs))
1✔
1886
        for i, listenAddr := range listenAddrs {
2✔
1887
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
1✔
1888
                // doesn't need to call the general lndResolveTCP function
1✔
1889
                // since we are resolving a local address.
1✔
1890

1✔
1891
                // RESOLVE: We are actually partially accepting inbound
1✔
1892
                // connection requests when we call NewListener.
1✔
1893
                listeners[i], err = brontide.NewListener(
1✔
1894
                        nodeKeyECDH, listenAddr.String(),
1✔
1895
                        s.peerAccessMan.checkIncomingConnBanScore,
1✔
1896
                )
1✔
1897
                if err != nil {
1✔
1898
                        return nil, err
×
1899
                }
×
1900
        }
1901

1902
        // Create the connection manager which will be responsible for
1903
        // maintaining persistent outbound connections and also accepting new
1904
        // incoming connections
1905
        cmgr, err := connmgr.New(&connmgr.Config{
1✔
1906
                Listeners:      listeners,
1✔
1907
                OnAccept:       s.InboundPeerConnected,
1✔
1908
                RetryDuration:  time.Second * 5,
1✔
1909
                TargetOutbound: 100,
1✔
1910
                Dial: noiseDial(
1✔
1911
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
1✔
1912
                ),
1✔
1913
                OnConnection: s.OutboundPeerConnected,
1✔
1914
        })
1✔
1915
        if err != nil {
1✔
1916
                return nil, err
×
1917
        }
×
1918
        s.connMgr = cmgr
1✔
1919

1✔
1920
        // Finally, register the subsystems in blockbeat.
1✔
1921
        s.registerBlockConsumers()
1✔
1922

1✔
1923
        return s, nil
1✔
1924
}
1925

1926
// UpdateRoutingConfig is a callback function to update the routing config
1927
// values in the main cfg.
1928
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
1✔
1929
        routerCfg := s.cfg.SubRPCServers.RouterRPC
1✔
1930

1✔
1931
        switch c := cfg.Estimator.Config().(type) {
1✔
1932
        case routing.AprioriConfig:
1✔
1933
                routerCfg.ProbabilityEstimatorType =
1✔
1934
                        routing.AprioriEstimatorName
1✔
1935

1✔
1936
                targetCfg := routerCfg.AprioriConfig
1✔
1937
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
1✔
1938
                targetCfg.Weight = c.AprioriWeight
1✔
1939
                targetCfg.CapacityFraction = c.CapacityFraction
1✔
1940
                targetCfg.HopProbability = c.AprioriHopProbability
1✔
1941

1942
        case routing.BimodalConfig:
1✔
1943
                routerCfg.ProbabilityEstimatorType =
1✔
1944
                        routing.BimodalEstimatorName
1✔
1945

1✔
1946
                targetCfg := routerCfg.BimodalConfig
1✔
1947
                targetCfg.Scale = int64(c.BimodalScaleMsat)
1✔
1948
                targetCfg.NodeWeight = c.BimodalNodeWeight
1✔
1949
                targetCfg.DecayTime = c.BimodalDecayTime
1✔
1950
        }
1951

1952
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
1✔
1953
}
1954

1955
// registerBlockConsumers registers the subsystems that consume block events.
1956
// By calling `RegisterQueue`, a list of subsystems are registered in the
1957
// blockbeat for block notifications. When a new block arrives, the subsystems
1958
// in the same queue are notified sequentially, and different queues are
1959
// notified concurrently.
1960
//
1961
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1962
// a new `RegisterQueue` call.
1963
func (s *server) registerBlockConsumers() {
1✔
1964
        // In this queue, when a new block arrives, it will be received and
1✔
1965
        // processed in this order: chainArb -> sweeper -> txPublisher.
1✔
1966
        consumers := []chainio.Consumer{
1✔
1967
                s.chainArb,
1✔
1968
                s.sweeper,
1✔
1969
                s.txPublisher,
1✔
1970
        }
1✔
1971
        s.blockbeatDispatcher.RegisterQueue(consumers)
1✔
1972
}
1✔
1973

1974
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1975
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1976
// may differ from what is on disk.
1977
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1978
        error) {
1✔
1979

1✔
1980
        data, err := u.DataToSign()
1✔
1981
        if err != nil {
1✔
1982
                return nil, err
×
1983
        }
×
1984

1985
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
1✔
1986
}
1987

1988
// createLivenessMonitor creates a set of health checks using our configured
1989
// values and uses these checks to create a liveness monitor. Available
1990
// health checks,
1991
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1992
//   - diskCheck
1993
//   - tlsHealthCheck
1994
//   - torController, only created when tor is enabled.
1995
//
1996
// If a health check has been disabled by setting attempts to 0, our monitor
1997
// will not run it.
1998
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
1999
        leaderElector cluster.LeaderElector) {
1✔
2000

1✔
2001
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
1✔
2002
        if cfg.Bitcoin.Node == "nochainbackend" {
1✔
2003
                srvrLog.Info("Disabling chain backend checks for " +
×
2004
                        "nochainbackend mode")
×
2005

×
2006
                chainBackendAttempts = 0
×
2007
        }
×
2008

2009
        chainHealthCheck := healthcheck.NewObservation(
1✔
2010
                "chain backend",
1✔
2011
                cc.HealthCheck,
1✔
2012
                cfg.HealthChecks.ChainCheck.Interval,
1✔
2013
                cfg.HealthChecks.ChainCheck.Timeout,
1✔
2014
                cfg.HealthChecks.ChainCheck.Backoff,
1✔
2015
                chainBackendAttempts,
1✔
2016
        )
1✔
2017

1✔
2018
        diskCheck := healthcheck.NewObservation(
1✔
2019
                "disk space",
1✔
2020
                func() error {
1✔
2021
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2022
                                cfg.LndDir,
×
2023
                        )
×
2024
                        if err != nil {
×
2025
                                return err
×
2026
                        }
×
2027

2028
                        // If we have more free space than we require,
2029
                        // we return a nil error.
2030
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2031
                                return nil
×
2032
                        }
×
2033

2034
                        return fmt.Errorf("require: %v free space, got: %v",
×
2035
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2036
                                free)
×
2037
                },
2038
                cfg.HealthChecks.DiskCheck.Interval,
2039
                cfg.HealthChecks.DiskCheck.Timeout,
2040
                cfg.HealthChecks.DiskCheck.Backoff,
2041
                cfg.HealthChecks.DiskCheck.Attempts,
2042
        )
2043

2044
        tlsHealthCheck := healthcheck.NewObservation(
1✔
2045
                "tls",
1✔
2046
                func() error {
1✔
2047
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2048
                                s.cc.KeyRing,
×
2049
                        )
×
2050
                        if err != nil {
×
2051
                                return err
×
2052
                        }
×
2053
                        if expired {
×
2054
                                return fmt.Errorf("TLS certificate is "+
×
2055
                                        "expired as of %v", expTime)
×
2056
                        }
×
2057

2058
                        // If the certificate is not outdated, no error needs
2059
                        // to be returned
2060
                        return nil
×
2061
                },
2062
                cfg.HealthChecks.TLSCheck.Interval,
2063
                cfg.HealthChecks.TLSCheck.Timeout,
2064
                cfg.HealthChecks.TLSCheck.Backoff,
2065
                cfg.HealthChecks.TLSCheck.Attempts,
2066
        )
2067

2068
        checks := []*healthcheck.Observation{
1✔
2069
                chainHealthCheck, diskCheck, tlsHealthCheck,
1✔
2070
        }
1✔
2071

1✔
2072
        // If Tor is enabled, add the healthcheck for tor connection.
1✔
2073
        if s.torController != nil {
1✔
2074
                torConnectionCheck := healthcheck.NewObservation(
×
2075
                        "tor connection",
×
2076
                        func() error {
×
2077
                                return healthcheck.CheckTorServiceStatus(
×
2078
                                        s.torController,
×
2079
                                        s.createNewHiddenService,
×
2080
                                )
×
2081
                        },
×
2082
                        cfg.HealthChecks.TorConnection.Interval,
2083
                        cfg.HealthChecks.TorConnection.Timeout,
2084
                        cfg.HealthChecks.TorConnection.Backoff,
2085
                        cfg.HealthChecks.TorConnection.Attempts,
2086
                )
2087
                checks = append(checks, torConnectionCheck)
×
2088
        }
2089

2090
        // If remote signing is enabled, add the healthcheck for the remote
2091
        // signing RPC interface.
2092
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
2✔
2093
                // Because we have two cascading timeouts here, we need to add
1✔
2094
                // some slack to the "outer" one of them in case the "inner"
1✔
2095
                // returns exactly on time.
1✔
2096
                overhead := time.Millisecond * 10
1✔
2097

1✔
2098
                remoteSignerConnectionCheck := healthcheck.NewObservation(
1✔
2099
                        "remote signer connection",
1✔
2100
                        rpcwallet.HealthCheck(
1✔
2101
                                s.cfg.RemoteSigner,
1✔
2102

1✔
2103
                                // For the health check we might to be even
1✔
2104
                                // stricter than the initial/normal connect, so
1✔
2105
                                // we use the health check timeout here.
1✔
2106
                                cfg.HealthChecks.RemoteSigner.Timeout,
1✔
2107
                        ),
1✔
2108
                        cfg.HealthChecks.RemoteSigner.Interval,
1✔
2109
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
1✔
2110
                        cfg.HealthChecks.RemoteSigner.Backoff,
1✔
2111
                        cfg.HealthChecks.RemoteSigner.Attempts,
1✔
2112
                )
1✔
2113
                checks = append(checks, remoteSignerConnectionCheck)
1✔
2114
        }
1✔
2115

2116
        // If we have a leader elector, we add a health check to ensure we are
2117
        // still the leader. During normal operation, we should always be the
2118
        // leader, but there are circumstances where this may change, such as
2119
        // when we lose network connectivity for long enough expiring out lease.
2120
        if leaderElector != nil {
1✔
2121
                leaderCheck := healthcheck.NewObservation(
×
2122
                        "leader status",
×
2123
                        func() error {
×
2124
                                // Check if we are still the leader. Note that
×
2125
                                // we don't need to use a timeout context here
×
2126
                                // as the healthcheck observer will handle the
×
2127
                                // timeout case for us.
×
2128
                                timeoutCtx, cancel := context.WithTimeout(
×
2129
                                        context.Background(),
×
2130
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2131
                                )
×
2132
                                defer cancel()
×
2133

×
2134
                                leader, err := leaderElector.IsLeader(
×
2135
                                        timeoutCtx,
×
2136
                                )
×
2137
                                if err != nil {
×
2138
                                        return fmt.Errorf("unable to check if "+
×
2139
                                                "still leader: %v", err)
×
2140
                                }
×
2141

2142
                                if !leader {
×
2143
                                        srvrLog.Debug("Not the current leader")
×
2144
                                        return fmt.Errorf("not the current " +
×
2145
                                                "leader")
×
2146
                                }
×
2147

2148
                                return nil
×
2149
                        },
2150
                        cfg.HealthChecks.LeaderCheck.Interval,
2151
                        cfg.HealthChecks.LeaderCheck.Timeout,
2152
                        cfg.HealthChecks.LeaderCheck.Backoff,
2153
                        cfg.HealthChecks.LeaderCheck.Attempts,
2154
                )
2155

2156
                checks = append(checks, leaderCheck)
×
2157
        }
2158

2159
        // If we have not disabled all of our health checks, we create a
2160
        // liveness monitor with our configured checks.
2161
        s.livenessMonitor = healthcheck.NewMonitor(
1✔
2162
                &healthcheck.Config{
1✔
2163
                        Checks:   checks,
1✔
2164
                        Shutdown: srvrLog.Criticalf,
1✔
2165
                },
1✔
2166
        )
1✔
2167
}
2168

2169
// Started returns true if the server has been started, and false otherwise.
2170
// NOTE: This function is safe for concurrent access.
2171
func (s *server) Started() bool {
1✔
2172
        return atomic.LoadInt32(&s.active) != 0
1✔
2173
}
1✔
2174

2175
// cleaner is used to aggregate "cleanup" functions during an operation that
2176
// starts several subsystems. In case one of the subsystem fails to start
2177
// and a proper resource cleanup is required, the "run" method achieves this
2178
// by running all these added "cleanup" functions.
2179
type cleaner []func() error
2180

2181
// add is used to add a cleanup function to be called when
2182
// the run function is executed.
2183
func (c cleaner) add(cleanup func() error) cleaner {
1✔
2184
        return append(c, cleanup)
1✔
2185
}
1✔
2186

2187
// run is used to run all the previousely added cleanup functions.
2188
func (c cleaner) run() {
×
2189
        for i := len(c) - 1; i >= 0; i-- {
×
2190
                if err := c[i](); err != nil {
×
2191
                        srvrLog.Errorf("Cleanup failed: %v", err)
×
2192
                }
×
2193
        }
2194
}
2195

2196
// startLowLevelServices starts the low-level services of the server. These
2197
// services must be started successfully before running the main server. The
2198
// services are,
2199
// 1. the chain notifier.
2200
//
2201
// TODO(yy): identify and add more low-level services here.
2202
func (s *server) startLowLevelServices() error {
1✔
2203
        var startErr error
1✔
2204

1✔
2205
        cleanup := cleaner{}
1✔
2206

1✔
2207
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
1✔
2208
        if err := s.cc.ChainNotifier.Start(); err != nil {
1✔
2209
                startErr = err
×
2210
        }
×
2211

2212
        if startErr != nil {
1✔
2213
                cleanup.run()
×
2214
        }
×
2215

2216
        return startErr
1✔
2217
}
2218

2219
// Start starts the main daemon server, all requested listeners, and any helper
2220
// goroutines.
2221
// NOTE: This function is safe for concurrent access.
2222
//
2223
//nolint:funlen
2224
func (s *server) Start() error {
1✔
2225
        // Get the current blockbeat.
1✔
2226
        beat, err := s.getStartingBeat()
1✔
2227
        if err != nil {
1✔
2228
                return err
×
2229
        }
×
2230

2231
        var startErr error
1✔
2232

1✔
2233
        // If one sub system fails to start, the following code ensures that the
1✔
2234
        // previous started ones are stopped. It also ensures a proper wallet
1✔
2235
        // shutdown which is important for releasing its resources (boltdb, etc...)
1✔
2236
        cleanup := cleaner{}
1✔
2237

1✔
2238
        s.start.Do(func() {
2✔
2239
                cleanup = cleanup.add(s.customMessageServer.Stop)
1✔
2240
                if err := s.customMessageServer.Start(); err != nil {
1✔
2241
                        startErr = err
×
2242
                        return
×
2243
                }
×
2244

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

2253
                if s.livenessMonitor != nil {
2✔
2254
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
1✔
2255
                        if err := s.livenessMonitor.Start(); err != nil {
1✔
2256
                                startErr = err
×
2257
                                return
×
2258
                        }
×
2259
                }
2260

2261
                // Start the notification server. This is used so channel
2262
                // management goroutines can be notified when a funding
2263
                // transaction reaches a sufficient number of confirmations, or
2264
                // when the input for the funding transaction is spent in an
2265
                // attempt at an uncooperative close by the counterparty.
2266
                cleanup = cleanup.add(s.sigPool.Stop)
1✔
2267
                if err := s.sigPool.Start(); err != nil {
1✔
2268
                        startErr = err
×
2269
                        return
×
2270
                }
×
2271

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

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

2284
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
1✔
2285
                if err := s.cc.BestBlockTracker.Start(); err != nil {
1✔
2286
                        startErr = err
×
2287
                        return
×
2288
                }
×
2289

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

2296
                cleanup = cleanup.add(func() error {
1✔
2297
                        return s.peerNotifier.Stop()
×
2298
                })
×
2299
                if err := s.peerNotifier.Start(); err != nil {
1✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

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

2310
                if s.towerClientMgr != nil {
2✔
2311
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
1✔
2312
                        if err := s.towerClientMgr.Start(); err != nil {
1✔
2313
                                startErr = err
×
2314
                                return
×
2315
                        }
×
2316
                }
2317

2318
                cleanup = cleanup.add(s.txPublisher.Stop)
1✔
2319
                if err := s.txPublisher.Start(beat); err != nil {
1✔
2320
                        startErr = err
×
2321
                        return
×
2322
                }
×
2323

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

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

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

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

2348
                // htlcSwitch must be started before chainArb since the latter
2349
                // relies on htlcSwitch to deliver resolution message upon
2350
                // start.
2351
                cleanup = cleanup.add(s.htlcSwitch.Stop)
1✔
2352
                if err := s.htlcSwitch.Start(); err != nil {
1✔
2353
                        startErr = err
×
2354
                        return
×
2355
                }
×
2356

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

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

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

2375
                cleanup = cleanup.add(s.graphDB.Stop)
1✔
2376
                if err := s.graphDB.Start(); err != nil {
1✔
2377
                        startErr = err
×
2378
                        return
×
2379
                }
×
2380

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

2387
                cleanup = cleanup.add(s.chanRouter.Stop)
1✔
2388
                if err := s.chanRouter.Start(); err != nil {
1✔
2389
                        startErr = err
×
2390
                        return
×
2391
                }
×
2392
                // The authGossiper depends on the chanRouter and therefore
2393
                // should be started after it.
2394
                cleanup = cleanup.add(s.authGossiper.Stop)
1✔
2395
                if err := s.authGossiper.Start(); err != nil {
1✔
2396
                        startErr = err
×
2397
                        return
×
2398
                }
×
2399

2400
                cleanup = cleanup.add(s.invoices.Stop)
1✔
2401
                if err := s.invoices.Start(); err != nil {
1✔
2402
                        startErr = err
×
2403
                        return
×
2404
                }
×
2405

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

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

2418
                cleanup = cleanup.add(s.chanEventStore.Stop)
1✔
2419
                if err := s.chanEventStore.Start(); err != nil {
1✔
2420
                        startErr = err
×
2421
                        return
×
2422
                }
×
2423

2424
                cleanup.add(func() error {
1✔
2425
                        s.missionController.StopStoreTickers()
×
2426
                        return nil
×
2427
                })
×
2428
                s.missionController.RunStoreTickers()
1✔
2429

1✔
2430
                // Before we start the connMgr, we'll check to see if we have
1✔
2431
                // any backups to recover. We do this now as we want to ensure
1✔
2432
                // that have all the information we need to handle channel
1✔
2433
                // recovery _before_ we even accept connections from any peers.
1✔
2434
                chanRestorer := &chanDBRestorer{
1✔
2435
                        db:         s.chanStateDB,
1✔
2436
                        secretKeys: s.cc.KeyRing,
1✔
2437
                        chainArb:   s.chainArb,
1✔
2438
                }
1✔
2439
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
1✔
2440
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2441
                                s.chansToRestore.PackedSingleChanBackups,
×
2442
                                s.cc.KeyRing, chanRestorer, s,
×
2443
                        )
×
2444
                        if err != nil {
×
2445
                                startErr = fmt.Errorf("unable to unpack single "+
×
2446
                                        "backups: %v", err)
×
2447
                                return
×
2448
                        }
×
2449
                }
2450
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
2✔
2451
                        _, err := chanbackup.UnpackAndRecoverMulti(
1✔
2452
                                s.chansToRestore.PackedMultiChanBackup,
1✔
2453
                                s.cc.KeyRing, chanRestorer, s,
1✔
2454
                        )
1✔
2455
                        if err != nil {
1✔
2456
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2457
                                        "backup: %v", err)
×
2458
                                return
×
2459
                        }
×
2460
                }
2461

2462
                // chanSubSwapper must be started after the `channelNotifier`
2463
                // because it depends on channel events as a synchronization
2464
                // point.
2465
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
1✔
2466
                if err := s.chanSubSwapper.Start(); err != nil {
1✔
2467
                        startErr = err
×
2468
                        return
×
2469
                }
×
2470

2471
                if s.torController != nil {
1✔
2472
                        cleanup = cleanup.add(s.torController.Stop)
×
2473
                        if err := s.createNewHiddenService(); err != nil {
×
2474
                                startErr = err
×
2475
                                return
×
2476
                        }
×
2477
                }
2478

2479
                if s.natTraversal != nil {
1✔
2480
                        s.wg.Add(1)
×
2481
                        go s.watchExternalIP()
×
2482
                }
×
2483

2484
                // Start connmgr last to prevent connections before init.
2485
                cleanup = cleanup.add(func() error {
1✔
2486
                        s.connMgr.Stop()
×
2487
                        return nil
×
2488
                })
×
2489

2490
                // RESOLVE: s.connMgr.Start() is called here, but
2491
                // brontide.NewListener() is called in newServer. This means
2492
                // that we are actually listening and partially accepting
2493
                // inbound connections even before the connMgr starts.
2494
                //
2495
                // TODO(yy): move the log into the connMgr's `Start` method.
2496
                srvrLog.Info("connMgr starting...")
1✔
2497
                s.connMgr.Start()
1✔
2498
                srvrLog.Debug("connMgr started")
1✔
2499

1✔
2500
                // If peers are specified as a config option, we'll add those
1✔
2501
                // peers first.
1✔
2502
                for _, peerAddrCfg := range s.cfg.AddPeers {
2✔
2503
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
1✔
2504
                                peerAddrCfg,
1✔
2505
                        )
1✔
2506
                        if err != nil {
1✔
2507
                                startErr = fmt.Errorf("unable to parse peer "+
×
2508
                                        "pubkey from config: %v", err)
×
2509
                                return
×
2510
                        }
×
2511
                        addr, err := parseAddr(parsedHost, s.cfg.net)
1✔
2512
                        if err != nil {
1✔
2513
                                startErr = fmt.Errorf("unable to parse peer "+
×
2514
                                        "address provided as a config option: "+
×
2515
                                        "%v", err)
×
2516
                                return
×
2517
                        }
×
2518

2519
                        peerAddr := &lnwire.NetAddress{
1✔
2520
                                IdentityKey: parsedPubkey,
1✔
2521
                                Address:     addr,
1✔
2522
                                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
2523
                        }
1✔
2524

1✔
2525
                        err = s.ConnectToPeer(
1✔
2526
                                peerAddr, true,
1✔
2527
                                s.cfg.ConnectionTimeout,
1✔
2528
                        )
1✔
2529
                        if err != nil {
1✔
2530
                                startErr = fmt.Errorf("unable to connect to "+
×
2531
                                        "peer address provided as a config "+
×
2532
                                        "option: %v", err)
×
2533
                                return
×
2534
                        }
×
2535
                }
2536

2537
                // Subscribe to NodeAnnouncements that advertise new addresses
2538
                // our persistent peers.
2539
                if err := s.updatePersistentPeerAddrs(); err != nil {
1✔
2540
                        srvrLog.Errorf("Failed to update persistent peer "+
×
2541
                                "addr: %v", err)
×
2542

×
2543
                        startErr = err
×
2544
                        return
×
2545
                }
×
2546

2547
                // With all the relevant sub-systems started, we'll now attempt
2548
                // to establish persistent connections to our direct channel
2549
                // collaborators within the network. Before doing so however,
2550
                // we'll prune our set of link nodes found within the database
2551
                // to ensure we don't reconnect to any nodes we no longer have
2552
                // open channels with.
2553
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
1✔
2554
                        srvrLog.Errorf("Failed to prune link nodes: %v", err)
×
2555

×
2556
                        startErr = err
×
2557
                        return
×
2558
                }
×
2559

2560
                if err := s.establishPersistentConnections(); err != nil {
1✔
2561
                        srvrLog.Errorf("Failed to establish persistent "+
×
2562
                                "connections: %v", err)
×
2563
                }
×
2564

2565
                // setSeedList is a helper function that turns multiple DNS seed
2566
                // server tuples from the command line or config file into the
2567
                // data structure we need and does a basic formal sanity check
2568
                // in the process.
2569
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
1✔
2570
                        if len(tuples) == 0 {
×
2571
                                return
×
2572
                        }
×
2573

2574
                        result := make([][2]string, len(tuples))
×
2575
                        for idx, tuple := range tuples {
×
2576
                                tuple = strings.TrimSpace(tuple)
×
2577
                                if len(tuple) == 0 {
×
2578
                                        return
×
2579
                                }
×
2580

2581
                                servers := strings.Split(tuple, ",")
×
2582
                                if len(servers) > 2 || len(servers) == 0 {
×
2583
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2584
                                                "seed tuple: %v", servers)
×
2585
                                        return
×
2586
                                }
×
2587

2588
                                copy(result[idx][:], servers)
×
2589
                        }
2590

2591
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2592
                }
2593

2594
                // Let users overwrite the DNS seed nodes. We only allow them
2595
                // for bitcoin mainnet/testnet/signet.
2596
                if s.cfg.Bitcoin.MainNet {
1✔
2597
                        setSeedList(
×
2598
                                s.cfg.Bitcoin.DNSSeeds,
×
2599
                                chainreg.BitcoinMainnetGenesis,
×
2600
                        )
×
2601
                }
×
2602
                if s.cfg.Bitcoin.TestNet3 {
1✔
2603
                        setSeedList(
×
2604
                                s.cfg.Bitcoin.DNSSeeds,
×
2605
                                chainreg.BitcoinTestnetGenesis,
×
2606
                        )
×
2607
                }
×
2608
                if s.cfg.Bitcoin.TestNet4 {
1✔
2609
                        setSeedList(
×
2610
                                s.cfg.Bitcoin.DNSSeeds,
×
2611
                                chainreg.BitcoinTestnet4Genesis,
×
2612
                        )
×
2613
                }
×
2614
                if s.cfg.Bitcoin.SigNet {
1✔
2615
                        setSeedList(
×
2616
                                s.cfg.Bitcoin.DNSSeeds,
×
2617
                                chainreg.BitcoinSignetGenesis,
×
2618
                        )
×
2619
                }
×
2620

2621
                // If network bootstrapping hasn't been disabled, then we'll
2622
                // configure the set of active bootstrappers, and launch a
2623
                // dedicated goroutine to maintain a set of persistent
2624
                // connections.
2625
                if shouldPeerBootstrap(s.cfg) {
1✔
2626
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2627
                        if err != nil {
×
2628
                                startErr = err
×
2629
                                return
×
2630
                        }
×
2631

2632
                        s.wg.Add(1)
×
2633
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2634
                } else {
1✔
2635
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
1✔
2636
                }
1✔
2637

2638
                // Start the blockbeat after all other subsystems have been
2639
                // started so they are ready to receive new blocks.
2640
                cleanup = cleanup.add(func() error {
1✔
2641
                        s.blockbeatDispatcher.Stop()
×
2642
                        return nil
×
2643
                })
×
2644
                if err := s.blockbeatDispatcher.Start(); err != nil {
1✔
2645
                        startErr = err
×
2646
                        return
×
2647
                }
×
2648

2649
                // Set the active flag now that we've completed the full
2650
                // startup.
2651
                atomic.StoreInt32(&s.active, 1)
1✔
2652
        })
2653

2654
        if startErr != nil {
1✔
2655
                cleanup.run()
×
2656
        }
×
2657
        return startErr
1✔
2658
}
2659

2660
// Stop gracefully shutsdown the main daemon server. This function will signal
2661
// any active goroutines, or helper objects to exit, then blocks until they've
2662
// all successfully exited. Additionally, any/all listeners are closed.
2663
// NOTE: This function is safe for concurrent access.
2664
func (s *server) Stop() error {
1✔
2665
        s.stop.Do(func() {
2✔
2666
                atomic.StoreInt32(&s.stopping, 1)
1✔
2667

1✔
2668
                close(s.quit)
1✔
2669

1✔
2670
                // Shutdown connMgr first to prevent conns during shutdown.
1✔
2671
                s.connMgr.Stop()
1✔
2672

1✔
2673
                // Stop dispatching blocks to other systems immediately.
1✔
2674
                s.blockbeatDispatcher.Stop()
1✔
2675

1✔
2676
                // Shutdown the wallet, funding manager, and the rpc server.
1✔
2677
                if err := s.chanStatusMgr.Stop(); err != nil {
1✔
2678
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2679
                }
×
2680
                if err := s.htlcSwitch.Stop(); err != nil {
1✔
2681
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2682
                }
×
2683
                if err := s.sphinx.Stop(); err != nil {
1✔
2684
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2685
                }
×
2686
                if err := s.invoices.Stop(); err != nil {
1✔
2687
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2688
                }
×
2689
                if err := s.interceptableSwitch.Stop(); err != nil {
1✔
2690
                        srvrLog.Warnf("failed to stop interceptable "+
×
2691
                                "switch: %v", err)
×
2692
                }
×
2693
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
1✔
2694
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2695
                                "modifier: %v", err)
×
2696
                }
×
2697
                if err := s.chanRouter.Stop(); err != nil {
1✔
2698
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2699
                }
×
2700
                if err := s.graphBuilder.Stop(); err != nil {
1✔
2701
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2702
                }
×
2703
                if err := s.graphDB.Stop(); err != nil {
1✔
2704
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
2705
                }
×
2706
                if err := s.chainArb.Stop(); err != nil {
1✔
2707
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2708
                }
×
2709
                if err := s.fundingMgr.Stop(); err != nil {
1✔
2710
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2711
                }
×
2712
                if err := s.breachArbitrator.Stop(); err != nil {
1✔
2713
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2714
                                err)
×
2715
                }
×
2716
                if err := s.utxoNursery.Stop(); err != nil {
1✔
2717
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2718
                }
×
2719
                if err := s.authGossiper.Stop(); err != nil {
1✔
2720
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2721
                }
×
2722
                if err := s.sweeper.Stop(); err != nil {
1✔
2723
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2724
                }
×
2725
                if err := s.txPublisher.Stop(); err != nil {
1✔
2726
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2727
                }
×
2728
                if err := s.channelNotifier.Stop(); err != nil {
1✔
2729
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2730
                }
×
2731
                if err := s.peerNotifier.Stop(); err != nil {
1✔
2732
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2733
                }
×
2734
                if err := s.htlcNotifier.Stop(); err != nil {
1✔
2735
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2736
                }
×
2737

2738
                // Update channel.backup file. Make sure to do it before
2739
                // stopping chanSubSwapper.
2740
                singles, err := chanbackup.FetchStaticChanBackups(
1✔
2741
                        s.chanStateDB, s.addrSource,
1✔
2742
                )
1✔
2743
                if err != nil {
1✔
2744
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2745
                                err)
×
2746
                } else {
1✔
2747
                        err := s.chanSubSwapper.ManualUpdate(singles)
1✔
2748
                        if err != nil {
2✔
2749
                                srvrLog.Warnf("Manual update of channel "+
1✔
2750
                                        "backup failed: %v", err)
1✔
2751
                        }
1✔
2752
                }
2753

2754
                if err := s.chanSubSwapper.Stop(); err != nil {
1✔
2755
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2756
                }
×
2757
                if err := s.cc.ChainNotifier.Stop(); err != nil {
1✔
2758
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2759
                }
×
2760
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
1✔
2761
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2762
                                err)
×
2763
                }
×
2764
                if err := s.chanEventStore.Stop(); err != nil {
1✔
2765
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2766
                                err)
×
2767
                }
×
2768
                s.missionController.StopStoreTickers()
1✔
2769

1✔
2770
                // Disconnect from each active peers to ensure that
1✔
2771
                // peerTerminationWatchers signal completion to each peer.
1✔
2772
                for _, peer := range s.Peers() {
2✔
2773
                        err := s.DisconnectPeer(peer.IdentityKey())
1✔
2774
                        if err != nil {
1✔
2775
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2776
                                        "received error: %v", peer.IdentityKey(),
×
2777
                                        err,
×
2778
                                )
×
2779
                        }
×
2780
                }
2781

2782
                // Now that all connections have been torn down, stop the tower
2783
                // client which will reliably flush all queued states to the
2784
                // tower. If this is halted for any reason, the force quit timer
2785
                // will kick in and abort to allow this method to return.
2786
                if s.towerClientMgr != nil {
2✔
2787
                        if err := s.towerClientMgr.Stop(); err != nil {
1✔
2788
                                srvrLog.Warnf("Unable to shut down tower "+
×
2789
                                        "client manager: %v", err)
×
2790
                        }
×
2791
                }
2792

2793
                if s.hostAnn != nil {
1✔
2794
                        if err := s.hostAnn.Stop(); err != nil {
×
2795
                                srvrLog.Warnf("unable to shut down host "+
×
2796
                                        "annoucner: %v", err)
×
2797
                        }
×
2798
                }
2799

2800
                if s.livenessMonitor != nil {
2✔
2801
                        if err := s.livenessMonitor.Stop(); err != nil {
1✔
2802
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2803
                                        "monitor: %v", err)
×
2804
                        }
×
2805
                }
2806

2807
                // Wait for all lingering goroutines to quit.
2808
                srvrLog.Debug("Waiting for server to shutdown...")
1✔
2809
                s.wg.Wait()
1✔
2810

1✔
2811
                srvrLog.Debug("Stopping buffer pools...")
1✔
2812
                s.sigPool.Stop()
1✔
2813
                s.writePool.Stop()
1✔
2814
                s.readPool.Stop()
1✔
2815
        })
2816

2817
        return nil
1✔
2818
}
2819

2820
// Stopped returns true if the server has been instructed to shutdown.
2821
// NOTE: This function is safe for concurrent access.
2822
func (s *server) Stopped() bool {
1✔
2823
        return atomic.LoadInt32(&s.stopping) != 0
1✔
2824
}
1✔
2825

2826
// configurePortForwarding attempts to set up port forwarding for the different
2827
// ports that the server will be listening on.
2828
//
2829
// NOTE: This should only be used when using some kind of NAT traversal to
2830
// automatically set up forwarding rules.
2831
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2832
        ip, err := s.natTraversal.ExternalIP()
×
2833
        if err != nil {
×
2834
                return nil, err
×
2835
        }
×
2836
        s.lastDetectedIP = ip
×
2837

×
2838
        externalIPs := make([]string, 0, len(ports))
×
2839
        for _, port := range ports {
×
2840
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2841
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2842
                        continue
×
2843
                }
2844

2845
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2846
                externalIPs = append(externalIPs, hostIP)
×
2847
        }
2848

2849
        return externalIPs, nil
×
2850
}
2851

2852
// removePortForwarding attempts to clear the forwarding rules for the different
2853
// ports the server is currently listening on.
2854
//
2855
// NOTE: This should only be used when using some kind of NAT traversal to
2856
// automatically set up forwarding rules.
2857
func (s *server) removePortForwarding() {
×
2858
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2859
        for _, port := range forwardedPorts {
×
2860
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2861
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2862
                                "port %d: %v", port, err)
×
2863
                }
×
2864
        }
2865
}
2866

2867
// watchExternalIP continuously checks for an updated external IP address every
2868
// 15 minutes. Once a new IP address has been detected, it will automatically
2869
// handle port forwarding rules and send updated node announcements to the
2870
// currently connected peers.
2871
//
2872
// NOTE: This MUST be run as a goroutine.
2873
func (s *server) watchExternalIP() {
×
2874
        defer s.wg.Done()
×
2875

×
2876
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2877
        // up by the server.
×
2878
        defer s.removePortForwarding()
×
2879

×
2880
        // Keep track of the external IPs set by the user to avoid replacing
×
2881
        // them when detecting a new IP.
×
2882
        ipsSetByUser := make(map[string]struct{})
×
2883
        for _, ip := range s.cfg.ExternalIPs {
×
2884
                ipsSetByUser[ip.String()] = struct{}{}
×
2885
        }
×
2886

2887
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2888

×
2889
        ticker := time.NewTicker(15 * time.Minute)
×
2890
        defer ticker.Stop()
×
2891
out:
×
2892
        for {
×
2893
                select {
×
2894
                case <-ticker.C:
×
2895
                        // We'll start off by making sure a new IP address has
×
2896
                        // been detected.
×
2897
                        ip, err := s.natTraversal.ExternalIP()
×
2898
                        if err != nil {
×
2899
                                srvrLog.Debugf("Unable to retrieve the "+
×
2900
                                        "external IP address: %v", err)
×
2901
                                continue
×
2902
                        }
2903

2904
                        // Periodically renew the NAT port forwarding.
2905
                        for _, port := range forwardedPorts {
×
2906
                                err := s.natTraversal.AddPortMapping(port)
×
2907
                                if err != nil {
×
2908
                                        srvrLog.Warnf("Unable to automatically "+
×
2909
                                                "re-create port forwarding using %s: %v",
×
2910
                                                s.natTraversal.Name(), err)
×
2911
                                } else {
×
2912
                                        srvrLog.Debugf("Automatically re-created "+
×
2913
                                                "forwarding for port %d using %s to "+
×
2914
                                                "advertise external IP",
×
2915
                                                port, s.natTraversal.Name())
×
2916
                                }
×
2917
                        }
2918

2919
                        if ip.Equal(s.lastDetectedIP) {
×
2920
                                continue
×
2921
                        }
2922

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

×
2925
                        // Next, we'll craft the new addresses that will be
×
2926
                        // included in the new node announcement and advertised
×
2927
                        // to the network. Each address will consist of the new
×
2928
                        // IP detected and one of the currently advertised
×
2929
                        // ports.
×
2930
                        var newAddrs []net.Addr
×
2931
                        for _, port := range forwardedPorts {
×
2932
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2933
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2934
                                if err != nil {
×
2935
                                        srvrLog.Debugf("Unable to resolve "+
×
2936
                                                "host %v: %v", addr, err)
×
2937
                                        continue
×
2938
                                }
2939

2940
                                newAddrs = append(newAddrs, addr)
×
2941
                        }
2942

2943
                        // Skip the update if we weren't able to resolve any of
2944
                        // the new addresses.
2945
                        if len(newAddrs) == 0 {
×
2946
                                srvrLog.Debug("Skipping node announcement " +
×
2947
                                        "update due to not being able to " +
×
2948
                                        "resolve any new addresses")
×
2949
                                continue
×
2950
                        }
2951

2952
                        // Now, we'll need to update the addresses in our node's
2953
                        // announcement in order to propagate the update
2954
                        // throughout the network. We'll only include addresses
2955
                        // that have a different IP from the previous one, as
2956
                        // the previous IP is no longer valid.
2957
                        currentNodeAnn := s.getNodeAnnouncement()
×
2958

×
2959
                        for _, addr := range currentNodeAnn.Addresses {
×
2960
                                host, _, err := net.SplitHostPort(addr.String())
×
2961
                                if err != nil {
×
2962
                                        srvrLog.Debugf("Unable to determine "+
×
2963
                                                "host from address %v: %v",
×
2964
                                                addr, err)
×
2965
                                        continue
×
2966
                                }
2967

2968
                                // We'll also make sure to include external IPs
2969
                                // set manually by the user.
2970
                                _, setByUser := ipsSetByUser[addr.String()]
×
2971
                                if setByUser || host != s.lastDetectedIP.String() {
×
2972
                                        newAddrs = append(newAddrs, addr)
×
2973
                                }
×
2974
                        }
2975

2976
                        // Then, we'll generate a new timestamped node
2977
                        // announcement with the updated addresses and broadcast
2978
                        // it to our peers.
2979
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2980
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2981
                        )
×
2982
                        if err != nil {
×
2983
                                srvrLog.Debugf("Unable to generate new node "+
×
2984
                                        "announcement: %v", err)
×
2985
                                continue
×
2986
                        }
2987

2988
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2989
                        if err != nil {
×
2990
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2991
                                        "announcement to peers: %v", err)
×
2992
                                continue
×
2993
                        }
2994

2995
                        // Finally, update the last IP seen to the current one.
2996
                        s.lastDetectedIP = ip
×
2997
                case <-s.quit:
×
2998
                        break out
×
2999
                }
3000
        }
3001
}
3002

3003
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3004
// based on the server, and currently active bootstrap mechanisms as defined
3005
// within the current configuration.
3006
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3007
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3008

×
3009
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3010

×
3011
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3012
        // this can be used by default if we've already partially seeded the
×
3013
        // network.
×
3014
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3015
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3016
        if err != nil {
×
3017
                return nil, err
×
3018
        }
×
3019
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3020

×
3021
        // If this isn't simnet mode, then one of our additional bootstrapping
×
3022
        // sources will be the set of running DNS seeds.
×
3023
        if !s.cfg.Bitcoin.SimNet {
×
3024
                dnsSeeds, ok := chainreg.ChainDNSSeeds[*s.cfg.ActiveNetParams.GenesisHash]
×
3025

×
3026
                // If we have a set of DNS seeds for this chain, then we'll add
×
3027
                // it as an additional bootstrapping source.
×
3028
                if ok {
×
3029
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3030
                                "seeds: %v", dnsSeeds)
×
3031

×
3032
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3033
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3034
                        )
×
3035
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3036
                }
×
3037
        }
3038

3039
        return bootStrappers, nil
×
3040
}
3041

3042
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3043
// needs to ignore, which is made of three parts,
3044
//   - the node itself needs to be skipped as it doesn't make sense to connect
3045
//     to itself.
3046
//   - the peers that already have connections with, as in s.peersByPub.
3047
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3048
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3049
        s.mu.RLock()
×
3050
        defer s.mu.RUnlock()
×
3051

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

×
3054
        // We should ignore ourselves from bootstrapping.
×
3055
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3056
        ignore[selfKey] = struct{}{}
×
3057

×
3058
        // Ignore all connected peers.
×
3059
        for _, peer := range s.peersByPub {
×
3060
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3061
                ignore[nID] = struct{}{}
×
3062
        }
×
3063

3064
        // Ignore all persistent peers as they have a dedicated reconnecting
3065
        // process.
3066
        for pubKeyStr := range s.persistentPeers {
×
3067
                var nID autopilot.NodeID
×
3068
                copy(nID[:], []byte(pubKeyStr))
×
3069
                ignore[nID] = struct{}{}
×
3070
        }
×
3071

3072
        return ignore
×
3073
}
3074

3075
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3076
// and maintain a target minimum number of outbound connections. With this
3077
// invariant, we ensure that our node is connected to a diverse set of peers
3078
// and that nodes newly joining the network receive an up to date network view
3079
// as soon as possible.
3080
func (s *server) peerBootstrapper(numTargetPeers uint32,
3081
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3082

×
3083
        defer s.wg.Done()
×
3084

×
3085
        // Before we continue, init the ignore peers map.
×
3086
        ignoreList := s.createBootstrapIgnorePeers()
×
3087

×
3088
        // We'll start off by aggressively attempting connections to peers in
×
3089
        // order to be a part of the network as soon as possible.
×
3090
        s.initialPeerBootstrap(ignoreList, numTargetPeers, bootstrappers)
×
3091

×
3092
        // Once done, we'll attempt to maintain our target minimum number of
×
3093
        // peers.
×
3094
        //
×
3095
        // We'll use a 15 second backoff, and double the time every time an
×
3096
        // epoch fails up to a ceiling.
×
3097
        backOff := time.Second * 15
×
3098

×
3099
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3100
        // see if we've reached our minimum number of peers.
×
3101
        sampleTicker := time.NewTicker(backOff)
×
3102
        defer sampleTicker.Stop()
×
3103

×
3104
        // We'll use the number of attempts and errors to determine if we need
×
3105
        // to increase the time between discovery epochs.
×
3106
        var epochErrors uint32 // To be used atomically.
×
3107
        var epochAttempts uint32
×
3108

×
3109
        for {
×
3110
                select {
×
3111
                // The ticker has just woken us up, so we'll need to check if
3112
                // we need to attempt to connect our to any more peers.
3113
                case <-sampleTicker.C:
×
3114
                        // Obtain the current number of peers, so we can gauge
×
3115
                        // if we need to sample more peers or not.
×
3116
                        s.mu.RLock()
×
3117
                        numActivePeers := uint32(len(s.peersByPub))
×
3118
                        s.mu.RUnlock()
×
3119

×
3120
                        // If we have enough peers, then we can loop back
×
3121
                        // around to the next round as we're done here.
×
3122
                        if numActivePeers >= numTargetPeers {
×
3123
                                continue
×
3124
                        }
3125

3126
                        // If all of our attempts failed during this last back
3127
                        // off period, then will increase our backoff to 5
3128
                        // minute ceiling to avoid an excessive number of
3129
                        // queries
3130
                        //
3131
                        // TODO(roasbeef): add reverse policy too?
3132

3133
                        if epochAttempts > 0 &&
×
3134
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3135

×
3136
                                sampleTicker.Stop()
×
3137

×
3138
                                backOff *= 2
×
3139
                                if backOff > bootstrapBackOffCeiling {
×
3140
                                        backOff = bootstrapBackOffCeiling
×
3141
                                }
×
3142

3143
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3144
                                        "%v", backOff)
×
3145
                                sampleTicker = time.NewTicker(backOff)
×
3146
                                continue
×
3147
                        }
3148

3149
                        atomic.StoreUint32(&epochErrors, 0)
×
3150
                        epochAttempts = 0
×
3151

×
3152
                        // Since we know need more peers, we'll compute the
×
3153
                        // exact number we need to reach our threshold.
×
3154
                        numNeeded := numTargetPeers - numActivePeers
×
3155

×
3156
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3157
                                "peers", numNeeded)
×
3158

×
3159
                        // With the number of peers we need calculated, we'll
×
3160
                        // query the network bootstrappers to sample a set of
×
3161
                        // random addrs for us.
×
3162
                        //
×
3163
                        // Before we continue, get a copy of the ignore peers
×
3164
                        // map.
×
3165
                        ignoreList = s.createBootstrapIgnorePeers()
×
3166

×
3167
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3168
                                ignoreList, numNeeded*2, bootstrappers...,
×
3169
                        )
×
3170
                        if err != nil {
×
3171
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3172
                                        "peers: %v", err)
×
3173
                                continue
×
3174
                        }
3175

3176
                        // Finally, we'll launch a new goroutine for each
3177
                        // prospective peer candidates.
3178
                        for _, addr := range peerAddrs {
×
3179
                                epochAttempts++
×
3180

×
3181
                                go func(a *lnwire.NetAddress) {
×
3182
                                        // TODO(roasbeef): can do AS, subnet,
×
3183
                                        // country diversity, etc
×
3184
                                        errChan := make(chan error, 1)
×
3185
                                        s.connectToPeer(
×
3186
                                                a, errChan,
×
3187
                                                s.cfg.ConnectionTimeout,
×
3188
                                        )
×
3189
                                        select {
×
3190
                                        case err := <-errChan:
×
3191
                                                if err == nil {
×
3192
                                                        return
×
3193
                                                }
×
3194

3195
                                                srvrLog.Errorf("Unable to "+
×
3196
                                                        "connect to %v: %v",
×
3197
                                                        a, err)
×
3198
                                                atomic.AddUint32(&epochErrors, 1)
×
3199
                                        case <-s.quit:
×
3200
                                        }
3201
                                }(addr)
3202
                        }
3203
                case <-s.quit:
×
3204
                        return
×
3205
                }
3206
        }
3207
}
3208

3209
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3210
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3211
// query back off each time we encounter a failure.
3212
const bootstrapBackOffCeiling = time.Minute * 5
3213

3214
// initialPeerBootstrap attempts to continuously connect to peers on startup
3215
// until the target number of peers has been reached. This ensures that nodes
3216
// receive an up to date network view as soon as possible.
3217
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3218
        numTargetPeers uint32,
3219
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3220

×
3221
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3222
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3223

×
3224
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3225
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3226
        var delaySignal <-chan time.Time
×
3227
        delayTime := time.Second * 2
×
3228

×
3229
        // As want to be more aggressive, we'll use a lower back off celling
×
3230
        // then the main peer bootstrap logic.
×
3231
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3232

×
3233
        for attempts := 0; ; attempts++ {
×
3234
                // Check if the server has been requested to shut down in order
×
3235
                // to prevent blocking.
×
3236
                if s.Stopped() {
×
3237
                        return
×
3238
                }
×
3239

3240
                // We can exit our aggressive initial peer bootstrapping stage
3241
                // if we've reached out target number of peers.
3242
                s.mu.RLock()
×
3243
                numActivePeers := uint32(len(s.peersByPub))
×
3244
                s.mu.RUnlock()
×
3245

×
3246
                if numActivePeers >= numTargetPeers {
×
3247
                        return
×
3248
                }
×
3249

3250
                if attempts > 0 {
×
3251
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3252
                                "bootstrap peers (attempt #%v)", delayTime,
×
3253
                                attempts)
×
3254

×
3255
                        // We've completed at least one iterating and haven't
×
3256
                        // finished, so we'll start to insert a delay period
×
3257
                        // between each attempt.
×
3258
                        delaySignal = time.After(delayTime)
×
3259
                        select {
×
3260
                        case <-delaySignal:
×
3261
                        case <-s.quit:
×
3262
                                return
×
3263
                        }
3264

3265
                        // After our delay, we'll double the time we wait up to
3266
                        // the max back off period.
3267
                        delayTime *= 2
×
3268
                        if delayTime > backOffCeiling {
×
3269
                                delayTime = backOffCeiling
×
3270
                        }
×
3271
                }
3272

3273
                // Otherwise, we'll request for the remaining number of peers
3274
                // in order to reach our target.
3275
                peersNeeded := numTargetPeers - numActivePeers
×
3276
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3277
                        ignore, peersNeeded, bootstrappers...,
×
3278
                )
×
3279
                if err != nil {
×
3280
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3281
                                "peers: %v", err)
×
3282
                        continue
×
3283
                }
3284

3285
                // Then, we'll attempt to establish a connection to the
3286
                // different peer addresses retrieved by our bootstrappers.
3287
                var wg sync.WaitGroup
×
3288
                for _, bootstrapAddr := range bootstrapAddrs {
×
3289
                        wg.Add(1)
×
3290
                        go func(addr *lnwire.NetAddress) {
×
3291
                                defer wg.Done()
×
3292

×
3293
                                errChan := make(chan error, 1)
×
3294
                                go s.connectToPeer(
×
3295
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3296
                                )
×
3297

×
3298
                                // We'll only allow this connection attempt to
×
3299
                                // take up to 3 seconds. This allows us to move
×
3300
                                // quickly by discarding peers that are slowing
×
3301
                                // us down.
×
3302
                                select {
×
3303
                                case err := <-errChan:
×
3304
                                        if err == nil {
×
3305
                                                return
×
3306
                                        }
×
3307
                                        srvrLog.Errorf("Unable to connect to "+
×
3308
                                                "%v: %v", addr, err)
×
3309
                                // TODO: tune timeout? 3 seconds might be *too*
3310
                                // aggressive but works well.
3311
                                case <-time.After(3 * time.Second):
×
3312
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3313
                                                "to not establishing a "+
×
3314
                                                "connection within 3 seconds",
×
3315
                                                addr)
×
3316
                                case <-s.quit:
×
3317
                                }
3318
                        }(bootstrapAddr)
3319
                }
3320

3321
                wg.Wait()
×
3322
        }
3323
}
3324

3325
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3326
// order to listen for inbound connections over Tor.
3327
func (s *server) createNewHiddenService() error {
×
3328
        // Determine the different ports the server is listening on. The onion
×
3329
        // service's virtual port will map to these ports and one will be picked
×
3330
        // at random when the onion service is being accessed.
×
3331
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3332
        for _, listenAddr := range s.listenAddrs {
×
3333
                port := listenAddr.(*net.TCPAddr).Port
×
3334
                listenPorts = append(listenPorts, port)
×
3335
        }
×
3336

3337
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3338
        if err != nil {
×
3339
                return err
×
3340
        }
×
3341

3342
        // Once the port mapping has been set, we can go ahead and automatically
3343
        // create our onion service. The service's private key will be saved to
3344
        // disk in order to regain access to this service when restarting `lnd`.
3345
        onionCfg := tor.AddOnionConfig{
×
3346
                VirtualPort: defaultPeerPort,
×
3347
                TargetPorts: listenPorts,
×
3348
                Store: tor.NewOnionFile(
×
3349
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3350
                        encrypter,
×
3351
                ),
×
3352
        }
×
3353

×
3354
        switch {
×
3355
        case s.cfg.Tor.V2:
×
3356
                onionCfg.Type = tor.V2
×
3357
        case s.cfg.Tor.V3:
×
3358
                onionCfg.Type = tor.V3
×
3359
        }
3360

3361
        addr, err := s.torController.AddOnion(onionCfg)
×
3362
        if err != nil {
×
3363
                return err
×
3364
        }
×
3365

3366
        // Now that the onion service has been created, we'll add the onion
3367
        // address it can be reached at to our list of advertised addresses.
3368
        newNodeAnn, err := s.genNodeAnnouncement(
×
3369
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3370
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3371
                },
×
3372
        )
3373
        if err != nil {
×
3374
                return fmt.Errorf("unable to generate new node "+
×
3375
                        "announcement: %v", err)
×
3376
        }
×
3377

3378
        // Finally, we'll update the on-disk version of our announcement so it
3379
        // will eventually propagate to nodes in the network.
3380
        selfNode := &models.LightningNode{
×
3381
                HaveNodeAnnouncement: true,
×
3382
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3383
                Addresses:            newNodeAnn.Addresses,
×
3384
                Alias:                newNodeAnn.Alias.String(),
×
3385
                Features: lnwire.NewFeatureVector(
×
3386
                        newNodeAnn.Features, lnwire.Features,
×
3387
                ),
×
3388
                Color:        newNodeAnn.RGBColor,
×
3389
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3390
        }
×
3391
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3392
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3393
                return fmt.Errorf("can't set self node: %w", err)
×
3394
        }
×
3395

3396
        return nil
×
3397
}
3398

3399
// findChannel finds a channel given a public key and ChannelID. It is an
3400
// optimization that is quicker than seeking for a channel given only the
3401
// ChannelID.
3402
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3403
        *channeldb.OpenChannel, error) {
1✔
3404

1✔
3405
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
1✔
3406
        if err != nil {
1✔
3407
                return nil, err
×
3408
        }
×
3409

3410
        for _, channel := range nodeChans {
2✔
3411
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
2✔
3412
                        return channel, nil
1✔
3413
                }
1✔
3414
        }
3415

3416
        return nil, fmt.Errorf("unable to find channel")
1✔
3417
}
3418

3419
// getNodeAnnouncement fetches the current, fully signed node announcement.
3420
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
1✔
3421
        s.mu.Lock()
1✔
3422
        defer s.mu.Unlock()
1✔
3423

1✔
3424
        return *s.currentNodeAnn
1✔
3425
}
1✔
3426

3427
// genNodeAnnouncement generates and returns the current fully signed node
3428
// announcement. The time stamp of the announcement will be updated in order
3429
// to ensure it propagates through the network.
3430
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3431
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
1✔
3432

1✔
3433
        s.mu.Lock()
1✔
3434
        defer s.mu.Unlock()
1✔
3435

1✔
3436
        // First, try to update our feature manager with the updated set of
1✔
3437
        // features.
1✔
3438
        if features != nil {
2✔
3439
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
1✔
3440
                        feature.SetNodeAnn: features,
1✔
3441
                }
1✔
3442
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
1✔
3443
                if err != nil {
2✔
3444
                        return lnwire.NodeAnnouncement{}, err
1✔
3445
                }
1✔
3446

3447
                // If we could successfully update our feature manager, add
3448
                // an update modifier to include these new features to our
3449
                // set.
3450
                modifiers = append(
1✔
3451
                        modifiers, netann.NodeAnnSetFeatures(features),
1✔
3452
                )
1✔
3453
        }
3454

3455
        // Always update the timestamp when refreshing to ensure the update
3456
        // propagates.
3457
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
1✔
3458

1✔
3459
        // Apply the requested changes to the node announcement.
1✔
3460
        for _, modifier := range modifiers {
2✔
3461
                modifier(s.currentNodeAnn)
1✔
3462
        }
1✔
3463

3464
        // Sign a new update after applying all of the passed modifiers.
3465
        err := netann.SignNodeAnnouncement(
1✔
3466
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
1✔
3467
        )
1✔
3468
        if err != nil {
1✔
3469
                return lnwire.NodeAnnouncement{}, err
×
3470
        }
×
3471

3472
        return *s.currentNodeAnn, nil
1✔
3473
}
3474

3475
// updateAndBroadcastSelfNode generates a new node announcement
3476
// applying the giving modifiers and updating the time stamp
3477
// to ensure it propagates through the network. Then it broadcasts
3478
// it to the network.
3479
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3480
        modifiers ...netann.NodeAnnModifier) error {
1✔
3481

1✔
3482
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
1✔
3483
        if err != nil {
2✔
3484
                return fmt.Errorf("unable to generate new node "+
1✔
3485
                        "announcement: %v", err)
1✔
3486
        }
1✔
3487

3488
        // Update the on-disk version of our announcement.
3489
        // Load and modify self node istead of creating anew instance so we
3490
        // don't risk overwriting any existing values.
3491
        selfNode, err := s.graphDB.SourceNode()
1✔
3492
        if err != nil {
1✔
3493
                return fmt.Errorf("unable to get current source node: %w", err)
×
3494
        }
×
3495

3496
        selfNode.HaveNodeAnnouncement = true
1✔
3497
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
1✔
3498
        selfNode.Addresses = newNodeAnn.Addresses
1✔
3499
        selfNode.Alias = newNodeAnn.Alias.String()
1✔
3500
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
1✔
3501
        selfNode.Color = newNodeAnn.RGBColor
1✔
3502
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
1✔
3503

1✔
3504
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
1✔
3505

1✔
3506
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
1✔
3507
                return fmt.Errorf("can't set self node: %w", err)
×
3508
        }
×
3509

3510
        // Finally, propagate it to the nodes in the network.
3511
        err = s.BroadcastMessage(nil, &newNodeAnn)
1✔
3512
        if err != nil {
1✔
3513
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3514
                        "announcement to peers: %v", err)
×
3515
                return err
×
3516
        }
×
3517

3518
        return nil
1✔
3519
}
3520

3521
type nodeAddresses struct {
3522
        pubKey    *btcec.PublicKey
3523
        addresses []net.Addr
3524
}
3525

3526
// establishPersistentConnections attempts to establish persistent connections
3527
// to all our direct channel collaborators. In order to promote liveness of our
3528
// active channels, we instruct the connection manager to attempt to establish
3529
// and maintain persistent connections to all our direct channel counterparties.
3530
func (s *server) establishPersistentConnections() error {
1✔
3531
        // nodeAddrsMap stores the combination of node public keys and addresses
1✔
3532
        // that we'll attempt to reconnect to. PubKey strings are used as keys
1✔
3533
        // since other PubKey forms can't be compared.
1✔
3534
        nodeAddrsMap := map[string]*nodeAddresses{}
1✔
3535

1✔
3536
        // Iterate through the list of LinkNodes to find addresses we should
1✔
3537
        // attempt to connect to based on our set of previous connections. Set
1✔
3538
        // the reconnection port to the default peer port.
1✔
3539
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
1✔
3540
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
1✔
3541
                return fmt.Errorf("failed to fetch all link nodes: %w", err)
×
3542
        }
×
3543

3544
        for _, node := range linkNodes {
2✔
3545
                pubStr := string(node.IdentityPub.SerializeCompressed())
1✔
3546
                nodeAddrs := &nodeAddresses{
1✔
3547
                        pubKey:    node.IdentityPub,
1✔
3548
                        addresses: node.Addresses,
1✔
3549
                }
1✔
3550
                nodeAddrsMap[pubStr] = nodeAddrs
1✔
3551
        }
1✔
3552

3553
        // After checking our previous connections for addresses to connect to,
3554
        // iterate through the nodes in our channel graph to find addresses
3555
        // that have been added via NodeAnnouncement messages.
3556
        sourceNode, err := s.graphDB.SourceNode()
1✔
3557
        if err != nil {
1✔
3558
                return fmt.Errorf("failed to fetch source node: %w", err)
×
3559
        }
×
3560

3561
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3562
        // each of the nodes.
3563
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
1✔
3564
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
1✔
3565
                tx kvdb.RTx,
1✔
3566
                chanInfo *models.ChannelEdgeInfo,
1✔
3567
                policy, _ *models.ChannelEdgePolicy) error {
2✔
3568

1✔
3569
                // If the remote party has announced the channel to us, but we
1✔
3570
                // haven't yet, then we won't have a policy. However, we don't
1✔
3571
                // need this to connect to the peer, so we'll log it and move on.
1✔
3572
                if policy == nil {
1✔
3573
                        srvrLog.Warnf("No channel policy found for "+
×
3574
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3575
                }
×
3576

3577
                // We'll now fetch the peer opposite from us within this
3578
                // channel so we can queue up a direct connection to them.
3579
                channelPeer, err := s.graphDB.FetchOtherNode(
1✔
3580
                        tx, chanInfo, selfPub,
1✔
3581
                )
1✔
3582
                if err != nil {
1✔
3583
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3584
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3585
                                err)
×
3586
                }
×
3587

3588
                pubStr := string(channelPeer.PubKeyBytes[:])
1✔
3589

1✔
3590
                // Add all unique addresses from channel
1✔
3591
                // graph/NodeAnnouncements to the list of addresses we'll
1✔
3592
                // connect to for this peer.
1✔
3593
                addrSet := make(map[string]net.Addr)
1✔
3594
                for _, addr := range channelPeer.Addresses {
2✔
3595
                        switch addr.(type) {
1✔
3596
                        case *net.TCPAddr:
1✔
3597
                                addrSet[addr.String()] = addr
1✔
3598

3599
                        // We'll only attempt to connect to Tor addresses if Tor
3600
                        // outbound support is enabled.
3601
                        case *tor.OnionAddr:
×
3602
                                if s.cfg.Tor.Active {
×
3603
                                        addrSet[addr.String()] = addr
×
3604
                                }
×
3605
                        }
3606
                }
3607

3608
                // If this peer is also recorded as a link node, we'll add any
3609
                // additional addresses that have not already been selected.
3610
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
1✔
3611
                if ok {
2✔
3612
                        for _, lnAddress := range linkNodeAddrs.addresses {
2✔
3613
                                switch lnAddress.(type) {
1✔
3614
                                case *net.TCPAddr:
1✔
3615
                                        addrSet[lnAddress.String()] = lnAddress
1✔
3616

3617
                                // We'll only attempt to connect to Tor
3618
                                // addresses if Tor outbound support is enabled.
3619
                                case *tor.OnionAddr:
×
3620
                                        if s.cfg.Tor.Active {
×
3621
                                                addrSet[lnAddress.String()] = lnAddress
×
3622
                                        }
×
3623
                                }
3624
                        }
3625
                }
3626

3627
                // Construct a slice of the deduped addresses.
3628
                var addrs []net.Addr
1✔
3629
                for _, addr := range addrSet {
2✔
3630
                        addrs = append(addrs, addr)
1✔
3631
                }
1✔
3632

3633
                n := &nodeAddresses{
1✔
3634
                        addresses: addrs,
1✔
3635
                }
1✔
3636
                n.pubKey, err = channelPeer.PubKey()
1✔
3637
                if err != nil {
1✔
3638
                        return err
×
3639
                }
×
3640

3641
                nodeAddrsMap[pubStr] = n
1✔
3642
                return nil
1✔
3643
        })
3644
        if err != nil {
1✔
3645
                srvrLog.Errorf("Failed to iterate channels for node %x",
×
3646
                        sourceNode.PubKeyBytes)
×
3647

×
3648
                if !errors.Is(err, graphdb.ErrGraphNoEdgesFound) &&
×
3649
                        !errors.Is(err, graphdb.ErrEdgeNotFound) {
×
3650

×
3651
                        return err
×
3652
                }
×
3653
        }
3654

3655
        srvrLog.Debugf("Establishing %v persistent connections on start",
1✔
3656
                len(nodeAddrsMap))
1✔
3657

1✔
3658
        // Acquire and hold server lock until all persistent connection requests
1✔
3659
        // have been recorded and sent to the connection manager.
1✔
3660
        s.mu.Lock()
1✔
3661
        defer s.mu.Unlock()
1✔
3662

1✔
3663
        // Iterate through the combined list of addresses from prior links and
1✔
3664
        // node announcements and attempt to reconnect to each node.
1✔
3665
        var numOutboundConns int
1✔
3666
        for pubStr, nodeAddr := range nodeAddrsMap {
2✔
3667
                // Add this peer to the set of peers we should maintain a
1✔
3668
                // persistent connection with. We set the value to false to
1✔
3669
                // indicate that we should not continue to reconnect if the
1✔
3670
                // number of channels returns to zero, since this peer has not
1✔
3671
                // been requested as perm by the user.
1✔
3672
                s.persistentPeers[pubStr] = false
1✔
3673
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
2✔
3674
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
1✔
3675
                }
1✔
3676

3677
                for _, address := range nodeAddr.addresses {
2✔
3678
                        // Create a wrapper address which couples the IP and
1✔
3679
                        // the pubkey so the brontide authenticated connection
1✔
3680
                        // can be established.
1✔
3681
                        lnAddr := &lnwire.NetAddress{
1✔
3682
                                IdentityKey: nodeAddr.pubKey,
1✔
3683
                                Address:     address,
1✔
3684
                        }
1✔
3685

1✔
3686
                        s.persistentPeerAddrs[pubStr] = append(
1✔
3687
                                s.persistentPeerAddrs[pubStr], lnAddr)
1✔
3688
                }
1✔
3689

3690
                // We'll connect to the first 10 peers immediately, then
3691
                // randomly stagger any remaining connections if the
3692
                // stagger initial reconnect flag is set. This ensures
3693
                // that mobile nodes or nodes with a small number of
3694
                // channels obtain connectivity quickly, but larger
3695
                // nodes are able to disperse the costs of connecting to
3696
                // all peers at once.
3697
                if numOutboundConns < numInstantInitReconnect ||
1✔
3698
                        !s.cfg.StaggerInitialReconnect {
2✔
3699

1✔
3700
                        go s.connectToPersistentPeer(pubStr)
1✔
3701
                } else {
1✔
3702
                        go s.delayInitialReconnect(pubStr)
×
3703
                }
×
3704

3705
                numOutboundConns++
1✔
3706
        }
3707

3708
        return nil
1✔
3709
}
3710

3711
// delayInitialReconnect will attempt a reconnection to the given peer after
3712
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3713
//
3714
// NOTE: This method MUST be run as a goroutine.
3715
func (s *server) delayInitialReconnect(pubStr string) {
×
3716
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3717
        select {
×
3718
        case <-time.After(delay):
×
3719
                s.connectToPersistentPeer(pubStr)
×
3720
        case <-s.quit:
×
3721
        }
3722
}
3723

3724
// prunePersistentPeerConnection removes all internal state related to
3725
// persistent connections to a peer within the server. This is used to avoid
3726
// persistent connection retries to peers we do not have any open channels with.
3727
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
1✔
3728
        pubKeyStr := string(compressedPubKey[:])
1✔
3729

1✔
3730
        s.mu.Lock()
1✔
3731
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
2✔
3732
                delete(s.persistentPeers, pubKeyStr)
1✔
3733
                delete(s.persistentPeersBackoff, pubKeyStr)
1✔
3734
                delete(s.persistentPeerAddrs, pubKeyStr)
1✔
3735
                s.cancelConnReqs(pubKeyStr, nil)
1✔
3736
                s.mu.Unlock()
1✔
3737

1✔
3738
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
1✔
3739
                        "peer has no open channels", compressedPubKey)
1✔
3740

1✔
3741
                return
1✔
3742
        }
1✔
3743
        s.mu.Unlock()
1✔
3744
}
3745

3746
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3747
// is instead used to remove persistent peer state for a peer that has been
3748
// disconnected for good cause by the server. Currently, a gossip ban from
3749
// sending garbage and the server running out of restricted-access
3750
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3751
// future, this function may expand when more ban criteria is added.
3752
//
3753
// NOTE: The server's write lock MUST be held when this is called.
3754
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3755
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3756
                delete(s.persistentPeers, remotePub)
×
3757
                delete(s.persistentPeersBackoff, remotePub)
×
3758
                delete(s.persistentPeerAddrs, remotePub)
×
3759
                s.cancelConnReqs(remotePub, nil)
×
3760
        }
×
3761
}
3762

3763
// BroadcastMessage sends a request to the server to broadcast a set of
3764
// messages to all peers other than the one specified by the `skips` parameter.
3765
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3766
// the target peers.
3767
//
3768
// NOTE: This function is safe for concurrent access.
3769
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3770
        msgs ...lnwire.Message) error {
1✔
3771

1✔
3772
        // Filter out peers found in the skips map. We synchronize access to
1✔
3773
        // peersByPub throughout this process to ensure we deliver messages to
1✔
3774
        // exact set of peers present at the time of invocation.
1✔
3775
        s.mu.RLock()
1✔
3776
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
1✔
3777
        for pubStr, sPeer := range s.peersByPub {
2✔
3778
                if skips != nil {
2✔
3779
                        if _, ok := skips[sPeer.PubKey()]; ok {
2✔
3780
                                srvrLog.Tracef("Skipping %x in broadcast with "+
1✔
3781
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
1✔
3782
                                continue
1✔
3783
                        }
3784
                }
3785

3786
                peers = append(peers, sPeer)
1✔
3787
        }
3788
        s.mu.RUnlock()
1✔
3789

1✔
3790
        // Iterate over all known peers, dispatching a go routine to enqueue
1✔
3791
        // all messages to each of peers.
1✔
3792
        var wg sync.WaitGroup
1✔
3793
        for _, sPeer := range peers {
2✔
3794
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
1✔
3795
                        sPeer.PubKey())
1✔
3796

1✔
3797
                // Dispatch a go routine to enqueue all messages to this peer.
1✔
3798
                wg.Add(1)
1✔
3799
                s.wg.Add(1)
1✔
3800
                go func(p lnpeer.Peer) {
2✔
3801
                        defer s.wg.Done()
1✔
3802
                        defer wg.Done()
1✔
3803

1✔
3804
                        p.SendMessageLazy(false, msgs...)
1✔
3805
                }(sPeer)
1✔
3806
        }
3807

3808
        // Wait for all messages to have been dispatched before returning to
3809
        // caller.
3810
        wg.Wait()
1✔
3811

1✔
3812
        return nil
1✔
3813
}
3814

3815
// NotifyWhenOnline can be called by other subsystems to get notified when a
3816
// particular peer comes online. The peer itself is sent across the peerChan.
3817
//
3818
// NOTE: This function is safe for concurrent access.
3819
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3820
        peerChan chan<- lnpeer.Peer) {
1✔
3821

1✔
3822
        s.mu.Lock()
1✔
3823

1✔
3824
        // Compute the target peer's identifier.
1✔
3825
        pubStr := string(peerKey[:])
1✔
3826

1✔
3827
        // Check if peer is connected.
1✔
3828
        peer, ok := s.peersByPub[pubStr]
1✔
3829
        if ok {
2✔
3830
                // Unlock here so that the mutex isn't held while we are
1✔
3831
                // waiting for the peer to become active.
1✔
3832
                s.mu.Unlock()
1✔
3833

1✔
3834
                // Wait until the peer signals that it is actually active
1✔
3835
                // rather than only in the server's maps.
1✔
3836
                select {
1✔
3837
                case <-peer.ActiveSignal():
1✔
UNCOV
3838
                case <-peer.QuitSignal():
×
UNCOV
3839
                        // The peer quit, so we'll add the channel to the slice
×
UNCOV
3840
                        // and return.
×
UNCOV
3841
                        s.mu.Lock()
×
UNCOV
3842
                        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3843
                                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3844
                        )
×
UNCOV
3845
                        s.mu.Unlock()
×
UNCOV
3846
                        return
×
3847
                }
3848

3849
                // Connected, can return early.
3850
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
1✔
3851

1✔
3852
                select {
1✔
3853
                case peerChan <- peer:
1✔
3854
                case <-s.quit:
×
3855
                }
3856

3857
                return
1✔
3858
        }
3859

3860
        // Not connected, store this listener such that it can be notified when
3861
        // the peer comes online.
3862
        s.peerConnectedListeners[pubStr] = append(
1✔
3863
                s.peerConnectedListeners[pubStr], peerChan,
1✔
3864
        )
1✔
3865
        s.mu.Unlock()
1✔
3866
}
3867

3868
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3869
// the given public key has been disconnected. The notification is signaled by
3870
// closing the channel returned.
3871
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
1✔
3872
        s.mu.Lock()
1✔
3873
        defer s.mu.Unlock()
1✔
3874

1✔
3875
        c := make(chan struct{})
1✔
3876

1✔
3877
        // If the peer is already offline, we can immediately trigger the
1✔
3878
        // notification.
1✔
3879
        peerPubKeyStr := string(peerPubKey[:])
1✔
3880
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
1✔
3881
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3882
                close(c)
×
3883
                return c
×
3884
        }
×
3885

3886
        // Otherwise, the peer is online, so we'll keep track of the channel to
3887
        // trigger the notification once the server detects the peer
3888
        // disconnects.
3889
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
1✔
3890
                s.peerDisconnectedListeners[peerPubKeyStr], c,
1✔
3891
        )
1✔
3892

1✔
3893
        return c
1✔
3894
}
3895

3896
// FindPeer will return the peer that corresponds to the passed in public key.
3897
// This function is used by the funding manager, allowing it to update the
3898
// daemon's local representation of the remote peer.
3899
//
3900
// NOTE: This function is safe for concurrent access.
3901
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
1✔
3902
        s.mu.RLock()
1✔
3903
        defer s.mu.RUnlock()
1✔
3904

1✔
3905
        pubStr := string(peerKey.SerializeCompressed())
1✔
3906

1✔
3907
        return s.findPeerByPubStr(pubStr)
1✔
3908
}
1✔
3909

3910
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3911
// which should be a string representation of the peer's serialized, compressed
3912
// public key.
3913
//
3914
// NOTE: This function is safe for concurrent access.
3915
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
1✔
3916
        s.mu.RLock()
1✔
3917
        defer s.mu.RUnlock()
1✔
3918

1✔
3919
        return s.findPeerByPubStr(pubStr)
1✔
3920
}
1✔
3921

3922
// findPeerByPubStr is an internal method that retrieves the specified peer from
3923
// the server's internal state using.
3924
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
1✔
3925
        peer, ok := s.peersByPub[pubStr]
1✔
3926
        if !ok {
2✔
3927
                return nil, ErrPeerNotConnected
1✔
3928
        }
1✔
3929

3930
        return peer, nil
1✔
3931
}
3932

3933
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3934
// exponential backoff. If no previous backoff was known, the default is
3935
// returned.
3936
func (s *server) nextPeerBackoff(pubStr string,
3937
        startTime time.Time) time.Duration {
1✔
3938

1✔
3939
        // Now, determine the appropriate backoff to use for the retry.
1✔
3940
        backoff, ok := s.persistentPeersBackoff[pubStr]
1✔
3941
        if !ok {
2✔
3942
                // If an existing backoff was unknown, use the default.
1✔
3943
                return s.cfg.MinBackoff
1✔
3944
        }
1✔
3945

3946
        // If the peer failed to start properly, we'll just use the previous
3947
        // backoff to compute the subsequent randomized exponential backoff
3948
        // duration. This will roughly double on average.
3949
        if startTime.IsZero() {
1✔
3950
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3951
        }
×
3952

3953
        // The peer succeeded in starting. If the connection didn't last long
3954
        // enough to be considered stable, we'll continue to back off retries
3955
        // with this peer.
3956
        connDuration := time.Since(startTime)
1✔
3957
        if connDuration < defaultStableConnDuration {
2✔
3958
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
1✔
3959
        }
1✔
3960

3961
        // The peer succeed in starting and this was stable peer, so we'll
3962
        // reduce the timeout duration by the length of the connection after
3963
        // applying randomized exponential backoff. We'll only apply this in the
3964
        // case that:
3965
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3966
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3967
        if relaxedBackoff > s.cfg.MinBackoff {
×
3968
                return relaxedBackoff
×
3969
        }
×
3970

3971
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3972
        // the stable connection lasted much longer than our previous backoff.
3973
        // To reward such good behavior, we'll reconnect after the default
3974
        // timeout.
3975
        return s.cfg.MinBackoff
×
3976
}
3977

3978
// shouldDropLocalConnection determines if our local connection to a remote peer
3979
// should be dropped in the case of concurrent connection establishment. In
3980
// order to deterministically decide which connection should be dropped, we'll
3981
// utilize the ordering of the local and remote public key. If we didn't use
3982
// such a tie breaker, then we risk _both_ connections erroneously being
3983
// dropped.
3984
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3985
        localPubBytes := local.SerializeCompressed()
×
3986
        remotePubPbytes := remote.SerializeCompressed()
×
3987

×
3988
        // The connection that comes from the node with a "smaller" pubkey
×
3989
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3990
        // should drop our established connection.
×
3991
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3992
}
×
3993

3994
// InboundPeerConnected initializes a new peer in response to a new inbound
3995
// connection.
3996
//
3997
// NOTE: This function is safe for concurrent access.
3998
func (s *server) InboundPeerConnected(conn net.Conn) {
1✔
3999
        // Exit early if we have already been instructed to shutdown, this
1✔
4000
        // prevents any delayed callbacks from accidentally registering peers.
1✔
4001
        if s.Stopped() {
1✔
4002
                return
×
4003
        }
×
4004

4005
        nodePub := conn.(*brontide.Conn).RemotePub()
1✔
4006
        pubSer := nodePub.SerializeCompressed()
1✔
4007
        pubStr := string(pubSer)
1✔
4008

1✔
4009
        var pubBytes [33]byte
1✔
4010
        copy(pubBytes[:], pubSer)
1✔
4011

1✔
4012
        s.mu.Lock()
1✔
4013
        defer s.mu.Unlock()
1✔
4014

1✔
4015
        // If the remote node's public key is banned, drop the connection.
1✔
4016
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
1✔
4017
        if err != nil {
1✔
4018
                // Clean up the persistent peer maps if we're dropping this
×
4019
                // connection.
×
4020
                s.bannedPersistentPeerConnection(pubStr)
×
4021

×
4022
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4023
                        "of restricted-access connection slots: %v.", pubSer,
×
4024
                        err)
×
4025

×
4026
                conn.Close()
×
4027

×
4028
                return
×
4029
        }
×
4030

4031
        // If we already have an outbound connection to this peer, then ignore
4032
        // this new connection.
4033
        if p, ok := s.outboundPeers[pubStr]; ok {
2✔
4034
                srvrLog.Debugf("Already have outbound connection for %v, "+
1✔
4035
                        "ignoring inbound connection from local=%v, remote=%v",
1✔
4036
                        p, conn.LocalAddr(), conn.RemoteAddr())
1✔
4037

1✔
4038
                conn.Close()
1✔
4039
                return
1✔
4040
        }
1✔
4041

4042
        // If we already have a valid connection that is scheduled to take
4043
        // precedence once the prior peer has finished disconnecting, we'll
4044
        // ignore this connection.
4045
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
1✔
4046
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4047
                        "scheduled", conn.RemoteAddr(), p)
×
4048
                conn.Close()
×
4049
                return
×
4050
        }
×
4051

4052
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
1✔
4053

1✔
4054
        // Check to see if we already have a connection with this peer. If so,
1✔
4055
        // we may need to drop our existing connection. This prevents us from
1✔
4056
        // having duplicate connections to the same peer. We forgo adding a
1✔
4057
        // default case as we expect these to be the only error values returned
1✔
4058
        // from findPeerByPubStr.
1✔
4059
        connectedPeer, err := s.findPeerByPubStr(pubStr)
1✔
4060
        switch err {
1✔
4061
        case ErrPeerNotConnected:
1✔
4062
                // We were unable to locate an existing connection with the
1✔
4063
                // target peer, proceed to connect.
1✔
4064
                s.cancelConnReqs(pubStr, nil)
1✔
4065
                s.peerConnected(conn, nil, true, access)
1✔
4066

4067
        case nil:
×
4068
                // We already have a connection with the incoming peer. If the
×
4069
                // connection we've already established should be kept and is
×
4070
                // not of the same type of the new connection (inbound), then
×
4071
                // we'll close out the new connection s.t there's only a single
×
4072
                // connection between us.
×
4073
                localPub := s.identityECDH.PubKey()
×
4074
                if !connectedPeer.Inbound() &&
×
4075
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4076

×
4077
                        srvrLog.Warnf("Received inbound connection from "+
×
4078
                                "peer %v, but already have outbound "+
×
4079
                                "connection, dropping conn", connectedPeer)
×
4080
                        conn.Close()
×
4081
                        return
×
4082
                }
×
4083

4084
                // Otherwise, if we should drop the connection, then we'll
4085
                // disconnect our already connected peer.
4086
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4087
                        connectedPeer)
×
4088

×
4089
                s.cancelConnReqs(pubStr, nil)
×
4090

×
4091
                // Remove the current peer from the server's internal state and
×
4092
                // signal that the peer termination watcher does not need to
×
4093
                // execute for this peer.
×
4094
                s.removePeer(connectedPeer)
×
4095
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4096
                s.scheduledPeerConnection[pubStr] = func() {
×
4097
                        s.peerConnected(conn, nil, true, access)
×
4098
                }
×
4099
        }
4100
}
4101

4102
// OutboundPeerConnected initializes a new peer in response to a new outbound
4103
// connection.
4104
// NOTE: This function is safe for concurrent access.
4105
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
1✔
4106
        // Exit early if we have already been instructed to shutdown, this
1✔
4107
        // prevents any delayed callbacks from accidentally registering peers.
1✔
4108
        if s.Stopped() {
1✔
4109
                return
×
4110
        }
×
4111

4112
        nodePub := conn.(*brontide.Conn).RemotePub()
1✔
4113
        pubSer := nodePub.SerializeCompressed()
1✔
4114
        pubStr := string(pubSer)
1✔
4115

1✔
4116
        var pubBytes [33]byte
1✔
4117
        copy(pubBytes[:], pubSer)
1✔
4118

1✔
4119
        s.mu.Lock()
1✔
4120
        defer s.mu.Unlock()
1✔
4121

1✔
4122
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
1✔
4123
        if err != nil {
1✔
4124
                // Clean up the persistent peer maps if we're dropping this
×
4125
                // connection.
×
4126
                s.bannedPersistentPeerConnection(pubStr)
×
4127

×
4128
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4129
                        "of restricted-access connection slots: %v.", pubSer,
×
4130
                        err)
×
4131

×
4132
                if connReq != nil {
×
4133
                        s.connMgr.Remove(connReq.ID())
×
4134
                }
×
4135

4136
                conn.Close()
×
4137

×
4138
                return
×
4139
        }
4140

4141
        // If we already have an inbound connection to this peer, then ignore
4142
        // this new connection.
4143
        if p, ok := s.inboundPeers[pubStr]; ok {
2✔
4144
                srvrLog.Debugf("Already have inbound connection for %v, "+
1✔
4145
                        "ignoring outbound connection from local=%v, remote=%v",
1✔
4146
                        p, conn.LocalAddr(), conn.RemoteAddr())
1✔
4147

1✔
4148
                if connReq != nil {
2✔
4149
                        s.connMgr.Remove(connReq.ID())
1✔
4150
                }
1✔
4151
                conn.Close()
1✔
4152
                return
1✔
4153
        }
4154
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
1✔
4155
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4156
                s.connMgr.Remove(connReq.ID())
×
4157
                conn.Close()
×
4158
                return
×
4159
        }
×
4160

4161
        // If we already have a valid connection that is scheduled to take
4162
        // precedence once the prior peer has finished disconnecting, we'll
4163
        // ignore this connection.
4164
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
1✔
4165
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4166

×
4167
                if connReq != nil {
×
4168
                        s.connMgr.Remove(connReq.ID())
×
4169
                }
×
4170

4171
                conn.Close()
×
4172
                return
×
4173
        }
4174

4175
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
1✔
4176
                conn.RemoteAddr())
1✔
4177

1✔
4178
        if connReq != nil {
2✔
4179
                // A successful connection was returned by the connmgr.
1✔
4180
                // Immediately cancel all pending requests, excluding the
1✔
4181
                // outbound connection we just established.
1✔
4182
                ignore := connReq.ID()
1✔
4183
                s.cancelConnReqs(pubStr, &ignore)
1✔
4184
        } else {
2✔
4185
                // This was a successful connection made by some other
1✔
4186
                // subsystem. Remove all requests being managed by the connmgr.
1✔
4187
                s.cancelConnReqs(pubStr, nil)
1✔
4188
        }
1✔
4189

4190
        // If we already have a connection with this peer, decide whether or not
4191
        // we need to drop the stale connection. We forgo adding a default case
4192
        // as we expect these to be the only error values returned from
4193
        // findPeerByPubStr.
4194
        connectedPeer, err := s.findPeerByPubStr(pubStr)
1✔
4195
        switch err {
1✔
4196
        case ErrPeerNotConnected:
1✔
4197
                // We were unable to locate an existing connection with the
1✔
4198
                // target peer, proceed to connect.
1✔
4199
                s.peerConnected(conn, connReq, false, access)
1✔
4200

4201
        case nil:
×
4202
                // We already have a connection with the incoming peer. If the
×
4203
                // connection we've already established should be kept and is
×
4204
                // not of the same type of the new connection (outbound), then
×
4205
                // we'll close out the new connection s.t there's only a single
×
4206
                // connection between us.
×
4207
                localPub := s.identityECDH.PubKey()
×
4208
                if connectedPeer.Inbound() &&
×
4209
                        shouldDropLocalConnection(localPub, nodePub) {
×
4210

×
4211
                        srvrLog.Warnf("Established outbound connection to "+
×
4212
                                "peer %v, but already have inbound "+
×
4213
                                "connection, dropping conn", connectedPeer)
×
4214
                        if connReq != nil {
×
4215
                                s.connMgr.Remove(connReq.ID())
×
4216
                        }
×
4217
                        conn.Close()
×
4218
                        return
×
4219
                }
4220

4221
                // Otherwise, _their_ connection should be dropped. So we'll
4222
                // disconnect the peer and send the now obsolete peer to the
4223
                // server for garbage collection.
4224
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4225
                        connectedPeer)
×
4226

×
4227
                // Remove the current peer from the server's internal state and
×
4228
                // signal that the peer termination watcher does not need to
×
4229
                // execute for this peer.
×
4230
                s.removePeer(connectedPeer)
×
4231
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4232
                s.scheduledPeerConnection[pubStr] = func() {
×
4233
                        s.peerConnected(conn, connReq, false, access)
×
4234
                }
×
4235
        }
4236
}
4237

4238
// UnassignedConnID is the default connection ID that a request can have before
4239
// it actually is submitted to the connmgr.
4240
// TODO(conner): move into connmgr package, or better, add connmgr method for
4241
// generating atomic IDs
4242
const UnassignedConnID uint64 = 0
4243

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

4258
        // Next, check to see if we have any outstanding persistent connection
4259
        // requests to this peer. If so, then we'll remove all of these
4260
        // connection requests, and also delete the entry from the map.
4261
        connReqs, ok := s.persistentConnReqs[pubStr]
1✔
4262
        if !ok {
2✔
4263
                return
1✔
4264
        }
1✔
4265

4266
        for _, connReq := range connReqs {
2✔
4267
                srvrLog.Tracef("Canceling %s:", connReqs)
1✔
4268

1✔
4269
                // Atomically capture the current request identifier.
1✔
4270
                connID := connReq.ID()
1✔
4271

1✔
4272
                // Skip any zero IDs, this indicates the request has not
1✔
4273
                // yet been schedule.
1✔
4274
                if connID == UnassignedConnID {
1✔
4275
                        continue
×
4276
                }
4277

4278
                // Skip a particular connection ID if instructed.
4279
                if skip != nil && connID == *skip {
2✔
4280
                        continue
1✔
4281
                }
4282

4283
                s.connMgr.Remove(connID)
1✔
4284
        }
4285

4286
        delete(s.persistentConnReqs, pubStr)
1✔
4287
}
4288

4289
// handleCustomMessage dispatches an incoming custom peers message to
4290
// subscribers.
4291
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
1✔
4292
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
1✔
4293
                peer, msg.Type)
1✔
4294

1✔
4295
        return s.customMessageServer.SendUpdate(&CustomMessage{
1✔
4296
                Peer: peer,
1✔
4297
                Msg:  msg,
1✔
4298
        })
1✔
4299
}
1✔
4300

4301
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4302
// messages.
4303
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
1✔
4304
        return s.customMessageServer.Subscribe()
1✔
4305
}
1✔
4306

4307
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4308
// the channelNotifier's NotifyOpenChannelEvent.
4309
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4310
        remotePub *btcec.PublicKey) error {
1✔
4311

1✔
4312
        // Call newOpenChan to update the access manager's maps for this peer.
1✔
4313
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
2✔
4314
                return err
1✔
4315
        }
1✔
4316

4317
        // Notify subscribers about this open channel event.
4318
        s.channelNotifier.NotifyOpenChannelEvent(op)
1✔
4319

1✔
4320
        return nil
1✔
4321
}
4322

4323
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4324
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4325
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4326
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
1✔
4327

1✔
4328
        // Call newPendingOpenChan to update the access manager's maps for this
1✔
4329
        // peer.
1✔
4330
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
1✔
4331
                return err
×
4332
        }
×
4333

4334
        // Notify subscribers about this event.
4335
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
1✔
4336

1✔
4337
        return nil
1✔
4338
}
4339

4340
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4341
// calls the channelNotifier's NotifyFundingTimeout.
4342
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4343
        remotePub *btcec.PublicKey) error {
1✔
4344

1✔
4345
        // Call newPendingCloseChan to potentially demote the peer.
1✔
4346
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
1✔
4347
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
1✔
4348
                // If we encounter an error while attempting to disconnect the
×
4349
                // peer, log the error.
×
4350
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4351
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4352
                }
×
4353
        }
4354

4355
        // Notify subscribers about this event.
4356
        s.channelNotifier.NotifyFundingTimeout(op)
1✔
4357

1✔
4358
        return nil
1✔
4359
}
4360

4361
// peerConnected is a function that handles initialization a newly connected
4362
// peer by adding it to the server's global list of all active peers, and
4363
// starting all the goroutines the peer needs to function properly. The inbound
4364
// boolean should be true if the peer initiated the connection to us.
4365
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4366
        inbound bool, access peerAccessStatus) {
1✔
4367

1✔
4368
        brontideConn := conn.(*brontide.Conn)
1✔
4369
        addr := conn.RemoteAddr()
1✔
4370
        pubKey := brontideConn.RemotePub()
1✔
4371

1✔
4372
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
1✔
4373
                pubKey.SerializeCompressed(), addr, inbound)
1✔
4374

1✔
4375
        peerAddr := &lnwire.NetAddress{
1✔
4376
                IdentityKey: pubKey,
1✔
4377
                Address:     addr,
1✔
4378
                ChainNet:    s.cfg.ActiveNetParams.Net,
1✔
4379
        }
1✔
4380

1✔
4381
        // With the brontide connection established, we'll now craft the feature
1✔
4382
        // vectors to advertise to the remote node.
1✔
4383
        initFeatures := s.featureMgr.Get(feature.SetInit)
1✔
4384
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
1✔
4385

1✔
4386
        // Lookup past error caches for the peer in the server. If no buffer is
1✔
4387
        // found, create a fresh buffer.
1✔
4388
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
1✔
4389
        errBuffer, ok := s.peerErrors[pkStr]
1✔
4390
        if !ok {
2✔
4391
                var err error
1✔
4392
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
1✔
4393
                if err != nil {
1✔
4394
                        srvrLog.Errorf("unable to create peer %v", err)
×
4395
                        return
×
4396
                }
×
4397
        }
4398

4399
        // If we directly set the peer.Config TowerClient member to the
4400
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4401
        // the peer.Config's TowerClient member will not evaluate to nil even
4402
        // though the underlying value is nil. To avoid this gotcha which can
4403
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4404
        // TowerClient if needed.
4405
        var towerClient wtclient.ClientManager
1✔
4406
        if s.towerClientMgr != nil {
2✔
4407
                towerClient = s.towerClientMgr
1✔
4408
        }
1✔
4409

4410
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
1✔
4411
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
1✔
4412

1✔
4413
        // Now that we've established a connection, create a peer, and it to the
1✔
4414
        // set of currently active peers. Configure the peer with the incoming
1✔
4415
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
1✔
4416
        // offered that would trigger channel closure. In case of outgoing
1✔
4417
        // htlcs, an extra block is added to prevent the channel from being
1✔
4418
        // closed when the htlc is outstanding and a new block comes in.
1✔
4419
        pCfg := peer.Config{
1✔
4420
                Conn:                    brontideConn,
1✔
4421
                ConnReq:                 connReq,
1✔
4422
                Addr:                    peerAddr,
1✔
4423
                Inbound:                 inbound,
1✔
4424
                Features:                initFeatures,
1✔
4425
                LegacyFeatures:          legacyFeatures,
1✔
4426
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
1✔
4427
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
1✔
4428
                ErrorBuffer:             errBuffer,
1✔
4429
                WritePool:               s.writePool,
1✔
4430
                ReadPool:                s.readPool,
1✔
4431
                Switch:                  s.htlcSwitch,
1✔
4432
                InterceptSwitch:         s.interceptableSwitch,
1✔
4433
                ChannelDB:               s.chanStateDB,
1✔
4434
                ChannelGraph:            s.graphDB,
1✔
4435
                ChainArb:                s.chainArb,
1✔
4436
                AuthGossiper:            s.authGossiper,
1✔
4437
                ChanStatusMgr:           s.chanStatusMgr,
1✔
4438
                ChainIO:                 s.cc.ChainIO,
1✔
4439
                FeeEstimator:            s.cc.FeeEstimator,
1✔
4440
                Signer:                  s.cc.Wallet.Cfg.Signer,
1✔
4441
                SigPool:                 s.sigPool,
1✔
4442
                Wallet:                  s.cc.Wallet,
1✔
4443
                ChainNotifier:           s.cc.ChainNotifier,
1✔
4444
                BestBlockView:           s.cc.BestBlockTracker,
1✔
4445
                RoutingPolicy:           s.cc.RoutingPolicy,
1✔
4446
                Sphinx:                  s.sphinx,
1✔
4447
                WitnessBeacon:           s.witnessBeacon,
1✔
4448
                Invoices:                s.invoices,
1✔
4449
                ChannelNotifier:         s.channelNotifier,
1✔
4450
                HtlcNotifier:            s.htlcNotifier,
1✔
4451
                TowerClient:             towerClient,
1✔
4452
                DisconnectPeer:          s.DisconnectPeer,
1✔
4453
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
1✔
4454
                        lnwire.NodeAnnouncement, error) {
2✔
4455

1✔
4456
                        return s.genNodeAnnouncement(nil)
1✔
4457
                },
1✔
4458

4459
                PongBuf: s.pongBuf,
4460

4461
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4462

4463
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4464

4465
                FundingManager: s.fundingMgr,
4466

4467
                Hodl:                    s.cfg.Hodl,
4468
                UnsafeReplay:            s.cfg.UnsafeReplay,
4469
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4470
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4471
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4472
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4473
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4474
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4475
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4476
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4477
                HandleCustomMessage:    s.handleCustomMessage,
4478
                GetAliases:             s.aliasMgr.GetAliases,
4479
                RequestAlias:           s.aliasMgr.RequestAlias,
4480
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4481
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4482
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4483
                MaxFeeExposure:         thresholdMSats,
4484
                Quit:                   s.quit,
4485
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4486
                AuxSigner:              s.implCfg.AuxSigner,
4487
                MsgRouter:              s.implCfg.MsgRouter,
4488
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4489
                AuxResolver:            s.implCfg.AuxContractResolver,
4490
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4491
                ShouldFwdExpEndorsement: func() bool {
1✔
4492
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
2✔
4493
                                return false
1✔
4494
                        }
1✔
4495

4496
                        return clock.NewDefaultClock().Now().Before(
1✔
4497
                                EndorsementExperimentEnd,
1✔
4498
                        )
1✔
4499
                },
4500
                NoDisconnectOnPongFailure: s.cfg.NoDisconnectOnPongFailure,
4501
        }
4502

4503
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
1✔
4504
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
1✔
4505

1✔
4506
        p := peer.NewBrontide(pCfg)
1✔
4507

1✔
4508
        // Update the access manager with the access permission for this peer.
1✔
4509
        s.peerAccessMan.addPeerAccess(pubKey, access)
1✔
4510

1✔
4511
        // TODO(roasbeef): update IP address for link-node
1✔
4512
        //  * also mark last-seen, do it one single transaction?
1✔
4513

1✔
4514
        s.addPeer(p)
1✔
4515

1✔
4516
        // Once we have successfully added the peer to the server, we can
1✔
4517
        // delete the previous error buffer from the server's map of error
1✔
4518
        // buffers.
1✔
4519
        delete(s.peerErrors, pkStr)
1✔
4520

1✔
4521
        // Dispatch a goroutine to asynchronously start the peer. This process
1✔
4522
        // includes sending and receiving Init messages, which would be a DOS
1✔
4523
        // vector if we held the server's mutex throughout the procedure.
1✔
4524
        s.wg.Add(1)
1✔
4525
        go s.peerInitializer(p)
1✔
4526
}
4527

4528
// addPeer adds the passed peer to the server's global state of all active
4529
// peers.
4530
func (s *server) addPeer(p *peer.Brontide) {
1✔
4531
        if p == nil {
1✔
4532
                return
×
4533
        }
×
4534

4535
        pubBytes := p.IdentityKey().SerializeCompressed()
1✔
4536

1✔
4537
        // Ignore new peers if we're shutting down.
1✔
4538
        if s.Stopped() {
1✔
4539
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4540
                        pubBytes)
×
4541
                p.Disconnect(ErrServerShuttingDown)
×
4542

×
4543
                return
×
4544
        }
×
4545

4546
        // Track the new peer in our indexes so we can quickly look it up either
4547
        // according to its public key, or its peer ID.
4548
        // TODO(roasbeef): pipe all requests through to the
4549
        // queryHandler/peerManager
4550

4551
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4552
        // be human-readable.
4553
        pubStr := string(pubBytes)
1✔
4554

1✔
4555
        s.peersByPub[pubStr] = p
1✔
4556

1✔
4557
        if p.Inbound() {
2✔
4558
                s.inboundPeers[pubStr] = p
1✔
4559
        } else {
2✔
4560
                s.outboundPeers[pubStr] = p
1✔
4561
        }
1✔
4562

4563
        // Inform the peer notifier of a peer online event so that it can be reported
4564
        // to clients listening for peer events.
4565
        var pubKey [33]byte
1✔
4566
        copy(pubKey[:], pubBytes)
1✔
4567

1✔
4568
        s.peerNotifier.NotifyPeerOnline(pubKey)
1✔
4569
}
4570

4571
// peerInitializer asynchronously starts a newly connected peer after it has
4572
// been added to the server's peer map. This method sets up a
4573
// peerTerminationWatcher for the given peer, and ensures that it executes even
4574
// if the peer failed to start. In the event of a successful connection, this
4575
// method reads the negotiated, local feature-bits and spawns the appropriate
4576
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4577
// be signaled of the new peer once the method returns.
4578
//
4579
// NOTE: This MUST be launched as a goroutine.
4580
func (s *server) peerInitializer(p *peer.Brontide) {
1✔
4581
        defer s.wg.Done()
1✔
4582

1✔
4583
        pubBytes := p.IdentityKey().SerializeCompressed()
1✔
4584

1✔
4585
        // Avoid initializing peers while the server is exiting.
1✔
4586
        if s.Stopped() {
1✔
4587
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4588
                        pubBytes)
×
4589
                return
×
4590
        }
×
4591

4592
        // Create a channel that will be used to signal a successful start of
4593
        // the link. This prevents the peer termination watcher from beginning
4594
        // its duty too early.
4595
        ready := make(chan struct{})
1✔
4596

1✔
4597
        // Before starting the peer, launch a goroutine to watch for the
1✔
4598
        // unexpected termination of this peer, which will ensure all resources
1✔
4599
        // are properly cleaned up, and re-establish persistent connections when
1✔
4600
        // necessary. The peer termination watcher will be short circuited if
1✔
4601
        // the peer is ever added to the ignorePeerTermination map, indicating
1✔
4602
        // that the server has already handled the removal of this peer.
1✔
4603
        s.wg.Add(1)
1✔
4604
        go s.peerTerminationWatcher(p, ready)
1✔
4605

1✔
4606
        // Start the peer! If an error occurs, we Disconnect the peer, which
1✔
4607
        // will unblock the peerTerminationWatcher.
1✔
4608
        if err := p.Start(); err != nil {
2✔
4609
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
1✔
4610

1✔
4611
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
1✔
4612
                return
1✔
4613
        }
1✔
4614

4615
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4616
        // was successful, and to begin watching the peer's wait group.
4617
        close(ready)
1✔
4618

1✔
4619
        s.mu.Lock()
1✔
4620
        defer s.mu.Unlock()
1✔
4621

1✔
4622
        // Check if there are listeners waiting for this peer to come online.
1✔
4623
        srvrLog.Debugf("Notifying that peer %v is online", p)
1✔
4624

1✔
4625
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
1✔
4626
        // route.Vertex as the key type of peerConnectedListeners.
1✔
4627
        pubStr := string(pubBytes)
1✔
4628
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
2✔
4629
                select {
1✔
4630
                case peerChan <- p:
1✔
4631
                case <-s.quit:
×
4632
                        return
×
4633
                }
4634
        }
4635
        delete(s.peerConnectedListeners, pubStr)
1✔
4636
}
4637

4638
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4639
// and then cleans up all resources allocated to the peer, notifies relevant
4640
// sub-systems of its demise, and finally handles re-connecting to the peer if
4641
// it's persistent. If the server intentionally disconnects a peer, it should
4642
// have a corresponding entry in the ignorePeerTermination map which will cause
4643
// the cleanup routine to exit early. The passed `ready` chan is used to
4644
// synchronize when WaitForDisconnect should begin watching on the peer's
4645
// waitgroup. The ready chan should only be signaled if the peer starts
4646
// successfully, otherwise the peer should be disconnected instead.
4647
//
4648
// NOTE: This MUST be launched as a goroutine.
4649
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
1✔
4650
        defer s.wg.Done()
1✔
4651

1✔
4652
        p.WaitForDisconnect(ready)
1✔
4653

1✔
4654
        srvrLog.Debugf("Peer %v has been disconnected", p)
1✔
4655

1✔
4656
        // If the server is exiting then we can bail out early ourselves as all
1✔
4657
        // the other sub-systems will already be shutting down.
1✔
4658
        if s.Stopped() {
2✔
4659
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
1✔
4660
                return
1✔
4661
        }
1✔
4662

4663
        // Next, we'll cancel all pending funding reservations with this node.
4664
        // If we tried to initiate any funding flows that haven't yet finished,
4665
        // then we need to unlock those committed outputs so they're still
4666
        // available for use.
4667
        s.fundingMgr.CancelPeerReservations(p.PubKey())
1✔
4668

1✔
4669
        pubKey := p.IdentityKey()
1✔
4670

1✔
4671
        // We'll also inform the gossiper that this peer is no longer active,
1✔
4672
        // so we don't need to maintain sync state for it any longer.
1✔
4673
        s.authGossiper.PruneSyncState(p.PubKey())
1✔
4674

1✔
4675
        // Tell the switch to remove all links associated with this peer.
1✔
4676
        // Passing nil as the target link indicates that all links associated
1✔
4677
        // with this interface should be closed.
1✔
4678
        //
1✔
4679
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
1✔
4680
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
1✔
4681
        if err != nil && err != htlcswitch.ErrNoLinksFound {
1✔
4682
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4683
        }
×
4684

4685
        for _, link := range links {
2✔
4686
                s.htlcSwitch.RemoveLink(link.ChanID())
1✔
4687
        }
1✔
4688

4689
        s.mu.Lock()
1✔
4690
        defer s.mu.Unlock()
1✔
4691

1✔
4692
        // If there were any notification requests for when this peer
1✔
4693
        // disconnected, we can trigger them now.
1✔
4694
        srvrLog.Debugf("Notifying that peer %v is offline", p)
1✔
4695
        pubStr := string(pubKey.SerializeCompressed())
1✔
4696
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
2✔
4697
                close(offlineChan)
1✔
4698
        }
1✔
4699
        delete(s.peerDisconnectedListeners, pubStr)
1✔
4700

1✔
4701
        // If the server has already removed this peer, we can short circuit the
1✔
4702
        // peer termination watcher and skip cleanup.
1✔
4703
        if _, ok := s.ignorePeerTermination[p]; ok {
1✔
4704
                delete(s.ignorePeerTermination, p)
×
4705

×
4706
                pubKey := p.PubKey()
×
4707
                pubStr := string(pubKey[:])
×
4708

×
4709
                // If a connection callback is present, we'll go ahead and
×
4710
                // execute it now that previous peer has fully disconnected. If
×
4711
                // the callback is not present, this likely implies the peer was
×
4712
                // purposefully disconnected via RPC, and that no reconnect
×
4713
                // should be attempted.
×
4714
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4715
                if ok {
×
4716
                        delete(s.scheduledPeerConnection, pubStr)
×
4717
                        connCallback()
×
4718
                }
×
4719
                return
×
4720
        }
4721

4722
        // First, cleanup any remaining state the server has regarding the peer
4723
        // in question.
4724
        s.removePeer(p)
1✔
4725

1✔
4726
        // Next, check to see if this is a persistent peer or not.
1✔
4727
        if _, ok := s.persistentPeers[pubStr]; !ok {
2✔
4728
                return
1✔
4729
        }
1✔
4730

4731
        // Get the last address that we used to connect to the peer.
4732
        addrs := []net.Addr{
1✔
4733
                p.NetAddress().Address,
1✔
4734
        }
1✔
4735

1✔
4736
        // We'll ensure that we locate all the peers advertised addresses for
1✔
4737
        // reconnection purposes.
1✔
4738
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
1✔
4739
        switch {
1✔
4740
        // We found advertised addresses, so use them.
4741
        case err == nil:
1✔
4742
                addrs = advertisedAddrs
1✔
4743

4744
        // The peer doesn't have an advertised address.
4745
        case err == errNoAdvertisedAddr:
1✔
4746
                // If it is an outbound peer then we fall back to the existing
1✔
4747
                // peer address.
1✔
4748
                if !p.Inbound() {
2✔
4749
                        break
1✔
4750
                }
4751

4752
                // Fall back to the existing peer address if
4753
                // we're not accepting connections over Tor.
4754
                if s.torController == nil {
2✔
4755
                        break
1✔
4756
                }
4757

4758
                // If we are, the peer's address won't be known
4759
                // to us (we'll see a private address, which is
4760
                // the address used by our onion service to dial
4761
                // to lnd), so we don't have enough information
4762
                // to attempt a reconnect.
4763
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4764
                        "to inbound peer %v without "+
×
4765
                        "advertised address", p)
×
4766
                return
×
4767

4768
        // We came across an error retrieving an advertised
4769
        // address, log it, and fall back to the existing peer
4770
        // address.
4771
        default:
1✔
4772
                srvrLog.Errorf("Unable to retrieve advertised "+
1✔
4773
                        "address for node %x: %v", p.PubKey(),
1✔
4774
                        err)
1✔
4775
        }
4776

4777
        // Make an easy lookup map so that we can check if an address
4778
        // is already in the address list that we have stored for this peer.
4779
        existingAddrs := make(map[string]bool)
1✔
4780
        for _, addr := range s.persistentPeerAddrs[pubStr] {
2✔
4781
                existingAddrs[addr.String()] = true
1✔
4782
        }
1✔
4783

4784
        // Add any missing addresses for this peer to persistentPeerAddr.
4785
        for _, addr := range addrs {
2✔
4786
                if existingAddrs[addr.String()] {
1✔
4787
                        continue
×
4788
                }
4789

4790
                s.persistentPeerAddrs[pubStr] = append(
1✔
4791
                        s.persistentPeerAddrs[pubStr],
1✔
4792
                        &lnwire.NetAddress{
1✔
4793
                                IdentityKey: p.IdentityKey(),
1✔
4794
                                Address:     addr,
1✔
4795
                                ChainNet:    p.NetAddress().ChainNet,
1✔
4796
                        },
1✔
4797
                )
1✔
4798
        }
4799

4800
        // Record the computed backoff in the backoff map.
4801
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
1✔
4802
        s.persistentPeersBackoff[pubStr] = backoff
1✔
4803

1✔
4804
        // Initialize a retry canceller for this peer if one does not
1✔
4805
        // exist.
1✔
4806
        cancelChan, ok := s.persistentRetryCancels[pubStr]
1✔
4807
        if !ok {
2✔
4808
                cancelChan = make(chan struct{})
1✔
4809
                s.persistentRetryCancels[pubStr] = cancelChan
1✔
4810
        }
1✔
4811

4812
        // We choose not to wait group this go routine since the Connect
4813
        // call can stall for arbitrarily long if we shutdown while an
4814
        // outbound connection attempt is being made.
4815
        go func() {
2✔
4816
                srvrLog.Debugf("Scheduling connection re-establishment to "+
1✔
4817
                        "persistent peer %x in %s",
1✔
4818
                        p.IdentityKey().SerializeCompressed(), backoff)
1✔
4819

1✔
4820
                select {
1✔
4821
                case <-time.After(backoff):
1✔
4822
                case <-cancelChan:
1✔
4823
                        return
1✔
4824
                case <-s.quit:
1✔
4825
                        return
1✔
4826
                }
4827

4828
                srvrLog.Debugf("Attempting to re-establish persistent "+
1✔
4829
                        "connection to peer %x",
1✔
4830
                        p.IdentityKey().SerializeCompressed())
1✔
4831

1✔
4832
                s.connectToPersistentPeer(pubStr)
1✔
4833
        }()
4834
}
4835

4836
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4837
// to connect to the peer. It creates connection requests if there are
4838
// currently none for a given address and it removes old connection requests
4839
// if the associated address is no longer in the latest address list for the
4840
// peer.
4841
func (s *server) connectToPersistentPeer(pubKeyStr string) {
1✔
4842
        s.mu.Lock()
1✔
4843
        defer s.mu.Unlock()
1✔
4844

1✔
4845
        // Create an easy lookup map of the addresses we have stored for the
1✔
4846
        // peer. We will remove entries from this map if we have existing
1✔
4847
        // connection requests for the associated address and then any leftover
1✔
4848
        // entries will indicate which addresses we should create new
1✔
4849
        // connection requests for.
1✔
4850
        addrMap := make(map[string]*lnwire.NetAddress)
1✔
4851
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
2✔
4852
                addrMap[addr.String()] = addr
1✔
4853
        }
1✔
4854

4855
        // Go through each of the existing connection requests and
4856
        // check if they correspond to the latest set of addresses. If
4857
        // there is a connection requests that does not use one of the latest
4858
        // advertised addresses then remove that connection request.
4859
        var updatedConnReqs []*connmgr.ConnReq
1✔
4860
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
2✔
4861
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
1✔
4862

1✔
4863
                switch _, ok := addrMap[lnAddr]; ok {
1✔
4864
                // If the existing connection request is using one of the
4865
                // latest advertised addresses for the peer then we add it to
4866
                // updatedConnReqs and remove the associated address from
4867
                // addrMap so that we don't recreate this connReq later on.
4868
                case true:
×
4869
                        updatedConnReqs = append(
×
4870
                                updatedConnReqs, connReq,
×
4871
                        )
×
4872
                        delete(addrMap, lnAddr)
×
4873

4874
                // If the existing connection request is using an address that
4875
                // is not one of the latest advertised addresses for the peer
4876
                // then we remove the connecting request from the connection
4877
                // manager.
4878
                case false:
1✔
4879
                        srvrLog.Info(
1✔
4880
                                "Removing conn req:", connReq.Addr.String(),
1✔
4881
                        )
1✔
4882
                        s.connMgr.Remove(connReq.ID())
1✔
4883
                }
4884
        }
4885

4886
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
1✔
4887

1✔
4888
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
1✔
4889
        if !ok {
2✔
4890
                cancelChan = make(chan struct{})
1✔
4891
                s.persistentRetryCancels[pubKeyStr] = cancelChan
1✔
4892
        }
1✔
4893

4894
        // Any addresses left in addrMap are new ones that we have not made
4895
        // connection requests for. So create new connection requests for those.
4896
        // If there is more than one address in the address map, stagger the
4897
        // creation of the connection requests for those.
4898
        go func() {
2✔
4899
                ticker := time.NewTicker(multiAddrConnectionStagger)
1✔
4900
                defer ticker.Stop()
1✔
4901

1✔
4902
                for _, addr := range addrMap {
2✔
4903
                        // Send the persistent connection request to the
1✔
4904
                        // connection manager, saving the request itself so we
1✔
4905
                        // can cancel/restart the process as needed.
1✔
4906
                        connReq := &connmgr.ConnReq{
1✔
4907
                                Addr:      addr,
1✔
4908
                                Permanent: true,
1✔
4909
                        }
1✔
4910

1✔
4911
                        s.mu.Lock()
1✔
4912
                        s.persistentConnReqs[pubKeyStr] = append(
1✔
4913
                                s.persistentConnReqs[pubKeyStr], connReq,
1✔
4914
                        )
1✔
4915
                        s.mu.Unlock()
1✔
4916

1✔
4917
                        srvrLog.Debugf("Attempting persistent connection to "+
1✔
4918
                                "channel peer %v", addr)
1✔
4919

1✔
4920
                        go s.connMgr.Connect(connReq)
1✔
4921

1✔
4922
                        select {
1✔
4923
                        case <-s.quit:
1✔
4924
                                return
1✔
4925
                        case <-cancelChan:
1✔
4926
                                return
1✔
4927
                        case <-ticker.C:
1✔
4928
                        }
4929
                }
4930
        }()
4931
}
4932

4933
// removePeer removes the passed peer from the server's state of all active
4934
// peers.
4935
func (s *server) removePeer(p *peer.Brontide) {
1✔
4936
        if p == nil {
1✔
4937
                return
×
4938
        }
×
4939

4940
        srvrLog.Debugf("removing peer %v", p)
1✔
4941

1✔
4942
        // As the peer is now finished, ensure that the TCP connection is
1✔
4943
        // closed and all of its related goroutines have exited.
1✔
4944
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
1✔
4945

1✔
4946
        // If this peer had an active persistent connection request, remove it.
1✔
4947
        if p.ConnReq() != nil {
2✔
4948
                s.connMgr.Remove(p.ConnReq().ID())
1✔
4949
        }
1✔
4950

4951
        // Ignore deleting peers if we're shutting down.
4952
        if s.Stopped() {
1✔
4953
                return
×
4954
        }
×
4955

4956
        pKey := p.PubKey()
1✔
4957
        pubSer := pKey[:]
1✔
4958
        pubStr := string(pubSer)
1✔
4959

1✔
4960
        delete(s.peersByPub, pubStr)
1✔
4961

1✔
4962
        if p.Inbound() {
2✔
4963
                delete(s.inboundPeers, pubStr)
1✔
4964
        } else {
2✔
4965
                delete(s.outboundPeers, pubStr)
1✔
4966
        }
1✔
4967

4968
        // Remove the peer's access permission from the access manager.
4969
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
1✔
4970

1✔
4971
        // Copy the peer's error buffer across to the server if it has any items
1✔
4972
        // in it so that we can restore peer errors across connections.
1✔
4973
        if p.ErrorBuffer().Total() > 0 {
2✔
4974
                s.peerErrors[pubStr] = p.ErrorBuffer()
1✔
4975
        }
1✔
4976

4977
        // Inform the peer notifier of a peer offline event so that it can be
4978
        // reported to clients listening for peer events.
4979
        var pubKey [33]byte
1✔
4980
        copy(pubKey[:], pubSer)
1✔
4981

1✔
4982
        s.peerNotifier.NotifyPeerOffline(pubKey)
1✔
4983
}
4984

4985
// ConnectToPeer requests that the server connect to a Lightning Network peer
4986
// at the specified address. This function will *block* until either a
4987
// connection is established, or the initial handshake process fails.
4988
//
4989
// NOTE: This function is safe for concurrent access.
4990
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4991
        perm bool, timeout time.Duration) error {
1✔
4992

1✔
4993
        targetPub := string(addr.IdentityKey.SerializeCompressed())
1✔
4994

1✔
4995
        // Acquire mutex, but use explicit unlocking instead of defer for
1✔
4996
        // better granularity.  In certain conditions, this method requires
1✔
4997
        // making an outbound connection to a remote peer, which requires the
1✔
4998
        // lock to be released, and subsequently reacquired.
1✔
4999
        s.mu.Lock()
1✔
5000

1✔
5001
        // Ensure we're not already connected to this peer.
1✔
5002
        peer, err := s.findPeerByPubStr(targetPub)
1✔
5003
        if err == nil {
2✔
5004
                s.mu.Unlock()
1✔
5005
                return &errPeerAlreadyConnected{peer: peer}
1✔
5006
        }
1✔
5007

5008
        // Peer was not found, continue to pursue connection with peer.
5009

5010
        // If there's already a pending connection request for this pubkey,
5011
        // then we ignore this request to ensure we don't create a redundant
5012
        // connection.
5013
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
2✔
5014
                srvrLog.Warnf("Already have %d persistent connection "+
1✔
5015
                        "requests for %v, connecting anyway.", len(reqs), addr)
1✔
5016
        }
1✔
5017

5018
        // If there's not already a pending or active connection to this node,
5019
        // then instruct the connection manager to attempt to establish a
5020
        // persistent connection to the peer.
5021
        srvrLog.Debugf("Connecting to %v", addr)
1✔
5022
        if perm {
2✔
5023
                connReq := &connmgr.ConnReq{
1✔
5024
                        Addr:      addr,
1✔
5025
                        Permanent: true,
1✔
5026
                }
1✔
5027

1✔
5028
                // Since the user requested a permanent connection, we'll set
1✔
5029
                // the entry to true which will tell the server to continue
1✔
5030
                // reconnecting even if the number of channels with this peer is
1✔
5031
                // zero.
1✔
5032
                s.persistentPeers[targetPub] = true
1✔
5033
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
2✔
5034
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
1✔
5035
                }
1✔
5036
                s.persistentConnReqs[targetPub] = append(
1✔
5037
                        s.persistentConnReqs[targetPub], connReq,
1✔
5038
                )
1✔
5039
                s.mu.Unlock()
1✔
5040

1✔
5041
                go s.connMgr.Connect(connReq)
1✔
5042

1✔
5043
                return nil
1✔
5044
        }
5045
        s.mu.Unlock()
1✔
5046

1✔
5047
        // If we're not making a persistent connection, then we'll attempt to
1✔
5048
        // connect to the target peer. If the we can't make the connection, or
1✔
5049
        // the crypto negotiation breaks down, then return an error to the
1✔
5050
        // caller.
1✔
5051
        errChan := make(chan error, 1)
1✔
5052
        s.connectToPeer(addr, errChan, timeout)
1✔
5053

1✔
5054
        select {
1✔
5055
        case err := <-errChan:
1✔
5056
                return err
1✔
5057
        case <-s.quit:
×
5058
                return ErrServerShuttingDown
×
5059
        }
5060
}
5061

5062
// connectToPeer establishes a connection to a remote peer. errChan is used to
5063
// notify the caller if the connection attempt has failed. Otherwise, it will be
5064
// closed.
5065
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5066
        errChan chan<- error, timeout time.Duration) {
1✔
5067

1✔
5068
        conn, err := brontide.Dial(
1✔
5069
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
1✔
5070
        )
1✔
5071
        if err != nil {
2✔
5072
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
1✔
5073
                select {
1✔
5074
                case errChan <- err:
1✔
5075
                case <-s.quit:
×
5076
                }
5077
                return
1✔
5078
        }
5079

5080
        close(errChan)
1✔
5081

1✔
5082
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
1✔
5083
                conn.LocalAddr(), conn.RemoteAddr())
1✔
5084

1✔
5085
        s.OutboundPeerConnected(nil, conn)
1✔
5086
}
5087

5088
// DisconnectPeer sends the request to server to close the connection with peer
5089
// identified by public key.
5090
//
5091
// NOTE: This function is safe for concurrent access.
5092
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
1✔
5093
        pubBytes := pubKey.SerializeCompressed()
1✔
5094
        pubStr := string(pubBytes)
1✔
5095

1✔
5096
        s.mu.Lock()
1✔
5097
        defer s.mu.Unlock()
1✔
5098

1✔
5099
        // Check that were actually connected to this peer. If not, then we'll
1✔
5100
        // exit in an error as we can't disconnect from a peer that we're not
1✔
5101
        // currently connected to.
1✔
5102
        peer, err := s.findPeerByPubStr(pubStr)
1✔
5103
        if err == ErrPeerNotConnected {
2✔
5104
                return fmt.Errorf("peer %x is not connected", pubBytes)
1✔
5105
        }
1✔
5106

5107
        srvrLog.Infof("Disconnecting from %v", peer)
1✔
5108

1✔
5109
        s.cancelConnReqs(pubStr, nil)
1✔
5110

1✔
5111
        // If this peer was formerly a persistent connection, then we'll remove
1✔
5112
        // them from this map so we don't attempt to re-connect after we
1✔
5113
        // disconnect.
1✔
5114
        delete(s.persistentPeers, pubStr)
1✔
5115
        delete(s.persistentPeersBackoff, pubStr)
1✔
5116

1✔
5117
        // Remove the peer by calling Disconnect. Previously this was done with
1✔
5118
        // removePeer, which bypassed the peerTerminationWatcher.
1✔
5119
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
1✔
5120

1✔
5121
        return nil
1✔
5122
}
5123

5124
// OpenChannel sends a request to the server to open a channel to the specified
5125
// peer identified by nodeKey with the passed channel funding parameters.
5126
//
5127
// NOTE: This function is safe for concurrent access.
5128
func (s *server) OpenChannel(
5129
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
1✔
5130

1✔
5131
        // The updateChan will have a buffer of 2, since we expect a ChanPending
1✔
5132
        // + a ChanOpen update, and we want to make sure the funding process is
1✔
5133
        // not blocked if the caller is not reading the updates.
1✔
5134
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
1✔
5135
        req.Err = make(chan error, 1)
1✔
5136

1✔
5137
        // First attempt to locate the target peer to open a channel with, if
1✔
5138
        // we're unable to locate the peer then this request will fail.
1✔
5139
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
1✔
5140
        s.mu.RLock()
1✔
5141
        peer, ok := s.peersByPub[string(pubKeyBytes)]
1✔
5142
        if !ok {
1✔
5143
                s.mu.RUnlock()
×
5144

×
5145
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5146
                return req.Updates, req.Err
×
5147
        }
×
5148
        req.Peer = peer
1✔
5149
        s.mu.RUnlock()
1✔
5150

1✔
5151
        // We'll wait until the peer is active before beginning the channel
1✔
5152
        // opening process.
1✔
5153
        select {
1✔
5154
        case <-peer.ActiveSignal():
1✔
5155
        case <-peer.QuitSignal():
×
5156
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5157
                return req.Updates, req.Err
×
5158
        case <-s.quit:
×
5159
                req.Err <- ErrServerShuttingDown
×
5160
                return req.Updates, req.Err
×
5161
        }
5162

5163
        // If the fee rate wasn't specified at this point we fail the funding
5164
        // because of the missing fee rate information. The caller of the
5165
        // `OpenChannel` method needs to make sure that default values for the
5166
        // fee rate are set beforehand.
5167
        if req.FundingFeePerKw == 0 {
1✔
5168
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5169
                        "the channel opening transaction")
×
5170

×
5171
                return req.Updates, req.Err
×
5172
        }
×
5173

5174
        // Spawn a goroutine to send the funding workflow request to the funding
5175
        // manager. This allows the server to continue handling queries instead
5176
        // of blocking on this request which is exported as a synchronous
5177
        // request to the outside world.
5178
        go s.fundingMgr.InitFundingWorkflow(req)
1✔
5179

1✔
5180
        return req.Updates, req.Err
1✔
5181
}
5182

5183
// Peers returns a slice of all active peers.
5184
//
5185
// NOTE: This function is safe for concurrent access.
5186
func (s *server) Peers() []*peer.Brontide {
1✔
5187
        s.mu.RLock()
1✔
5188
        defer s.mu.RUnlock()
1✔
5189

1✔
5190
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
1✔
5191
        for _, peer := range s.peersByPub {
2✔
5192
                peers = append(peers, peer)
1✔
5193
        }
1✔
5194

5195
        return peers
1✔
5196
}
5197

5198
// computeNextBackoff uses a truncated exponential backoff to compute the next
5199
// backoff using the value of the exiting backoff. The returned duration is
5200
// randomized in either direction by 1/20 to prevent tight loops from
5201
// stabilizing.
5202
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
1✔
5203
        // Double the current backoff, truncating if it exceeds our maximum.
1✔
5204
        nextBackoff := 2 * currBackoff
1✔
5205
        if nextBackoff > maxBackoff {
2✔
5206
                nextBackoff = maxBackoff
1✔
5207
        }
1✔
5208

5209
        // Using 1/10 of our duration as a margin, compute a random offset to
5210
        // avoid the nodes entering connection cycles.
5211
        margin := nextBackoff / 10
1✔
5212

1✔
5213
        var wiggle big.Int
1✔
5214
        wiggle.SetUint64(uint64(margin))
1✔
5215
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
1✔
5216
                // Randomizing is not mission critical, so we'll just return the
×
5217
                // current backoff.
×
5218
                return nextBackoff
×
5219
        }
×
5220

5221
        // Otherwise add in our wiggle, but subtract out half of the margin so
5222
        // that the backoff can tweaked by 1/20 in either direction.
5223
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
1✔
5224
}
5225

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

5230
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5231
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
1✔
5232
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
1✔
5233
        if err != nil {
1✔
5234
                return nil, err
×
5235
        }
×
5236

5237
        node, err := s.graphDB.FetchLightningNode(vertex)
1✔
5238
        if err != nil {
2✔
5239
                return nil, err
1✔
5240
        }
1✔
5241

5242
        if len(node.Addresses) == 0 {
2✔
5243
                return nil, errNoAdvertisedAddr
1✔
5244
        }
1✔
5245

5246
        return node.Addresses, nil
1✔
5247
}
5248

5249
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5250
// channel update for a target channel.
5251
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5252
        *lnwire.ChannelUpdate1, error) {
1✔
5253

1✔
5254
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
1✔
5255
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
2✔
5256
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
1✔
5257
                if err != nil {
2✔
5258
                        return nil, err
1✔
5259
                }
1✔
5260

5261
                return netann.ExtractChannelUpdate(
1✔
5262
                        ourPubKey[:], info, edge1, edge2,
1✔
5263
                )
1✔
5264
        }
5265
}
5266

5267
// applyChannelUpdate applies the channel update to the different sub-systems of
5268
// the server. The useAlias boolean denotes whether or not to send an alias in
5269
// place of the real SCID.
5270
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5271
        op *wire.OutPoint, useAlias bool) error {
1✔
5272

1✔
5273
        var (
1✔
5274
                peerAlias    *lnwire.ShortChannelID
1✔
5275
                defaultAlias lnwire.ShortChannelID
1✔
5276
        )
1✔
5277

1✔
5278
        chanID := lnwire.NewChanIDFromOutPoint(*op)
1✔
5279

1✔
5280
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
1✔
5281
        // in the ChannelUpdate if it hasn't been announced yet.
1✔
5282
        if useAlias {
2✔
5283
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
1✔
5284
                if foundAlias != defaultAlias {
2✔
5285
                        peerAlias = &foundAlias
1✔
5286
                }
1✔
5287
        }
5288

5289
        errChan := s.authGossiper.ProcessLocalAnnouncement(
1✔
5290
                update, discovery.RemoteAlias(peerAlias),
1✔
5291
        )
1✔
5292
        select {
1✔
5293
        case err := <-errChan:
1✔
5294
                return err
1✔
5295
        case <-s.quit:
×
5296
                return ErrServerShuttingDown
×
5297
        }
5298
}
5299

5300
// SendCustomMessage sends a custom message to the peer with the specified
5301
// pubkey.
5302
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5303
        data []byte) error {
1✔
5304

1✔
5305
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
1✔
5306
        if err != nil {
1✔
5307
                return err
×
5308
        }
×
5309

5310
        // We'll wait until the peer is active.
5311
        select {
1✔
5312
        case <-peer.ActiveSignal():
1✔
5313
        case <-peer.QuitSignal():
×
5314
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5315
        case <-s.quit:
×
5316
                return ErrServerShuttingDown
×
5317
        }
5318

5319
        msg, err := lnwire.NewCustom(msgType, data)
1✔
5320
        if err != nil {
2✔
5321
                return err
1✔
5322
        }
1✔
5323

5324
        // Send the message as low-priority. For now we assume that all
5325
        // application-defined message are low priority.
5326
        return peer.SendMessageLazy(true, msg)
1✔
5327
}
5328

5329
// newSweepPkScriptGen creates closure that generates a new public key script
5330
// which should be used to sweep any funds into the on-chain wallet.
5331
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5332
// (p2wkh) output.
5333
func newSweepPkScriptGen(
5334
        wallet lnwallet.WalletController,
5335
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
1✔
5336

1✔
5337
        return func() fn.Result[lnwallet.AddrWithKey] {
2✔
5338
                sweepAddr, err := wallet.NewAddress(
1✔
5339
                        lnwallet.TaprootPubkey, false,
1✔
5340
                        lnwallet.DefaultAccountName,
1✔
5341
                )
1✔
5342
                if err != nil {
1✔
5343
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5344
                }
×
5345

5346
                addr, err := txscript.PayToAddrScript(sweepAddr)
1✔
5347
                if err != nil {
1✔
5348
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5349
                }
×
5350

5351
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
1✔
5352
                        wallet, netParams, addr,
1✔
5353
                )
1✔
5354
                if err != nil {
1✔
5355
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5356
                }
×
5357

5358
                return fn.Ok(lnwallet.AddrWithKey{
1✔
5359
                        DeliveryAddress: addr,
1✔
5360
                        InternalKey:     internalKeyDesc,
1✔
5361
                })
1✔
5362
        }
5363
}
5364

5365
// shouldPeerBootstrap returns true if we should attempt to perform peer
5366
// bootstrapping to actively seek our peers using the set of active network
5367
// bootstrappers.
5368
func shouldPeerBootstrap(cfg *Config) bool {
1✔
5369
        isSimnet := cfg.Bitcoin.SimNet
1✔
5370
        isSignet := cfg.Bitcoin.SigNet
1✔
5371
        isRegtest := cfg.Bitcoin.RegTest
1✔
5372
        isDevNetwork := isSimnet || isSignet || isRegtest
1✔
5373

1✔
5374
        // TODO(yy): remove the check on simnet/regtest such that the itest is
1✔
5375
        // covering the bootstrapping process.
1✔
5376
        return !cfg.NoNetBootstrap && !isDevNetwork
1✔
5377
}
1✔
5378

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

5389
        // Save the SCIDs in a map.
5390
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
1✔
5391
        for _, c := range channels {
2✔
5392
                // If the channel is not pending, its FC has been finalized.
1✔
5393
                if !c.IsPending {
2✔
5394
                        closedSCIDs[c.ShortChanID] = struct{}{}
1✔
5395
                }
1✔
5396
        }
5397

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

5412
        for _, c := range pendings {
2✔
5413
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
2✔
5414
                        continue
1✔
5415
                }
5416

5417
                // If the channel is still reported as pending, remove it from
5418
                // the map.
5419
                delete(closedSCIDs, c.ShortChannelID)
×
5420

×
5421
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5422
                        c.ShortChannelID)
×
5423
        }
5424

5425
        return closedSCIDs
1✔
5426
}
5427

5428
// getStartingBeat returns the current beat. This is used during the startup to
5429
// initialize blockbeat consumers.
5430
func (s *server) getStartingBeat() (*chainio.Beat, error) {
1✔
5431
        // beat is the current blockbeat.
1✔
5432
        var beat *chainio.Beat
1✔
5433

1✔
5434
        // If the node is configured with nochainbackend mode (remote signer),
1✔
5435
        // we will skip fetching the best block.
1✔
5436
        if s.cfg.Bitcoin.Node == "nochainbackend" {
1✔
5437
                srvrLog.Info("Skipping block notification for nochainbackend " +
×
5438
                        "mode")
×
5439

×
5440
                return &chainio.Beat{}, nil
×
5441
        }
×
5442

5443
        // We should get a notification with the current best block immediately
5444
        // by passing a nil block.
5445
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
1✔
5446
        if err != nil {
1✔
5447
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5448
        }
×
5449
        defer blockEpochs.Cancel()
1✔
5450

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

1✔
5459
                // Update the current blockbeat.
1✔
5460
                beat = chainio.NewBeat(*bestBlock)
1✔
5461

5462
        case <-s.quit:
×
5463
                srvrLog.Debug("LND shutting down")
×
5464
        }
5465

5466
        return beat, nil
1✔
5467
}
5468

5469
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5470
// point has an active RBF chan closer.
5471
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5472
        chanPoint wire.OutPoint) bool {
1✔
5473

1✔
5474
        pubBytes := peerPub.SerializeCompressed()
1✔
5475

1✔
5476
        s.mu.RLock()
1✔
5477
        targetPeer, ok := s.peersByPub[string(pubBytes)]
1✔
5478
        s.mu.RUnlock()
1✔
5479
        if !ok {
1✔
5480
                return false
×
5481
        }
×
5482

5483
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
1✔
5484
}
5485

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

1✔
5494
        // First, we'll attempt to look up the channel based on it's
1✔
5495
        // ChannelPoint.
1✔
5496
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
1✔
5497
        if err != nil {
1✔
5498
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5499
        }
×
5500

5501
        // From the channel, we can now get the pubkey of the peer, then use
5502
        // that to eventually get the chan closer.
5503
        peerPub := channel.IdentityPub.SerializeCompressed()
1✔
5504

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

5514
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
1✔
5515
                ctx, chanPoint, feeRate, deliveryScript,
1✔
5516
        )
1✔
5517
        if err != nil {
1✔
5518
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5519
                        "%w", err)
×
5520
        }
×
5521

5522
        return closeUpdates, nil
1✔
5523
}
5524

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

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

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

5551
        return updates, nil
1✔
5552
}
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