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

lightningnetwork / lnd / 14000719599

21 Mar 2025 08:54PM UTC coverage: 58.717% (-10.3%) from 68.989%
14000719599

Pull #8754

github

web-flow
Merge 29f363f18 into 5235f3b24
Pull Request #8754: Add `Outbound` Remote Signer implementation

1562 of 2088 new or added lines in 41 files covered. (74.81%)

28126 existing lines in 464 files now uncovered.

97953 of 166822 relevant lines covered (58.72%)

1.82 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

212
        start sync.Once
213
        stop  sync.Once
214

215
        cfg *Config
216

217
        implCfg *ImplementationCfg
218

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

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

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

230
        chanStatusMgr *netann.ChanStatusManager
231

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

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

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

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

252
        mu sync.RWMutex
253

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

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

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

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

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

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

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

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

304
        cc *chainreg.ChainControl
305

306
        fundingMgr *funding.Manager
307

308
        graphDB *graphdb.ChannelGraph
309

310
        chanStateDB *channeldb.ChannelStateDB
311

312
        addrSource channeldb.AddrSource
313

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

318
        invoicesDB invoices.InvoiceDB
319

320
        aliasMgr *aliasmgr.Manager
321

322
        htlcSwitch *htlcswitch.Switch
323

324
        interceptableSwitch *htlcswitch.InterceptableSwitch
325

326
        invoices *invoices.InvoiceRegistry
327

328
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
329

330
        channelNotifier *channelnotifier.ChannelNotifier
331

332
        peerNotifier *peernotifier.PeerNotifier
333

334
        htlcNotifier *htlcswitch.HtlcNotifier
335

336
        witnessBeacon contractcourt.WitnessBeacon
337

338
        breachArbitrator *contractcourt.BreachArbitrator
339

340
        missionController *routing.MissionController
341
        defaultMC         *routing.MissionControl
342

343
        graphBuilder *graph.Builder
344

345
        chanRouter *routing.ChannelRouter
346

347
        controlTower routing.ControlTower
348

349
        authGossiper *discovery.AuthenticatedGossiper
350

351
        localChanMgr *localchans.Manager
352

353
        utxoNursery *contractcourt.UtxoNursery
354

355
        sweeper *sweep.UtxoSweeper
356

357
        chainArb *contractcourt.ChainArbitrator
358

359
        sphinx *hop.OnionProcessor
360

361
        towerClientMgr *wtclient.Manager
362

363
        connMgr *connmgr.ConnManager
364

365
        sigPool *lnwallet.SigPool
366

367
        writePool *pool.Write
368

369
        readPool *pool.Read
370

371
        tlsManager *TLSManager
372

373
        remoteSignerClient rpcwallet.RemoteSignerClient
374

375
        // featureMgr dispatches feature vectors for various contexts within the
376
        // daemon.
377
        featureMgr *feature.Manager
378

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

384
        // chansToRestore is the set of channels that upon starting, the server
385
        // should attempt to restore/recover.
386
        chansToRestore walletunlocker.ChannelsToRecover
387

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

393
        // chanEventStore tracks the behaviour of channels and their remote peers to
394
        // provide insights into their health and performance.
395
        chanEventStore *chanfitness.ChannelEventStore
396

397
        hostAnn *netann.HostAnnouncer
398

399
        // livenessMonitor monitors that lnd has access to critical resources.
400
        livenessMonitor *healthcheck.Monitor
401

402
        customMessageServer *subscribe.Server
403

404
        // txPublisher is a publisher with fee-bumping capability.
405
        txPublisher *sweep.TxPublisher
406

407
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
408
        // of new blocks.
409
        blockbeatDispatcher *chainio.BlockbeatDispatcher
410

411
        // peerAccessMan implements peer access controls.
412
        peerAccessMan *accessMan
413

414
        quit chan struct{}
415

416
        wg sync.WaitGroup
417
}
418

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

427
        s.wg.Add(1)
3✔
428
        go func() {
6✔
429
                defer func() {
6✔
430
                        graphSub.Cancel()
3✔
431
                        s.wg.Done()
3✔
432
                }()
3✔
433

434
                for {
6✔
435
                        select {
3✔
436
                        case <-s.quit:
3✔
437
                                return
3✔
438

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

446
                                for _, update := range topChange.NodeUpdates {
6✔
447
                                        pubKeyStr := string(
3✔
448
                                                update.IdentityKey.
3✔
449
                                                        SerializeCompressed(),
3✔
450
                                        )
3✔
451

3✔
452
                                        // We only care about updates from
3✔
453
                                        // our persistentPeers.
3✔
454
                                        s.mu.RLock()
3✔
455
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
456
                                        s.mu.RUnlock()
3✔
457
                                        if !ok {
6✔
458
                                                continue
3✔
459
                                        }
460

461
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
462
                                                len(update.Addresses))
3✔
463

3✔
464
                                        for _, addr := range update.Addresses {
6✔
465
                                                addrs = append(addrs,
3✔
466
                                                        &lnwire.NetAddress{
3✔
467
                                                                IdentityKey: update.IdentityKey,
3✔
468
                                                                Address:     addr,
3✔
469
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
470
                                                        },
3✔
471
                                                )
3✔
472
                                        }
3✔
473

474
                                        s.mu.Lock()
3✔
475

3✔
476
                                        // Update the stored addresses for this
3✔
477
                                        // to peer to reflect the new set.
3✔
478
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
479

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

490
                                        s.mu.Unlock()
3✔
491

3✔
492
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
493
                                }
494
                        }
495
                }
496
        }()
497

498
        return nil
3✔
499
}
500

501
// CustomMessage is a custom message that is received from a peer.
502
type CustomMessage struct {
503
        // Peer is the peer pubkey
504
        Peer [33]byte
505

506
        // Msg is the custom wire message.
507
        Msg *lnwire.Custom
508
}
509

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

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

534
        if tor.IsOnionHost(host) {
3✔
535
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
536
        }
×
537

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

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

3✔
551
        return func(a net.Addr) (net.Conn, error) {
6✔
552
                lnAddr := a.(*lnwire.NetAddress)
3✔
553
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
554
        }
3✔
555
}
556

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

3✔
568
        var (
3✔
569
                err         error
3✔
570
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
571

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

3✔
579
        var serializedPubKey [33]byte
3✔
580
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
581

3✔
582
        netParams := cfg.ActiveNetParams.Params
3✔
583

3✔
584
        // Initialize the sphinx router.
3✔
585
        replayLog := htlcswitch.NewDecayedLog(
3✔
586
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
587
        )
3✔
588
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
589

3✔
590
        writeBufferPool := pool.NewWriteBuffer(
3✔
591
                pool.DefaultWriteBufferGCInterval,
3✔
592
                pool.DefaultWriteBufferExpiryInterval,
3✔
593
        )
3✔
594

3✔
595
        writePool := pool.NewWrite(
3✔
596
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
597
        )
3✔
598

3✔
599
        readBufferPool := pool.NewReadBuffer(
3✔
600
                pool.DefaultReadBufferGCInterval,
3✔
601
                pool.DefaultReadBufferExpiryInterval,
3✔
602
        )
3✔
603

3✔
604
        readPool := pool.NewRead(
3✔
605
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
606
        )
3✔
607

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

×
613
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
614
                        "aux controllers")
×
615
        }
×
616

617
        // For now, the RBF coop close flag and the taproot channel type cannot
618
        // be used together.
619
        //
620
        // TODO(roasbeef): fix
621
        if cfg.ProtocolOptions.RbfCoopClose &&
3✔
622
                cfg.ProtocolOptions.TaprootChans {
3✔
623

×
624
                return nil, fmt.Errorf("RBF coop close and taproot " +
×
625
                        "channels cannot be used together")
×
626
        }
×
627

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

651
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
652
        registryConfig := invoices.RegistryConfig{
3✔
653
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
654
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
655
                Clock:                       clock.NewDefaultClock(),
3✔
656
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
657
                AcceptAMP:                   cfg.AcceptAMP,
3✔
658
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
659
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
660
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
661
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
662
        }
3✔
663

3✔
664
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
665

3✔
666
        s := &server{
3✔
667
                cfg:            cfg,
3✔
668
                implCfg:        implCfg,
3✔
669
                graphDB:        dbs.GraphDB,
3✔
670
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
671
                addrSource:     addrSource,
3✔
672
                miscDB:         dbs.ChanStateDB,
3✔
673
                invoicesDB:     dbs.InvoiceDB,
3✔
674
                cc:             cc,
3✔
675
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
676
                writePool:      writePool,
3✔
677
                readPool:       readPool,
3✔
678
                chansToRestore: chansToRestore,
3✔
679

3✔
680
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
681
                        cc.ChainNotifier,
3✔
682
                ),
3✔
683
                channelNotifier: channelnotifier.New(
3✔
684
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
685
                ),
3✔
686

3✔
687
                identityECDH:   nodeKeyECDH,
3✔
688
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
689
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
690

3✔
691
                listenAddrs: listenAddrs,
3✔
692

3✔
693
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
694
                // schedule
3✔
695
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
696

3✔
697
                torController: torController,
3✔
698

3✔
699
                persistentPeers:         make(map[string]bool),
3✔
700
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
701
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
702
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
703
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
704
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
705
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
706
                scheduledPeerConnection: make(map[string]func()),
3✔
707
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
708

3✔
709
                peersByPub:                make(map[string]*peer.Brontide),
3✔
710
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
711
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
712
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
713
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
714

3✔
715
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
716

3✔
717
                customMessageServer: subscribe.NewServer(),
3✔
718

3✔
719
                tlsManager: tlsManager,
3✔
720

3✔
721
                remoteSignerClient: remoteSignerClient,
3✔
722

3✔
723
                featureMgr: featureMgr,
3✔
724
                quit:       make(chan struct{}),
3✔
725
        }
3✔
726

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

738
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
739
        if err != nil {
3✔
740
                return nil, err
×
741
        }
×
742

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

3✔
751
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
752

3✔
753
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
754
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
755

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

762
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
763

3✔
764
                return nil
3✔
765
        }
766

767
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
768
        if err != nil {
3✔
769
                return nil, err
×
770
        }
×
771

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

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

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

824
        s.witnessBeacon = newPreimageBeacon(
3✔
825
                dbs.ChanStateDB.NewWitnessCache(),
3✔
826
                s.interceptableSwitch.ForwardPacket,
3✔
827
        )
3✔
828

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

3✔
842
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
843
        if err != nil {
3✔
844
                return nil, err
×
845
        }
×
846
        s.chanStatusMgr = chanStatusMgr
3✔
847

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

×
853
                discoveryTimeout := time.Duration(10 * time.Second)
×
854

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

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

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

881
                        s.natTraversal = pmp
×
882
                }
883
        }
884

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

×
900
                        listenPorts = append(listenPorts, uint16(port))
×
901
                }
×
902

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

916
        // If external IP addresses have been specified, add those to the list
917
        // of this server's addresses.
918
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
919
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
920
                cfg.net.ResolveTCPAddr,
3✔
921
        )
3✔
922
        if err != nil {
3✔
923
                return nil, err
×
924
        }
×
925

926
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
927
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
928

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

940
        // If no alias is provided, default to first 10 characters of public
941
        // key.
942
        alias := cfg.Alias
3✔
943
        if alias == "" {
6✔
944
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
945
        }
3✔
946
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
947
        if err != nil {
3✔
948
                return nil, err
×
949
        }
×
950
        selfNode := &models.LightningNode{
3✔
951
                HaveNodeAnnouncement: true,
3✔
952
                LastUpdate:           time.Now(),
3✔
953
                Addresses:            selfAddrs,
3✔
954
                Alias:                nodeAlias.String(),
3✔
955
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
956
                Color:                color,
3✔
957
        }
3✔
958
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
959

3✔
960
        // Based on the disk representation of the node announcement generated
3✔
961
        // above, we'll generate a node announcement that can go out on the
3✔
962
        // network so we can properly sign it.
3✔
963
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
964
        if err != nil {
3✔
965
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
966
        }
×
967

968
        // With the announcement generated, we'll sign it to properly
969
        // authenticate the message on the network.
970
        authSig, err := netann.SignAnnouncement(
3✔
971
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
972
        )
3✔
973
        if err != nil {
3✔
974
                return nil, fmt.Errorf("unable to generate signature for "+
×
975
                        "self node announcement: %v", err)
×
976
        }
×
977
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
978
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
979
                selfNode.AuthSigBytes,
3✔
980
        )
3✔
981
        if err != nil {
3✔
982
                return nil, err
×
983
        }
×
984

985
        // Finally, we'll update the representation on disk, and update our
986
        // cached in-memory version as well.
987
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
988
                return nil, fmt.Errorf("can't set self node: %w", err)
×
989
        }
×
990
        s.currentNodeAnn = nodeAnn
3✔
991

3✔
992
        // The router will get access to the payment ID sequencer, such that it
3✔
993
        // can generate unique payment IDs.
3✔
994
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
995
        if err != nil {
3✔
996
                return nil, err
×
997
        }
×
998

999
        // Instantiate mission control with config from the sub server.
1000
        //
1001
        // TODO(joostjager): When we are further in the process of moving to sub
1002
        // servers, the mission control instance itself can be moved there too.
1003
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1004

3✔
1005
        // We only initialize a probability estimator if there's no custom one.
3✔
1006
        var estimator routing.Estimator
3✔
1007
        if cfg.Estimator != nil {
3✔
1008
                estimator = cfg.Estimator
×
1009
        } else {
3✔
1010
                switch routingConfig.ProbabilityEstimatorType {
3✔
1011
                case routing.AprioriEstimatorName:
3✔
1012
                        aCfg := routingConfig.AprioriConfig
3✔
1013
                        aprioriConfig := routing.AprioriConfig{
3✔
1014
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1015
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1016
                                AprioriWeight:         aCfg.Weight,
3✔
1017
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1018
                        }
3✔
1019

3✔
1020
                        estimator, err = routing.NewAprioriEstimator(
3✔
1021
                                aprioriConfig,
3✔
1022
                        )
3✔
1023
                        if err != nil {
3✔
1024
                                return nil, err
×
1025
                        }
×
1026

1027
                case routing.BimodalEstimatorName:
×
1028
                        bCfg := routingConfig.BimodalConfig
×
1029
                        bimodalConfig := routing.BimodalConfig{
×
1030
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1031
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1032
                                        bCfg.Scale,
×
1033
                                ),
×
1034
                                BimodalDecayTime: bCfg.DecayTime,
×
1035
                        }
×
1036

×
1037
                        estimator, err = routing.NewBimodalEstimator(
×
1038
                                bimodalConfig,
×
1039
                        )
×
1040
                        if err != nil {
×
1041
                                return nil, err
×
1042
                        }
×
1043

1044
                default:
×
1045
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1046
                                routingConfig.ProbabilityEstimatorType)
×
1047
                }
1048
        }
1049

1050
        mcCfg := &routing.MissionControlConfig{
3✔
1051
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1052
                Estimator:               estimator,
3✔
1053
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1054
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1055
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1056
        }
3✔
1057

3✔
1058
        s.missionController, err = routing.NewMissionController(
3✔
1059
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1060
        )
3✔
1061
        if err != nil {
3✔
1062
                return nil, fmt.Errorf("can't create mission control "+
×
1063
                        "manager: %w", err)
×
1064
        }
×
1065
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1066
                routing.DefaultMissionControlNamespace,
3✔
1067
        )
3✔
1068
        if err != nil {
3✔
1069
                return nil, fmt.Errorf("can't create mission control in the "+
×
1070
                        "default namespace: %w", err)
×
1071
        }
×
1072

1073
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1074
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1075
                int64(routingConfig.AttemptCost),
3✔
1076
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1077
                routingConfig.MinRouteProbability)
3✔
1078

3✔
1079
        pathFindingConfig := routing.PathFindingConfig{
3✔
1080
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1081
                        routingConfig.AttemptCost,
3✔
1082
                ),
3✔
1083
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1084
                MinProbability: routingConfig.MinRouteProbability,
3✔
1085
        }
3✔
1086

3✔
1087
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1088
        if err != nil {
3✔
1089
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1090
        }
×
1091
        paymentSessionSource := &routing.SessionSource{
3✔
1092
                GraphSessionFactory: dbs.GraphDB,
3✔
1093
                SourceNode:          sourceNode,
3✔
1094
                MissionControl:      s.defaultMC,
3✔
1095
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1096
                PathFindingConfig:   pathFindingConfig,
3✔
1097
        }
3✔
1098

3✔
1099
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1100

3✔
1101
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1102

3✔
1103
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1104
                cfg.Routing.StrictZombiePruning
3✔
1105

3✔
1106
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1107
                SelfNode:            selfNode.PubKeyBytes,
3✔
1108
                Graph:               dbs.GraphDB,
3✔
1109
                Chain:               cc.ChainIO,
3✔
1110
                ChainView:           cc.ChainView,
3✔
1111
                Notifier:            cc.ChainNotifier,
3✔
1112
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1113
                GraphPruneInterval:  time.Hour,
3✔
1114
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1115
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1116
                StrictZombiePruning: strictPruning,
3✔
1117
                IsAlias:             aliasmgr.IsAlias,
3✔
1118
        })
3✔
1119
        if err != nil {
3✔
1120
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1121
        }
×
1122

1123
        s.chanRouter, err = routing.New(routing.Config{
3✔
1124
                SelfNode:           selfNode.PubKeyBytes,
3✔
1125
                RoutingGraph:       dbs.GraphDB,
3✔
1126
                Chain:              cc.ChainIO,
3✔
1127
                Payer:              s.htlcSwitch,
3✔
1128
                Control:            s.controlTower,
3✔
1129
                MissionControl:     s.defaultMC,
3✔
1130
                SessionSource:      paymentSessionSource,
3✔
1131
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1132
                NextPaymentID:      sequencer.NextID,
3✔
1133
                PathFindingConfig:  pathFindingConfig,
3✔
1134
                Clock:              clock.NewDefaultClock(),
3✔
1135
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1136
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1137
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1138
        })
3✔
1139
        if err != nil {
3✔
1140
                return nil, fmt.Errorf("can't create router: %w", err)
×
1141
        }
×
1142

1143
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1144
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1145
        if err != nil {
3✔
1146
                return nil, err
×
1147
        }
×
1148
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1149
        if err != nil {
3✔
1150
                return nil, err
×
1151
        }
×
1152

1153
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1154

3✔
1155
        s.authGossiper = discovery.New(discovery.Config{
3✔
1156
                Graph:                 s.graphBuilder,
3✔
1157
                ChainIO:               s.cc.ChainIO,
3✔
1158
                Notifier:              s.cc.ChainNotifier,
3✔
1159
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1160
                Broadcast:             s.BroadcastMessage,
3✔
1161
                ChanSeries:            chanSeries,
3✔
1162
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1163
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1164
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1165
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1166
                        error) {
3✔
1167

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

1197
        accessCfg := &accessManConfig{
3✔
1198
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1199
                        error) {
6✔
1200

3✔
1201
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1202
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1203
                                genesisHash[:],
3✔
1204
                        )
3✔
1205
                },
3✔
1206
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1207
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1208
        }
1209

1210
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1211
        if err != nil {
3✔
1212
                return nil, err
×
1213
        }
×
1214

1215
        s.peerAccessMan = peerAccessMan
3✔
1216

3✔
1217
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1218
        //nolint:ll
3✔
1219
        s.localChanMgr = &localchans.Manager{
3✔
1220
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1221
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1222
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1223
                        *models.ChannelEdgePolicy) error) error {
6✔
1224

3✔
1225
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1226
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
3✔
1227
                                        e *models.ChannelEdgePolicy,
3✔
1228
                                        _ *models.ChannelEdgePolicy) error {
6✔
1229

3✔
1230
                                        // NOTE: The invoked callback here may
3✔
1231
                                        // receive a nil channel policy.
3✔
1232
                                        return cb(c, e)
3✔
1233
                                },
3✔
1234
                        )
1235
                },
1236
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1237
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1238
                FetchChannel:              s.chanStateDB.FetchChannel,
1239
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1240
                        return s.graphBuilder.AddEdge(edge)
×
1241
                },
×
1242
        }
1243

1244
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1245
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1246
        )
3✔
1247
        if err != nil {
3✔
1248
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1249
                return nil, err
×
1250
        }
×
1251

1252
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1253
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1254
        )
3✔
1255
        if err != nil {
3✔
1256
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1257
                return nil, err
×
1258
        }
×
1259

1260
        aggregator := sweep.NewBudgetAggregator(
3✔
1261
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1262
                s.implCfg.AuxSweeper,
3✔
1263
        )
3✔
1264

3✔
1265
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1266
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1267
                Wallet:     cc.Wallet,
3✔
1268
                Estimator:  cc.FeeEstimator,
3✔
1269
                Notifier:   cc.ChainNotifier,
3✔
1270
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1271
        })
3✔
1272

3✔
1273
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1274
                FeeEstimator: cc.FeeEstimator,
3✔
1275
                GenSweepScript: newSweepPkScriptGen(
3✔
1276
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1277
                ),
3✔
1278
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1279
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1280
                Mempool:              cc.MempoolNotifier,
3✔
1281
                Notifier:             cc.ChainNotifier,
3✔
1282
                Store:                sweeperStore,
3✔
1283
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1284
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1285
                Aggregator:           aggregator,
3✔
1286
                Publisher:            s.txPublisher,
3✔
1287
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1288
        })
3✔
1289

3✔
1290
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1291
                ChainIO:             cc.ChainIO,
3✔
1292
                ConfDepth:           1,
3✔
1293
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1294
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1295
                Notifier:            cc.ChainNotifier,
3✔
1296
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1297
                Store:               utxnStore,
3✔
1298
                SweepInput:          s.sweeper.SweepInput,
3✔
1299
                Budget:              s.cfg.Sweeper.Budget,
3✔
1300
        })
3✔
1301

3✔
1302
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1303
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1304
                closureType contractcourt.ChannelCloseType) {
6✔
1305
                // TODO(conner): Properly respect the update and error channels
3✔
1306
                // returned by CloseLink.
3✔
1307

3✔
1308
                // Instruct the switch to close the channel.  Provide no close out
3✔
1309
                // delivery script or target fee per kw because user input is not
3✔
1310
                // available when the remote peer closes the channel.
3✔
1311
                s.htlcSwitch.CloseLink(
3✔
1312
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1313
                )
3✔
1314
        }
3✔
1315

1316
        // We will use the following channel to reliably hand off contract
1317
        // breach events from the ChannelArbitrator to the BreachArbitrator,
1318
        contractBreaches := make(chan *contractcourt.ContractBreachEvent, 1)
3✔
1319

3✔
1320
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1321
                &contractcourt.BreachConfig{
3✔
1322
                        CloseLink: closeLink,
3✔
1323
                        DB:        s.chanStateDB,
3✔
1324
                        Estimator: s.cc.FeeEstimator,
3✔
1325
                        GenSweepScript: newSweepPkScriptGen(
3✔
1326
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1327
                        ),
3✔
1328
                        Notifier:           cc.ChainNotifier,
3✔
1329
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1330
                        ContractBreaches:   contractBreaches,
3✔
1331
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1332
                        Store: contractcourt.NewRetributionStore(
3✔
1333
                                dbs.ChanStateDB,
3✔
1334
                        ),
3✔
1335
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1336
                },
3✔
1337
        )
3✔
1338

3✔
1339
        //nolint:ll
3✔
1340
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1341
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1342
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1343
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1344
                NewSweepAddr: func() ([]byte, error) {
3✔
1345
                        addr, err := newSweepPkScriptGen(
×
1346
                                cc.Wallet, netParams,
×
1347
                        )().Unpack()
×
1348
                        if err != nil {
×
1349
                                return nil, err
×
1350
                        }
×
1351

1352
                        return addr.DeliveryAddress, nil
×
1353
                },
1354
                PublishTx: cc.Wallet.PublishTransaction,
1355
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1356
                        for _, msg := range msgs {
6✔
1357
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1358
                                if err != nil {
3✔
1359
                                        return err
×
1360
                                }
×
1361
                        }
1362
                        return nil
3✔
1363
                },
1364
                IncubateOutputs: func(chanPoint wire.OutPoint,
1365
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1366
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1367
                        broadcastHeight uint32,
1368
                        deadlineHeight fn.Option[int32]) error {
3✔
1369

3✔
1370
                        return s.utxoNursery.IncubateOutputs(
3✔
1371
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1372
                                broadcastHeight, deadlineHeight,
3✔
1373
                        )
3✔
1374
                },
3✔
1375
                PreimageDB:   s.witnessBeacon,
1376
                Notifier:     cc.ChainNotifier,
1377
                Mempool:      cc.MempoolNotifier,
1378
                Signer:       cc.Wallet.Cfg.Signer,
1379
                FeeEstimator: cc.FeeEstimator,
1380
                ChainIO:      cc.ChainIO,
1381
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1382
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1383
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1384
                        return nil
3✔
1385
                },
3✔
1386
                IsOurAddress: cc.Wallet.IsOurAddress,
1387
                ContractBreach: func(chanPoint wire.OutPoint,
1388
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1389

3✔
1390
                        // processACK will handle the BreachArbitrator ACKing
3✔
1391
                        // the event.
3✔
1392
                        finalErr := make(chan error, 1)
3✔
1393
                        processACK := func(brarErr error) {
6✔
1394
                                if brarErr != nil {
3✔
1395
                                        finalErr <- brarErr
×
1396
                                        return
×
1397
                                }
×
1398

1399
                                // If the BreachArbitrator successfully handled
1400
                                // the event, we can signal that the handoff
1401
                                // was successful.
1402
                                finalErr <- nil
3✔
1403
                        }
1404

1405
                        event := &contractcourt.ContractBreachEvent{
3✔
1406
                                ChanPoint:         chanPoint,
3✔
1407
                                ProcessACK:        processACK,
3✔
1408
                                BreachRetribution: breachRet,
3✔
1409
                        }
3✔
1410

3✔
1411
                        // Send the contract breach event to the
3✔
1412
                        // BreachArbitrator.
3✔
1413
                        select {
3✔
1414
                        case contractBreaches <- event:
3✔
1415
                        case <-s.quit:
×
1416
                                return ErrServerShuttingDown
×
1417
                        }
1418

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

1444
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1445
                QueryIncomingCircuit: func(
1446
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1447

3✔
1448
                        // Get the circuit map.
3✔
1449
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1450

3✔
1451
                        // Lookup the outgoing circuit.
3✔
1452
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1453
                        if pc == nil {
5✔
1454
                                return nil
2✔
1455
                        }
2✔
1456

1457
                        return &pc.Incoming
3✔
1458
                },
1459
                AuxLeafStore: implCfg.AuxLeafStore,
1460
                AuxSigner:    implCfg.AuxSigner,
1461
                AuxResolver:  implCfg.AuxContractResolver,
1462
        }, dbs.ChanStateDB)
1463

1464
        // Select the configuration and funding parameters for Bitcoin.
1465
        chainCfg := cfg.Bitcoin
3✔
1466
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1467
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1468

3✔
1469
        var chanIDSeed [32]byte
3✔
1470
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1471
                return nil, err
×
1472
        }
×
1473

1474
        // Wrap the DeleteChannelEdges method so that the funding manager can
1475
        // use it without depending on several layers of indirection.
1476
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1477
                *models.ChannelEdgePolicy, error) {
6✔
1478

3✔
1479
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1480
                        scid.ToUint64(),
3✔
1481
                )
3✔
1482
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1483
                        // This is unlikely but there is a slim chance of this
×
1484
                        // being hit if lnd was killed via SIGKILL and the
×
1485
                        // funding manager was stepping through the delete
×
1486
                        // alias edge logic.
×
1487
                        return nil, nil
×
1488
                } else if err != nil {
3✔
1489
                        return nil, err
×
1490
                }
×
1491

1492
                // Grab our key to find our policy.
1493
                var ourKey [33]byte
3✔
1494
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1495

3✔
1496
                var ourPolicy *models.ChannelEdgePolicy
3✔
1497
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1498
                        ourPolicy = e1
3✔
1499
                } else {
6✔
1500
                        ourPolicy = e2
3✔
1501
                }
3✔
1502

1503
                if ourPolicy == nil {
3✔
1504
                        // Something is wrong, so return an error.
×
1505
                        return nil, fmt.Errorf("we don't have an edge")
×
1506
                }
×
1507

1508
                err = s.graphDB.DeleteChannelEdges(
3✔
1509
                        false, false, scid.ToUint64(),
3✔
1510
                )
3✔
1511
                return ourPolicy, err
3✔
1512
        }
1513

1514
        // For the reservationTimeout and the zombieSweeperInterval different
1515
        // values are set in case we are in a dev environment so enhance test
1516
        // capacilities.
1517
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1518
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1519

3✔
1520
        // Get the development config for funding manager. If we are not in
3✔
1521
        // development mode, this would be nil.
3✔
1522
        var devCfg *funding.DevConfig
3✔
1523
        if lncfg.IsDevBuild() {
6✔
1524
                devCfg = &funding.DevConfig{
3✔
1525
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1526
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1527
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1528
                }
3✔
1529

3✔
1530
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1531
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1532

3✔
1533
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1534
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1535
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1536
        }
3✔
1537

1538
        //nolint:ll
1539
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1540
                Dev:                devCfg,
3✔
1541
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1542
                IDKey:              nodeKeyDesc.PubKey,
3✔
1543
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1544
                Wallet:             cc.Wallet,
3✔
1545
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1546
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1547
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1548
                },
3✔
1549
                Notifier:     cc.ChainNotifier,
1550
                ChannelDB:    s.chanStateDB,
1551
                FeeEstimator: cc.FeeEstimator,
1552
                SignMessage:  cc.MsgSigner.SignMessage,
1553
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1554
                        error) {
3✔
1555

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

3✔
1576
                        // In case the user has explicitly specified
3✔
1577
                        // a default value for the number of
3✔
1578
                        // confirmations, we use it.
3✔
1579
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1580
                        if defaultConf != 0 {
6✔
1581
                                return defaultConf
3✔
1582
                        }
3✔
1583

1584
                        minConf := uint64(3)
×
1585
                        maxConf := uint64(6)
×
1586

×
1587
                        // If this is a wumbo channel, then we'll require the
×
1588
                        // max amount of confirmations.
×
1589
                        if chanAmt > MaxFundingAmount {
×
1590
                                return uint16(maxConf)
×
1591
                        }
×
1592

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

3✔
1615
                        // In case the user has explicitly specified
3✔
1616
                        // a default value for the remote delay, we
3✔
1617
                        // use it.
3✔
1618
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1619
                        if defaultDelay > 0 {
6✔
1620
                                return defaultDelay
3✔
1621
                        }
3✔
1622

1623
                        // If this is a wumbo channel, then we'll require the
1624
                        // max value.
1625
                        if chanAmt > MaxFundingAmount {
×
1626
                                return maxRemoteDelay
×
1627
                        }
×
1628

1629
                        // If not we scale according to channel size.
1630
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1631
                                chanAmt / MaxFundingAmount)
×
1632
                        if delay < minRemoteDelay {
×
1633
                                delay = minRemoteDelay
×
1634
                        }
×
1635
                        if delay > maxRemoteDelay {
×
1636
                                delay = maxRemoteDelay
×
1637
                        }
×
1638
                        return delay
×
1639
                },
1640
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1641
                        peerKey *btcec.PublicKey) error {
3✔
1642

3✔
1643
                        // First, we'll mark this new peer as a persistent peer
3✔
1644
                        // for re-connection purposes. If the peer is not yet
3✔
1645
                        // tracked or the user hasn't requested it to be perm,
3✔
1646
                        // we'll set false to prevent the server from continuing
3✔
1647
                        // to connect to this peer even if the number of
3✔
1648
                        // channels with this peer is zero.
3✔
1649
                        s.mu.Lock()
3✔
1650
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1651
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1652
                                s.persistentPeers[pubStr] = false
3✔
1653
                        }
3✔
1654
                        s.mu.Unlock()
3✔
1655

3✔
1656
                        // With that taken care of, we'll send this channel to
3✔
1657
                        // the chain arb so it can react to on-chain events.
3✔
1658
                        return s.chainArb.WatchNewChannel(channel)
3✔
1659
                },
1660
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1661
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1662
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1663
                },
3✔
1664
                RequiredRemoteChanReserve: func(chanAmt,
1665
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1666

3✔
1667
                        // By default, we'll require the remote peer to maintain
3✔
1668
                        // at least 1% of the total channel capacity at all
3✔
1669
                        // times. If this value ends up dipping below the dust
3✔
1670
                        // limit, then we'll use the dust limit itself as the
3✔
1671
                        // reserve as required by BOLT #2.
3✔
1672
                        reserve := chanAmt / 100
3✔
1673
                        if reserve < dustLimit {
6✔
1674
                                reserve = dustLimit
3✔
1675
                        }
3✔
1676

1677
                        return reserve
3✔
1678
                },
1679
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1680
                        // By default, we'll allow the remote peer to fully
3✔
1681
                        // utilize the full bandwidth of the channel, minus our
3✔
1682
                        // required reserve.
3✔
1683
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1684
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1685
                },
3✔
1686
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1687
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1688
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1689
                        }
3✔
1690

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

1720
        // Next, we'll assemble the sub-system that will maintain an on-disk
1721
        // static backup of the latest channel state.
1722
        chanNotifier := &channelNotifier{
3✔
1723
                chanNotifier: s.channelNotifier,
3✔
1724
                addrs:        s.addrSource,
3✔
1725
        }
3✔
1726
        backupFile := chanbackup.NewMultiFile(
3✔
1727
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1728
        )
3✔
1729
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1730
                s.chanStateDB, s.addrSource,
3✔
1731
        )
3✔
1732
        if err != nil {
3✔
1733
                return nil, err
×
1734
        }
×
1735
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1736
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1737
        )
3✔
1738
        if err != nil {
3✔
1739
                return nil, err
×
1740
        }
×
1741

1742
        // Assemble a peer notifier which will provide clients with subscriptions
1743
        // to peer online and offline events.
1744
        s.peerNotifier = peernotifier.New()
3✔
1745

3✔
1746
        // Create a channel event store which monitors all open channels.
3✔
1747
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1748
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1749
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1750
                },
3✔
1751
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1752
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1753
                },
3✔
1754
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1755
                Clock:           clock.NewDefaultClock(),
1756
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1757
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1758
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1759
        })
1760

1761
        if cfg.WtClient.Active {
6✔
1762
                policy := wtpolicy.DefaultPolicy()
3✔
1763
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1764

3✔
1765
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1766
                // protocol operations on sat/kw.
3✔
1767
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1768
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1769
                )
3✔
1770

3✔
1771
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1772

3✔
1773
                if err := policy.Validate(); err != nil {
3✔
1774
                        return nil, err
×
1775
                }
×
1776

1777
                // authDial is the wrapper around the btrontide.Dial for the
1778
                // watchtower.
1779
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1780
                        netAddr *lnwire.NetAddress,
3✔
1781
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1782

3✔
1783
                        return brontide.Dial(
3✔
1784
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1785
                        )
3✔
1786
                }
3✔
1787

1788
                // buildBreachRetribution is a call-back that can be used to
1789
                // query the BreachRetribution info and channel type given a
1790
                // channel ID and commitment height.
1791
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1792
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1793
                        channeldb.ChannelType, error) {
6✔
1794

3✔
1795
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1796
                                nil, chanID,
3✔
1797
                        )
3✔
1798
                        if err != nil {
3✔
1799
                                return nil, 0, err
×
1800
                        }
×
1801

1802
                        br, err := lnwallet.NewBreachRetribution(
3✔
1803
                                channel, commitHeight, 0, nil,
3✔
1804
                                implCfg.AuxLeafStore,
3✔
1805
                                implCfg.AuxContractResolver,
3✔
1806
                        )
3✔
1807
                        if err != nil {
3✔
1808
                                return nil, 0, err
×
1809
                        }
×
1810

1811
                        return br, channel.ChanType, nil
3✔
1812
                }
1813

1814
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1815

3✔
1816
                // Copy the policy for legacy channels and set the blob flag
3✔
1817
                // signalling support for anchor channels.
3✔
1818
                anchorPolicy := policy
3✔
1819
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1820

3✔
1821
                // Copy the policy for legacy channels and set the blob flag
3✔
1822
                // signalling support for taproot channels.
3✔
1823
                taprootPolicy := policy
3✔
1824
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1825
                        blob.FlagTaprootChannel,
3✔
1826
                )
3✔
1827

3✔
1828
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1829
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1830
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1831
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1832
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1833
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1834
                                error) {
6✔
1835

3✔
1836
                                return s.channelNotifier.
3✔
1837
                                        SubscribeChannelEvents()
3✔
1838
                        },
3✔
1839
                        Signer: cc.Wallet.Cfg.Signer,
1840
                        NewAddress: func() ([]byte, error) {
3✔
1841
                                addr, err := newSweepPkScriptGen(
3✔
1842
                                        cc.Wallet, netParams,
3✔
1843
                                )().Unpack()
3✔
1844
                                if err != nil {
3✔
1845
                                        return nil, err
×
1846
                                }
×
1847

1848
                                return addr.DeliveryAddress, nil
3✔
1849
                        },
1850
                        SecretKeyRing:      s.cc.KeyRing,
1851
                        Dial:               cfg.net.Dial,
1852
                        AuthDial:           authDial,
1853
                        DB:                 dbs.TowerClientDB,
1854
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1855
                        MinBackoff:         10 * time.Second,
1856
                        MaxBackoff:         5 * time.Minute,
1857
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1858
                }, policy, anchorPolicy, taprootPolicy)
1859
                if err != nil {
3✔
1860
                        return nil, err
×
1861
                }
×
1862
        }
1863

1864
        if len(cfg.ExternalHosts) != 0 {
3✔
1865
                advertisedIPs := make(map[string]struct{})
×
1866
                for _, addr := range s.currentNodeAnn.Addresses {
×
1867
                        advertisedIPs[addr.String()] = struct{}{}
×
1868
                }
×
1869

1870
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1871
                        Hosts:         cfg.ExternalHosts,
×
1872
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1873
                        LookupHost: func(host string) (net.Addr, error) {
×
1874
                                return lncfg.ParseAddressString(
×
1875
                                        host, strconv.Itoa(defaultPeerPort),
×
1876
                                        cfg.net.ResolveTCPAddr,
×
1877
                                )
×
NEW
1878
                        },
×
1879
                        AdvertisedIPs: advertisedIPs,
1880
                        AnnounceNewIPs: netann.IPAnnouncer(
1881
                                func(modifier ...netann.NodeAnnModifier) (
NEW
1882
                                        lnwire.NodeAnnouncement, error) {
×
NEW
1883

×
UNCOV
1884
                                        return s.genNodeAnnouncement(
×
UNCOV
1885
                                                nil, modifier...,
×
UNCOV
1886
                                        )
×
1887
                                }),
×
1888
                })
1889
        }
1890

1891
        // Create liveness monitor.
1892
        err = s.createLivenessMonitor(
3✔
1893
                context.Background(), cfg, cc, leaderElector,
3✔
1894
        )
3✔
1895
        if err != nil {
3✔
UNCOV
1896
                return nil, err
×
UNCOV
1897
        }
×
1898

1899
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1900
        for i, listenAddr := range listenAddrs {
6✔
1901
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1902
                // doesn't need to call the general lndResolveTCP function
3✔
1903
                // since we are resolving a local address.
3✔
1904

3✔
1905
                // RESOLVE: We are actually partially accepting inbound
3✔
1906
                // connection requests when we call NewListener.
3✔
1907
                listeners[i], err = brontide.NewListener(
3✔
1908
                        nodeKeyECDH, listenAddr.String(),
3✔
1909
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1910
                )
3✔
1911
                if err != nil {
3✔
1912
                        return nil, err
×
1913
                }
×
1914
        }
1915

1916
        // Create the connection manager which will be responsible for
1917
        // maintaining persistent outbound connections and also accepting new
1918
        // incoming connections
1919
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1920
                Listeners:      listeners,
3✔
1921
                OnAccept:       s.InboundPeerConnected,
3✔
1922
                RetryDuration:  time.Second * 5,
3✔
1923
                TargetOutbound: 100,
3✔
1924
                Dial: noiseDial(
3✔
1925
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1926
                ),
3✔
1927
                OnConnection: s.OutboundPeerConnected,
3✔
1928
        })
3✔
1929
        if err != nil {
3✔
1930
                return nil, err
×
1931
        }
×
1932
        s.connMgr = cmgr
3✔
1933

3✔
1934
        // Finally, register the subsystems in blockbeat.
3✔
1935
        s.registerBlockConsumers()
3✔
1936

3✔
1937
        return s, nil
3✔
1938
}
1939

1940
// UpdateRoutingConfig is a callback function to update the routing config
1941
// values in the main cfg.
1942
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1943
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1944

3✔
1945
        switch c := cfg.Estimator.Config().(type) {
3✔
1946
        case routing.AprioriConfig:
3✔
1947
                routerCfg.ProbabilityEstimatorType =
3✔
1948
                        routing.AprioriEstimatorName
3✔
1949

3✔
1950
                targetCfg := routerCfg.AprioriConfig
3✔
1951
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1952
                targetCfg.Weight = c.AprioriWeight
3✔
1953
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1954
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1955

1956
        case routing.BimodalConfig:
3✔
1957
                routerCfg.ProbabilityEstimatorType =
3✔
1958
                        routing.BimodalEstimatorName
3✔
1959

3✔
1960
                targetCfg := routerCfg.BimodalConfig
3✔
1961
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1962
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1963
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1964
        }
1965

1966
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1967
}
1968

1969
// registerBlockConsumers registers the subsystems that consume block events.
1970
// By calling `RegisterQueue`, a list of subsystems are registered in the
1971
// blockbeat for block notifications. When a new block arrives, the subsystems
1972
// in the same queue are notified sequentially, and different queues are
1973
// notified concurrently.
1974
//
1975
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1976
// a new `RegisterQueue` call.
1977
func (s *server) registerBlockConsumers() {
3✔
1978
        // In this queue, when a new block arrives, it will be received and
3✔
1979
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1980
        consumers := []chainio.Consumer{
3✔
1981
                s.chainArb,
3✔
1982
                s.sweeper,
3✔
1983
                s.txPublisher,
3✔
1984
        }
3✔
1985
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1986
}
3✔
1987

1988
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1989
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1990
// may differ from what is on disk.
1991
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1992
        error) {
3✔
1993

3✔
1994
        data, err := u.DataToSign()
3✔
1995
        if err != nil {
3✔
1996
                return nil, err
×
1997
        }
×
1998

1999
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
2000
}
2001

2002
// createLivenessMonitor creates a set of health checks using our configured
2003
// values and uses these checks to create a liveness monitor. Available
2004
// health checks,
2005
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
2006
//   - diskCheck
2007
//   - tlsHealthCheck
2008
//   - torController, only created when tor is enabled.
2009
//
2010
// If a health check has been disabled by setting attempts to 0, our monitor
2011
// will not run it.
2012
func (s *server) createLivenessMonitor(ctx context.Context, cfg *Config,
2013
        cc *chainreg.ChainControl, leaderElector cluster.LeaderElector) error {
3✔
2014

3✔
2015
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2016
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2017
                srvrLog.Info("Disabling chain backend checks for " +
×
2018
                        "nochainbackend mode")
×
2019

×
2020
                chainBackendAttempts = 0
×
2021
        }
×
2022

2023
        chainHealthCheck := healthcheck.NewObservation(
3✔
2024
                "chain backend",
3✔
2025
                cc.HealthCheck,
3✔
2026
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2027
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2028
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2029
                chainBackendAttempts,
3✔
2030
        )
3✔
2031

3✔
2032
        diskCheck := healthcheck.NewObservation(
3✔
2033
                "disk space",
3✔
2034
                func() error {
3✔
2035
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2036
                                cfg.LndDir,
×
2037
                        )
×
2038
                        if err != nil {
×
2039
                                return err
×
2040
                        }
×
2041

2042
                        // If we have more free space than we require,
2043
                        // we return a nil error.
2044
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2045
                                return nil
×
2046
                        }
×
2047

2048
                        return fmt.Errorf("require: %v free space, got: %v",
×
2049
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2050
                                free)
×
2051
                },
2052
                cfg.HealthChecks.DiskCheck.Interval,
2053
                cfg.HealthChecks.DiskCheck.Timeout,
2054
                cfg.HealthChecks.DiskCheck.Backoff,
2055
                cfg.HealthChecks.DiskCheck.Attempts,
2056
        )
2057

2058
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2059
                "tls",
3✔
2060
                func() error {
3✔
2061
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2062
                                s.cc.KeyRing,
×
2063
                        )
×
2064
                        if err != nil {
×
2065
                                return err
×
2066
                        }
×
2067
                        if expired {
×
2068
                                return fmt.Errorf("TLS certificate is "+
×
2069
                                        "expired as of %v", expTime)
×
2070
                        }
×
2071

2072
                        // If the certificate is not outdated, no error needs
2073
                        // to be returned
2074
                        return nil
×
2075
                },
2076
                cfg.HealthChecks.TLSCheck.Interval,
2077
                cfg.HealthChecks.TLSCheck.Timeout,
2078
                cfg.HealthChecks.TLSCheck.Backoff,
2079
                cfg.HealthChecks.TLSCheck.Attempts,
2080
        )
2081

2082
        checks := []*healthcheck.Observation{
3✔
2083
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2084
        }
3✔
2085

3✔
2086
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2087
        if s.torController != nil {
3✔
2088
                torConnectionCheck := healthcheck.NewObservation(
×
2089
                        "tor connection",
×
2090
                        func() error {
×
2091
                                return healthcheck.CheckTorServiceStatus(
×
NEW
2092
                                        s.torController,
×
NEW
2093
                                        s.createNewHiddenService,
×
NEW
2094
                                )
×
NEW
2095
                        },
×
2096
                        cfg.HealthChecks.TorConnection.Interval,
2097
                        cfg.HealthChecks.TorConnection.Timeout,
2098
                        cfg.HealthChecks.TorConnection.Backoff,
2099
                        cfg.HealthChecks.TorConnection.Attempts,
2100
                )
2101
                checks = append(checks, torConnectionCheck)
×
2102
        }
2103

2104
        // If remote signing is enabled, add the healthcheck for the remote
2105
        // signing RPC interface.
2106
        if s.cfg.RemoteSigner.Enable {
6✔
2107
                rpckKeyRing, ok := cc.Wc.(*rpcwallet.RPCKeyRing)
3✔
2108
                if !ok {
3✔
NEW
2109
                        return errors.New("incorrect WalletController type, " +
×
NEW
2110
                                "expected *rpcwallet.RPCKeyRing")
×
UNCOV
2111
                }
×
2112

2113
                innerTimeout := cfg.HealthChecks.RemoteSigner.Timeout
3✔
2114

3✔
2115
                // Because we have two cascading timeouts here, we need to add
3✔
2116
                // some slack to the "outer" one of them in case the "inner"
3✔
2117
                // returns exactly on time.
3✔
2118
                outerTimeout := innerTimeout + time.Millisecond*10
3✔
2119

3✔
2120
                rsConnectionCheck := healthcheck.NewObservation(
3✔
2121
                        "remote signer connection",
3✔
2122
                        rpcwallet.HealthCheck(
3✔
2123
                                ctx,
3✔
2124
                                rpckKeyRing.RemoteSignerConnection(),
3✔
2125
                                // For the health check we might to be even
3✔
2126
                                // stricter than the initial/normal connect, so
3✔
2127
                                // we use the health check timeout.
3✔
2128
                                innerTimeout,
3✔
2129
                        ),
3✔
2130
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2131
                        outerTimeout,
3✔
2132
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2133
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2134
                )
3✔
2135
                checks = append(checks, rsConnectionCheck)
3✔
2136
        }
2137

2138
        // If we have a leader elector, we add a health check to ensure we are
2139
        // still the leader. During normal operation, we should always be the
2140
        // leader, but there are circumstances where this may change, such as
2141
        // when we lose network connectivity for long enough expiring out lease.
2142
        if leaderElector != nil {
3✔
2143
                leaderCheck := healthcheck.NewObservation(
×
2144
                        "leader status",
×
2145
                        func() error {
×
2146
                                // Check if we are still the leader. Note that
×
2147
                                // we don't need to use a timeout context here
×
2148
                                // as the healthcheck observer will handle the
×
2149
                                // timeout case for us.
×
2150
                                timeoutCtx, cancel := context.WithTimeout(
×
2151
                                        ctx,
×
2152
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2153
                                )
×
2154
                                defer cancel()
×
2155

×
2156
                                leader, err := leaderElector.IsLeader(
×
2157
                                        timeoutCtx,
×
2158
                                )
×
2159
                                if err != nil {
×
2160
                                        return fmt.Errorf("unable to check if "+
×
2161
                                                "still leader: %v", err)
×
2162
                                }
×
2163

2164
                                if !leader {
×
2165
                                        srvrLog.Debug("Not the current leader")
×
2166
                                        return fmt.Errorf("not the current " +
×
2167
                                                "leader")
×
2168
                                }
×
2169

2170
                                return nil
×
2171
                        },
2172
                        cfg.HealthChecks.LeaderCheck.Interval,
2173
                        cfg.HealthChecks.LeaderCheck.Timeout,
2174
                        cfg.HealthChecks.LeaderCheck.Backoff,
2175
                        cfg.HealthChecks.LeaderCheck.Attempts,
2176
                )
2177

UNCOV
2178
                checks = append(checks, leaderCheck)
×
2179
        }
2180

2181
        // If we have not disabled all of our health checks, we create a
2182
        // liveness monitor with our configured checks.
2183
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2184
                &healthcheck.Config{
3✔
2185
                        Checks:   checks,
3✔
2186
                        Shutdown: srvrLog.Criticalf,
3✔
2187
                },
3✔
2188
        )
3✔
2189

3✔
2190
        return nil
3✔
2191
}
2192

2193
// Started returns true if the server has been started, and false otherwise.
2194
// NOTE: This function is safe for concurrent access.
2195
func (s *server) Started() bool {
3✔
2196
        return atomic.LoadInt32(&s.active) != 0
3✔
2197
}
3✔
2198

2199
// cleaner is used to aggregate "cleanup" functions during an operation that
2200
// starts several subsystems. In case one of the subsystem fails to start
2201
// and a proper resource cleanup is required, the "run" method achieves this
2202
// by running all these added "cleanup" functions.
2203
type cleaner []func() error
2204

2205
// add is used to add a cleanup function to be called when
2206
// the run function is executed.
2207
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2208
        return append(c, cleanup)
3✔
2209
}
3✔
2210

2211
// run is used to run all the previousely added cleanup functions.
2212
func (c cleaner) run() {
×
2213
        for i := len(c) - 1; i >= 0; i-- {
×
2214
                if err := c[i](); err != nil {
×
2215
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2216
                }
×
2217
        }
2218
}
2219

2220
// startLowLevelServices starts the low-level services of the server. These
2221
// services must be started successfully before running the main server. The
2222
// services are,
2223
// 1. the chain notifier.
2224
//
2225
// TODO(yy): identify and add more low-level services here.
2226
func (s *server) startLowLevelServices() error {
3✔
2227
        var startErr error
3✔
2228

3✔
2229
        cleanup := cleaner{}
3✔
2230

3✔
2231
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2232
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2233
                startErr = err
×
2234
        }
×
2235

2236
        if startErr != nil {
3✔
2237
                cleanup.run()
×
2238
        }
×
2239

2240
        return startErr
3✔
2241
}
2242

2243
// Start starts the main daemon server, all requested listeners, and any helper
2244
// goroutines.
2245
// NOTE: This function is safe for concurrent access.
2246
//
2247
//nolint:funlen
2248
func (s *server) Start() error {
3✔
2249
        // Get the current blockbeat.
3✔
2250
        beat, err := s.getStartingBeat()
3✔
2251
        if err != nil {
3✔
2252
                return err
×
2253
        }
×
2254

2255
        var startErr error
3✔
2256

3✔
2257
        // If one sub system fails to start, the following code ensures that the
3✔
2258
        // previous started ones are stopped. It also ensures a proper wallet
3✔
2259
        // shutdown which is important for releasing its resources (boltdb, etc...)
3✔
2260
        cleanup := cleaner{}
3✔
2261

3✔
2262
        s.start.Do(func() {
6✔
2263
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2264
                if err := s.customMessageServer.Start(); err != nil {
3✔
2265
                        startErr = err
×
2266
                        return
×
2267
                }
×
2268

2269
                if s.hostAnn != nil {
3✔
2270
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
NEW
2271
                        if err := s.hostAnn.Start(); err != nil {
×
NEW
2272
                                startErr = err
×
NEW
2273
                                return
×
NEW
2274
                        }
×
2275
                }
2276

2277
                if s.livenessMonitor != nil {
6✔
2278
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2279
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2280
                                startErr = err
×
2281
                                return
×
2282
                        }
×
2283
                }
2284

2285
                ctx := context.TODO()
3✔
2286

3✔
2287
                cleanup = cleanup.add(s.remoteSignerClient.Stop)
3✔
2288
                if err := s.remoteSignerClient.Start(ctx); err != nil {
3✔
2289
                        startErr = err
×
2290
                        return
×
UNCOV
2291
                }
×
2292

2293
                // Start the notification server. This is used so channel
2294
                // management goroutines can be notified when a funding
2295
                // transaction reaches a sufficient number of confirmations, or
2296
                // when the input for the funding transaction is spent in an
2297
                // attempt at an uncooperative close by the counterparty.
2298
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2299
                if err := s.sigPool.Start(); err != nil {
3✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

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

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

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

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

2328
                cleanup = cleanup.add(func() error {
3✔
2329
                        return s.peerNotifier.Stop()
×
2330
                })
×
2331
                if err := s.peerNotifier.Start(); err != nil {
3✔
2332
                        startErr = err
×
2333
                        return
×
2334
                }
×
2335

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

2342
                if s.towerClientMgr != nil {
6✔
2343
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2344
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2345
                                startErr = err
×
2346
                                return
×
2347
                        }
×
2348
                }
2349

2350
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2351
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2352
                        startErr = err
×
2353
                        return
×
2354
                }
×
2355

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

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

2368
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2369
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2370
                        startErr = err
×
2371
                        return
×
2372
                }
×
2373

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

2380
                // htlcSwitch must be started before chainArb since the latter
2381
                // relies on htlcSwitch to deliver resolution message upon
2382
                // start.
2383
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2384
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2385
                        startErr = err
×
2386
                        return
×
2387
                }
×
2388

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

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

2401
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2402
                if err := s.chainArb.Start(beat); err != nil {
3✔
2403
                        startErr = err
×
2404
                        return
×
2405
                }
×
2406

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

2413
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2414
                if err := s.chanRouter.Start(); err != nil {
3✔
2415
                        startErr = err
×
2416
                        return
×
2417
                }
×
2418
                // The authGossiper depends on the chanRouter and therefore
2419
                // should be started after it.
2420
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2421
                if err := s.authGossiper.Start(); err != nil {
3✔
2422
                        startErr = err
×
2423
                        return
×
2424
                }
×
2425

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

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

2438
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2439
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2440
                        startErr = err
×
2441
                        return
×
2442
                }
×
2443

2444
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2445
                if err := s.chanEventStore.Start(); err != nil {
3✔
2446
                        startErr = err
×
2447
                        return
×
2448
                }
×
2449

2450
                cleanup.add(func() error {
3✔
2451
                        s.missionController.StopStoreTickers()
×
2452
                        return nil
×
2453
                })
×
2454
                s.missionController.RunStoreTickers()
3✔
2455

3✔
2456
                // Before we start the connMgr, we'll check to see if we have
3✔
2457
                // any backups to recover. We do this now as we want to ensure
3✔
2458
                // that have all the information we need to handle channel
3✔
2459
                // recovery _before_ we even accept connections from any peers.
3✔
2460
                chanRestorer := &chanDBRestorer{
3✔
2461
                        db:         s.chanStateDB,
3✔
2462
                        secretKeys: s.cc.KeyRing,
3✔
2463
                        chainArb:   s.chainArb,
3✔
2464
                }
3✔
2465
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2466
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2467
                                s.chansToRestore.PackedSingleChanBackups,
×
2468
                                s.cc.KeyRing, chanRestorer, s,
×
2469
                        )
×
2470
                        if err != nil {
×
2471
                                startErr = fmt.Errorf("unable to unpack single "+
×
2472
                                        "backups: %v", err)
×
2473
                                return
×
2474
                        }
×
2475
                }
2476
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2477
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2478
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2479
                                s.cc.KeyRing, chanRestorer, s,
3✔
2480
                        )
3✔
2481
                        if err != nil {
3✔
2482
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2483
                                        "backup: %v", err)
×
2484
                                return
×
2485
                        }
×
2486
                }
2487

2488
                // chanSubSwapper must be started after the `channelNotifier`
2489
                // because it depends on channel events as a synchronization
2490
                // point.
2491
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2492
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2493
                        startErr = err
×
2494
                        return
×
2495
                }
×
2496

2497
                if s.torController != nil {
3✔
2498
                        cleanup = cleanup.add(s.torController.Stop)
×
2499
                        if err := s.createNewHiddenService(); err != nil {
×
2500
                                startErr = err
×
2501
                                return
×
2502
                        }
×
2503
                }
2504

2505
                if s.natTraversal != nil {
3✔
2506
                        s.wg.Add(1)
×
2507
                        go s.watchExternalIP()
×
2508
                }
×
2509

2510
                // Start connmgr last to prevent connections before init.
2511
                cleanup = cleanup.add(func() error {
3✔
2512
                        s.connMgr.Stop()
×
2513
                        return nil
×
2514
                })
×
2515

2516
                // RESOLVE: s.connMgr.Start() is called here, but
2517
                // brontide.NewListener() is called in newServer. This means
2518
                // that we are actually listening and partially accepting
2519
                // inbound connections even before the connMgr starts.
2520
                s.connMgr.Start()
3✔
2521

3✔
2522
                // If peers are specified as a config option, we'll add those
3✔
2523
                // peers first.
3✔
2524
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2525
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2526
                                peerAddrCfg,
3✔
2527
                        )
3✔
2528
                        if err != nil {
3✔
2529
                                startErr = fmt.Errorf("unable to parse peer "+
×
2530
                                        "pubkey from config: %v", err)
×
2531
                                return
×
2532
                        }
×
2533
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2534
                        if err != nil {
3✔
2535
                                startErr = fmt.Errorf("unable to parse peer "+
×
2536
                                        "address provided as a config option: "+
×
2537
                                        "%v", err)
×
2538
                                return
×
2539
                        }
×
2540

2541
                        peerAddr := &lnwire.NetAddress{
3✔
2542
                                IdentityKey: parsedPubkey,
3✔
2543
                                Address:     addr,
3✔
2544
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2545
                        }
3✔
2546

3✔
2547
                        err = s.ConnectToPeer(
3✔
2548
                                peerAddr, true,
3✔
2549
                                s.cfg.ConnectionTimeout,
3✔
2550
                        )
3✔
2551
                        if err != nil {
3✔
2552
                                startErr = fmt.Errorf("unable to connect to "+
×
2553
                                        "peer address provided as a config "+
×
2554
                                        "option: %v", err)
×
2555
                                return
×
2556
                        }
×
2557
                }
2558

2559
                // Subscribe to NodeAnnouncements that advertise new addresses
2560
                // our persistent peers.
2561
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2562
                        startErr = err
×
2563
                        return
×
2564
                }
×
2565

2566
                // With all the relevant sub-systems started, we'll now attempt
2567
                // to establish persistent connections to our direct channel
2568
                // collaborators within the network. Before doing so however,
2569
                // we'll prune our set of link nodes found within the database
2570
                // to ensure we don't reconnect to any nodes we no longer have
2571
                // open channels with.
2572
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2573
                        startErr = err
×
2574
                        return
×
2575
                }
×
2576
                if err := s.establishPersistentConnections(); err != nil {
3✔
2577
                        startErr = err
×
2578
                        return
×
2579
                }
×
2580

2581
                // setSeedList is a helper function that turns multiple DNS seed
2582
                // server tuples from the command line or config file into the
2583
                // data structure we need and does a basic formal sanity check
2584
                // in the process.
2585
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2586
                        if len(tuples) == 0 {
×
2587
                                return
×
2588
                        }
×
2589

2590
                        result := make([][2]string, len(tuples))
×
2591
                        for idx, tuple := range tuples {
×
2592
                                tuple = strings.TrimSpace(tuple)
×
2593
                                if len(tuple) == 0 {
×
2594
                                        return
×
2595
                                }
×
2596

2597
                                servers := strings.Split(tuple, ",")
×
2598
                                if len(servers) > 2 || len(servers) == 0 {
×
2599
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2600
                                                "seed tuple: %v", servers)
×
2601
                                        return
×
2602
                                }
×
2603

2604
                                copy(result[idx][:], servers)
×
2605
                        }
2606

2607
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2608
                }
2609

2610
                // Let users overwrite the DNS seed nodes. We only allow them
2611
                // for bitcoin mainnet/testnet/signet.
2612
                if s.cfg.Bitcoin.MainNet {
3✔
2613
                        setSeedList(
×
2614
                                s.cfg.Bitcoin.DNSSeeds,
×
2615
                                chainreg.BitcoinMainnetGenesis,
×
2616
                        )
×
2617
                }
×
2618
                if s.cfg.Bitcoin.TestNet3 {
3✔
2619
                        setSeedList(
×
2620
                                s.cfg.Bitcoin.DNSSeeds,
×
2621
                                chainreg.BitcoinTestnetGenesis,
×
2622
                        )
×
2623
                }
×
2624
                if s.cfg.Bitcoin.SigNet {
3✔
2625
                        setSeedList(
×
2626
                                s.cfg.Bitcoin.DNSSeeds,
×
2627
                                chainreg.BitcoinSignetGenesis,
×
2628
                        )
×
2629
                }
×
2630

2631
                // If network bootstrapping hasn't been disabled, then we'll
2632
                // configure the set of active bootstrappers, and launch a
2633
                // dedicated goroutine to maintain a set of persistent
2634
                // connections.
2635
                if shouldPeerBootstrap(s.cfg) {
3✔
2636
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2637
                        if err != nil {
×
2638
                                startErr = err
×
2639
                                return
×
2640
                        }
×
2641

2642
                        s.wg.Add(1)
×
2643
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2644
                } else {
3✔
2645
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2646
                }
3✔
2647

2648
                // Start the blockbeat after all other subsystems have been
2649
                // started so they are ready to receive new blocks.
2650
                cleanup = cleanup.add(func() error {
3✔
2651
                        s.blockbeatDispatcher.Stop()
×
2652
                        return nil
×
2653
                })
×
2654
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2655
                        startErr = err
×
2656
                        return
×
2657
                }
×
2658

2659
                // Set the active flag now that we've completed the full
2660
                // startup.
2661
                atomic.StoreInt32(&s.active, 1)
3✔
2662
        })
2663

2664
        if startErr != nil {
3✔
2665
                cleanup.run()
×
2666
        }
×
2667
        return startErr
3✔
2668
}
2669

2670
// Stop gracefully shutsdown the main daemon server. This function will signal
2671
// any active goroutines, or helper objects to exit, then blocks until they've
2672
// all successfully exited. Additionally, any/all listeners are closed.
2673
// NOTE: This function is safe for concurrent access.
2674
func (s *server) Stop() error {
3✔
2675
        s.stop.Do(func() {
6✔
2676
                atomic.StoreInt32(&s.stopping, 1)
3✔
2677

3✔
2678
                close(s.quit)
3✔
2679

3✔
2680
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2681
                s.connMgr.Stop()
3✔
2682

3✔
2683
                // Stop dispatching blocks to other systems immediately.
3✔
2684
                s.blockbeatDispatcher.Stop()
3✔
2685

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

2745
                // Update channel.backup file. Make sure to do it before
2746
                // stopping chanSubSwapper.
2747
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2748
                        s.chanStateDB, s.addrSource,
3✔
2749
                )
3✔
2750
                if err != nil {
3✔
2751
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2752
                                err)
×
2753
                } else {
3✔
2754
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2755
                        if err != nil {
6✔
2756
                                srvrLog.Warnf("Manual update of channel "+
3✔
2757
                                        "backup failed: %v", err)
3✔
2758
                        }
3✔
2759
                }
2760

2761
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
UNCOV
2762
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
UNCOV
2763
                }
×
2764
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
UNCOV
2765
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2766
                }
×
2767
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
UNCOV
2768
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2769
                                err)
×
2770
                }
×
2771
                if err := s.remoteSignerClient.Stop(); err != nil {
3✔
2772
                        srvrLog.Warnf("Unable to stop remote signer "+
×
2773
                                "client: %v", err)
×
2774
                }
×
2775
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2776
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2777
                                err)
×
2778
                }
×
2779
                s.missionController.StopStoreTickers()
3✔
2780

3✔
2781
                // Disconnect from each active peers to ensure that
3✔
2782
                // peerTerminationWatchers signal completion to each peer.
3✔
2783
                for _, peer := range s.Peers() {
6✔
2784
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2785
                        if err != nil {
3✔
2786
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2787
                                        "received error: %v", peer.IdentityKey(),
×
2788
                                        err,
×
2789
                                )
×
2790
                        }
×
2791
                }
2792

2793
                // Now that all connections have been torn down, stop the tower
2794
                // client which will reliably flush all queued states to the
2795
                // tower. If this is halted for any reason, the force quit timer
2796
                // will kick in and abort to allow this method to return.
2797
                if s.towerClientMgr != nil {
6✔
2798
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2799
                                srvrLog.Warnf("Unable to shut down tower "+
×
2800
                                        "client manager: %v", err)
×
2801
                        }
×
2802
                }
2803

2804
                if s.hostAnn != nil {
3✔
2805
                        if err := s.hostAnn.Stop(); err != nil {
×
2806
                                srvrLog.Warnf("unable to shut down host "+
×
2807
                                        "annoucner: %v", err)
×
2808
                        }
×
2809
                }
2810

2811
                if s.livenessMonitor != nil {
6✔
2812
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2813
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2814
                                        "monitor: %v", err)
×
2815
                        }
×
2816
                }
2817

2818
                // Wait for all lingering goroutines to quit.
2819
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2820
                s.wg.Wait()
3✔
2821

3✔
2822
                srvrLog.Debug("Stopping buffer pools...")
3✔
2823
                s.sigPool.Stop()
3✔
2824
                s.writePool.Stop()
3✔
2825
                s.readPool.Stop()
3✔
2826
        })
2827

2828
        return nil
3✔
2829
}
2830

2831
// Stopped returns true if the server has been instructed to shutdown.
2832
// NOTE: This function is safe for concurrent access.
2833
func (s *server) Stopped() bool {
3✔
2834
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2835
}
3✔
2836

2837
// configurePortForwarding attempts to set up port forwarding for the different
2838
// ports that the server will be listening on.
2839
//
2840
// NOTE: This should only be used when using some kind of NAT traversal to
2841
// automatically set up forwarding rules.
2842
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2843
        ip, err := s.natTraversal.ExternalIP()
×
2844
        if err != nil {
×
2845
                return nil, err
×
2846
        }
×
2847
        s.lastDetectedIP = ip
×
2848

×
2849
        externalIPs := make([]string, 0, len(ports))
×
2850
        for _, port := range ports {
×
2851
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2852
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2853
                        continue
×
2854
                }
2855

2856
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2857
                externalIPs = append(externalIPs, hostIP)
×
2858
        }
2859

2860
        return externalIPs, nil
×
2861
}
2862

2863
// removePortForwarding attempts to clear the forwarding rules for the different
2864
// ports the server is currently listening on.
2865
//
2866
// NOTE: This should only be used when using some kind of NAT traversal to
2867
// automatically set up forwarding rules.
2868
func (s *server) removePortForwarding() {
×
2869
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2870
        for _, port := range forwardedPorts {
×
2871
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2872
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2873
                                "port %d: %v", port, err)
×
2874
                }
×
2875
        }
2876
}
2877

2878
// watchExternalIP continuously checks for an updated external IP address every
2879
// 15 minutes. Once a new IP address has been detected, it will automatically
2880
// handle port forwarding rules and send updated node announcements to the
2881
// currently connected peers.
2882
//
2883
// NOTE: This MUST be run as a goroutine.
2884
func (s *server) watchExternalIP() {
×
2885
        defer s.wg.Done()
×
2886

×
2887
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2888
        // up by the server.
×
2889
        defer s.removePortForwarding()
×
2890

×
2891
        // Keep track of the external IPs set by the user to avoid replacing
×
2892
        // them when detecting a new IP.
×
2893
        ipsSetByUser := make(map[string]struct{})
×
2894
        for _, ip := range s.cfg.ExternalIPs {
×
2895
                ipsSetByUser[ip.String()] = struct{}{}
×
2896
        }
×
2897

2898
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2899

×
2900
        ticker := time.NewTicker(15 * time.Minute)
×
2901
        defer ticker.Stop()
×
2902
out:
×
2903
        for {
×
2904
                select {
×
2905
                case <-ticker.C:
×
2906
                        // We'll start off by making sure a new IP address has
×
2907
                        // been detected.
×
2908
                        ip, err := s.natTraversal.ExternalIP()
×
2909
                        if err != nil {
×
2910
                                srvrLog.Debugf("Unable to retrieve the "+
×
2911
                                        "external IP address: %v", err)
×
2912
                                continue
×
2913
                        }
2914

2915
                        // Periodically renew the NAT port forwarding.
2916
                        for _, port := range forwardedPorts {
×
2917
                                err := s.natTraversal.AddPortMapping(port)
×
2918
                                if err != nil {
×
2919
                                        srvrLog.Warnf("Unable to automatically "+
×
2920
                                                "re-create port forwarding using %s: %v",
×
2921
                                                s.natTraversal.Name(), err)
×
2922
                                } else {
×
2923
                                        srvrLog.Debugf("Automatically re-created "+
×
2924
                                                "forwarding for port %d using %s to "+
×
2925
                                                "advertise external IP",
×
2926
                                                port, s.natTraversal.Name())
×
2927
                                }
×
2928
                        }
2929

2930
                        if ip.Equal(s.lastDetectedIP) {
×
2931
                                continue
×
2932
                        }
2933

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

×
2936
                        // Next, we'll craft the new addresses that will be
×
2937
                        // included in the new node announcement and advertised
×
2938
                        // to the network. Each address will consist of the new
×
2939
                        // IP detected and one of the currently advertised
×
2940
                        // ports.
×
2941
                        var newAddrs []net.Addr
×
2942
                        for _, port := range forwardedPorts {
×
2943
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2944
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2945
                                if err != nil {
×
2946
                                        srvrLog.Debugf("Unable to resolve "+
×
2947
                                                "host %v: %v", addr, err)
×
2948
                                        continue
×
2949
                                }
2950

2951
                                newAddrs = append(newAddrs, addr)
×
2952
                        }
2953

2954
                        // Skip the update if we weren't able to resolve any of
2955
                        // the new addresses.
2956
                        if len(newAddrs) == 0 {
×
2957
                                srvrLog.Debug("Skipping node announcement " +
×
2958
                                        "update due to not being able to " +
×
2959
                                        "resolve any new addresses")
×
2960
                                continue
×
2961
                        }
2962

2963
                        // Now, we'll need to update the addresses in our node's
2964
                        // announcement in order to propagate the update
2965
                        // throughout the network. We'll only include addresses
2966
                        // that have a different IP from the previous one, as
2967
                        // the previous IP is no longer valid.
2968
                        currentNodeAnn := s.getNodeAnnouncement()
×
2969

×
2970
                        for _, addr := range currentNodeAnn.Addresses {
×
2971
                                host, _, err := net.SplitHostPort(addr.String())
×
2972
                                if err != nil {
×
2973
                                        srvrLog.Debugf("Unable to determine "+
×
2974
                                                "host from address %v: %v",
×
2975
                                                addr, err)
×
2976
                                        continue
×
2977
                                }
2978

2979
                                // We'll also make sure to include external IPs
2980
                                // set manually by the user.
2981
                                _, setByUser := ipsSetByUser[addr.String()]
×
2982
                                if setByUser || host != s.lastDetectedIP.String() {
×
2983
                                        newAddrs = append(newAddrs, addr)
×
2984
                                }
×
2985
                        }
2986

2987
                        // Then, we'll generate a new timestamped node
2988
                        // announcement with the updated addresses and broadcast
2989
                        // it to our peers.
2990
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2991
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2992
                        )
×
2993
                        if err != nil {
×
2994
                                srvrLog.Debugf("Unable to generate new node "+
×
2995
                                        "announcement: %v", err)
×
2996
                                continue
×
2997
                        }
2998

2999
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3000
                        if err != nil {
×
3001
                                srvrLog.Debugf("Unable to broadcast new node "+
×
3002
                                        "announcement to peers: %v", err)
×
3003
                                continue
×
3004
                        }
3005

3006
                        // Finally, update the last IP seen to the current one.
3007
                        s.lastDetectedIP = ip
×
3008
                case <-s.quit:
×
3009
                        break out
×
3010
                }
3011
        }
3012
}
3013

3014
// initNetworkBootstrappers initializes a set of network peer bootstrappers
3015
// based on the server, and currently active bootstrap mechanisms as defined
3016
// within the current configuration.
3017
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
3018
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
3019

×
3020
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
3021

×
3022
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3023
        // this can be used by default if we've already partially seeded the
×
3024
        // network.
×
3025
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3026
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3027
        if err != nil {
×
3028
                return nil, err
×
3029
        }
×
3030
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3031

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

×
3037
                // If we have a set of DNS seeds for this chain, then we'll add
×
3038
                // it as an additional bootstrapping source.
×
3039
                if ok {
×
3040
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3041
                                "seeds: %v", dnsSeeds)
×
3042

×
3043
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3044
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3045
                        )
×
3046
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3047
                }
×
3048
        }
3049

3050
        return bootStrappers, nil
×
3051
}
3052

3053
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3054
// needs to ignore, which is made of three parts,
3055
//   - the node itself needs to be skipped as it doesn't make sense to connect
3056
//     to itself.
3057
//   - the peers that already have connections with, as in s.peersByPub.
3058
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3059
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3060
        s.mu.RLock()
×
3061
        defer s.mu.RUnlock()
×
3062

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

×
3065
        // We should ignore ourselves from bootstrapping.
×
3066
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3067
        ignore[selfKey] = struct{}{}
×
3068

×
3069
        // Ignore all connected peers.
×
3070
        for _, peer := range s.peersByPub {
×
3071
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3072
                ignore[nID] = struct{}{}
×
3073
        }
×
3074

3075
        // Ignore all persistent peers as they have a dedicated reconnecting
3076
        // process.
3077
        for pubKeyStr := range s.persistentPeers {
×
3078
                var nID autopilot.NodeID
×
3079
                copy(nID[:], []byte(pubKeyStr))
×
3080
                ignore[nID] = struct{}{}
×
3081
        }
×
3082

3083
        return ignore
×
3084
}
3085

3086
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3087
// and maintain a target minimum number of outbound connections. With this
3088
// invariant, we ensure that our node is connected to a diverse set of peers
3089
// and that nodes newly joining the network receive an up to date network view
3090
// as soon as possible.
3091
func (s *server) peerBootstrapper(numTargetPeers uint32,
3092
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3093

×
3094
        defer s.wg.Done()
×
3095

×
3096
        // Before we continue, init the ignore peers map.
×
3097
        ignoreList := s.createBootstrapIgnorePeers()
×
3098

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

×
3103
        // Once done, we'll attempt to maintain our target minimum number of
×
3104
        // peers.
×
3105
        //
×
3106
        // We'll use a 15 second backoff, and double the time every time an
×
3107
        // epoch fails up to a ceiling.
×
3108
        backOff := time.Second * 15
×
3109

×
3110
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3111
        // see if we've reached our minimum number of peers.
×
3112
        sampleTicker := time.NewTicker(backOff)
×
3113
        defer sampleTicker.Stop()
×
3114

×
3115
        // We'll use the number of attempts and errors to determine if we need
×
3116
        // to increase the time between discovery epochs.
×
3117
        var epochErrors uint32 // To be used atomically.
×
3118
        var epochAttempts uint32
×
3119

×
3120
        for {
×
3121
                select {
×
3122
                // The ticker has just woken us up, so we'll need to check if
3123
                // we need to attempt to connect our to any more peers.
3124
                case <-sampleTicker.C:
×
3125
                        // Obtain the current number of peers, so we can gauge
×
3126
                        // if we need to sample more peers or not.
×
3127
                        s.mu.RLock()
×
3128
                        numActivePeers := uint32(len(s.peersByPub))
×
3129
                        s.mu.RUnlock()
×
3130

×
3131
                        // If we have enough peers, then we can loop back
×
3132
                        // around to the next round as we're done here.
×
3133
                        if numActivePeers >= numTargetPeers {
×
3134
                                continue
×
3135
                        }
3136

3137
                        // If all of our attempts failed during this last back
3138
                        // off period, then will increase our backoff to 5
3139
                        // minute ceiling to avoid an excessive number of
3140
                        // queries
3141
                        //
3142
                        // TODO(roasbeef): add reverse policy too?
3143

3144
                        if epochAttempts > 0 &&
×
3145
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3146

×
3147
                                sampleTicker.Stop()
×
3148

×
3149
                                backOff *= 2
×
3150
                                if backOff > bootstrapBackOffCeiling {
×
3151
                                        backOff = bootstrapBackOffCeiling
×
3152
                                }
×
3153

3154
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3155
                                        "%v", backOff)
×
3156
                                sampleTicker = time.NewTicker(backOff)
×
3157
                                continue
×
3158
                        }
3159

3160
                        atomic.StoreUint32(&epochErrors, 0)
×
3161
                        epochAttempts = 0
×
3162

×
3163
                        // Since we know need more peers, we'll compute the
×
3164
                        // exact number we need to reach our threshold.
×
3165
                        numNeeded := numTargetPeers - numActivePeers
×
3166

×
3167
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3168
                                "peers", numNeeded)
×
3169

×
3170
                        // With the number of peers we need calculated, we'll
×
3171
                        // query the network bootstrappers to sample a set of
×
3172
                        // random addrs for us.
×
3173
                        //
×
3174
                        // Before we continue, get a copy of the ignore peers
×
3175
                        // map.
×
3176
                        ignoreList = s.createBootstrapIgnorePeers()
×
3177

×
3178
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3179
                                ignoreList, numNeeded*2, bootstrappers...,
×
3180
                        )
×
3181
                        if err != nil {
×
3182
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3183
                                        "peers: %v", err)
×
3184
                                continue
×
3185
                        }
3186

3187
                        // Finally, we'll launch a new goroutine for each
3188
                        // prospective peer candidates.
3189
                        for _, addr := range peerAddrs {
×
3190
                                epochAttempts++
×
3191

×
3192
                                go func(a *lnwire.NetAddress) {
×
3193
                                        // TODO(roasbeef): can do AS, subnet,
×
3194
                                        // country diversity, etc
×
3195
                                        errChan := make(chan error, 1)
×
3196
                                        s.connectToPeer(
×
3197
                                                a, errChan,
×
3198
                                                s.cfg.ConnectionTimeout,
×
3199
                                        )
×
3200
                                        select {
×
3201
                                        case err := <-errChan:
×
3202
                                                if err == nil {
×
3203
                                                        return
×
3204
                                                }
×
3205

3206
                                                srvrLog.Errorf("Unable to "+
×
3207
                                                        "connect to %v: %v",
×
3208
                                                        a, err)
×
3209
                                                atomic.AddUint32(&epochErrors, 1)
×
3210
                                        case <-s.quit:
×
3211
                                        }
3212
                                }(addr)
3213
                        }
3214
                case <-s.quit:
×
3215
                        return
×
3216
                }
3217
        }
3218
}
3219

3220
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3221
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3222
// query back off each time we encounter a failure.
3223
const bootstrapBackOffCeiling = time.Minute * 5
3224

3225
// initialPeerBootstrap attempts to continuously connect to peers on startup
3226
// until the target number of peers has been reached. This ensures that nodes
3227
// receive an up to date network view as soon as possible.
3228
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3229
        numTargetPeers uint32,
3230
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3231

×
3232
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3233
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3234

×
3235
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3236
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3237
        var delaySignal <-chan time.Time
×
3238
        delayTime := time.Second * 2
×
3239

×
3240
        // As want to be more aggressive, we'll use a lower back off celling
×
3241
        // then the main peer bootstrap logic.
×
3242
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3243

×
3244
        for attempts := 0; ; attempts++ {
×
3245
                // Check if the server has been requested to shut down in order
×
3246
                // to prevent blocking.
×
3247
                if s.Stopped() {
×
3248
                        return
×
3249
                }
×
3250

3251
                // We can exit our aggressive initial peer bootstrapping stage
3252
                // if we've reached out target number of peers.
3253
                s.mu.RLock()
×
3254
                numActivePeers := uint32(len(s.peersByPub))
×
3255
                s.mu.RUnlock()
×
3256

×
3257
                if numActivePeers >= numTargetPeers {
×
3258
                        return
×
3259
                }
×
3260

3261
                if attempts > 0 {
×
3262
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3263
                                "bootstrap peers (attempt #%v)", delayTime,
×
3264
                                attempts)
×
3265

×
3266
                        // We've completed at least one iterating and haven't
×
3267
                        // finished, so we'll start to insert a delay period
×
3268
                        // between each attempt.
×
3269
                        delaySignal = time.After(delayTime)
×
3270
                        select {
×
3271
                        case <-delaySignal:
×
3272
                        case <-s.quit:
×
3273
                                return
×
3274
                        }
3275

3276
                        // After our delay, we'll double the time we wait up to
3277
                        // the max back off period.
3278
                        delayTime *= 2
×
3279
                        if delayTime > backOffCeiling {
×
3280
                                delayTime = backOffCeiling
×
3281
                        }
×
3282
                }
3283

3284
                // Otherwise, we'll request for the remaining number of peers
3285
                // in order to reach our target.
3286
                peersNeeded := numTargetPeers - numActivePeers
×
3287
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3288
                        ignore, peersNeeded, bootstrappers...,
×
3289
                )
×
3290
                if err != nil {
×
3291
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3292
                                "peers: %v", err)
×
3293
                        continue
×
3294
                }
3295

3296
                // Then, we'll attempt to establish a connection to the
3297
                // different peer addresses retrieved by our bootstrappers.
3298
                var wg sync.WaitGroup
×
3299
                for _, bootstrapAddr := range bootstrapAddrs {
×
3300
                        wg.Add(1)
×
3301
                        go func(addr *lnwire.NetAddress) {
×
3302
                                defer wg.Done()
×
3303

×
3304
                                errChan := make(chan error, 1)
×
3305
                                go s.connectToPeer(
×
3306
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3307
                                )
×
3308

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

3332
                wg.Wait()
×
3333
        }
3334
}
3335

3336
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3337
// order to listen for inbound connections over Tor.
3338
func (s *server) createNewHiddenService() error {
×
3339
        // Determine the different ports the server is listening on. The onion
×
3340
        // service's virtual port will map to these ports and one will be picked
×
3341
        // at random when the onion service is being accessed.
×
3342
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3343
        for _, listenAddr := range s.listenAddrs {
×
3344
                port := listenAddr.(*net.TCPAddr).Port
×
3345
                listenPorts = append(listenPorts, port)
×
3346
        }
×
3347

3348
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3349
        if err != nil {
×
3350
                return err
×
3351
        }
×
3352

3353
        // Once the port mapping has been set, we can go ahead and automatically
3354
        // create our onion service. The service's private key will be saved to
3355
        // disk in order to regain access to this service when restarting `lnd`.
3356
        onionCfg := tor.AddOnionConfig{
×
3357
                VirtualPort: defaultPeerPort,
×
3358
                TargetPorts: listenPorts,
×
3359
                Store: tor.NewOnionFile(
×
3360
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3361
                        encrypter,
×
3362
                ),
×
3363
        }
×
3364

×
3365
        switch {
×
3366
        case s.cfg.Tor.V2:
×
3367
                onionCfg.Type = tor.V2
×
3368
        case s.cfg.Tor.V3:
×
3369
                onionCfg.Type = tor.V3
×
3370
        }
3371

3372
        addr, err := s.torController.AddOnion(onionCfg)
×
3373
        if err != nil {
×
3374
                return err
×
3375
        }
×
3376

3377
        // Now that the onion service has been created, we'll add the onion
3378
        // address it can be reached at to our list of advertised addresses.
3379
        newNodeAnn, err := s.genNodeAnnouncement(
×
3380
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3381
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3382
                },
×
3383
        )
3384
        if err != nil {
×
3385
                return fmt.Errorf("unable to generate new node "+
×
3386
                        "announcement: %v", err)
×
3387
        }
×
3388

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

3407
        return nil
×
3408
}
3409

3410
// findChannel finds a channel given a public key and ChannelID. It is an
3411
// optimization that is quicker than seeking for a channel given only the
3412
// ChannelID.
3413
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3414
        *channeldb.OpenChannel, error) {
3✔
3415

3✔
3416
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3417
        if err != nil {
3✔
3418
                return nil, err
×
3419
        }
×
3420

3421
        for _, channel := range nodeChans {
6✔
3422
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3423
                        return channel, nil
3✔
3424
                }
3✔
3425
        }
3426

3427
        return nil, fmt.Errorf("unable to find channel")
3✔
3428
}
3429

3430
// getNodeAnnouncement fetches the current, fully signed node announcement.
3431
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3432
        s.mu.Lock()
3✔
3433
        defer s.mu.Unlock()
3✔
3434

3✔
3435
        return *s.currentNodeAnn
3✔
3436
}
3✔
3437

3438
// genNodeAnnouncement generates and returns the current fully signed node
3439
// announcement. The time stamp of the announcement will be updated in order
3440
// to ensure it propagates through the network.
3441
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3442
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3443

3✔
3444
        s.mu.Lock()
3✔
3445
        defer s.mu.Unlock()
3✔
3446

3✔
3447
        // First, try to update our feature manager with the updated set of
3✔
3448
        // features.
3✔
3449
        if features != nil {
6✔
3450
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3451
                        feature.SetNodeAnn: features,
3✔
3452
                }
3✔
3453
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3454
                if err != nil {
6✔
3455
                        return lnwire.NodeAnnouncement{}, err
3✔
3456
                }
3✔
3457

3458
                // If we could successfully update our feature manager, add
3459
                // an update modifier to include these new features to our
3460
                // set.
3461
                modifiers = append(
3✔
3462
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3463
                )
3✔
3464
        }
3465

3466
        // Always update the timestamp when refreshing to ensure the update
3467
        // propagates.
3468
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3469

3✔
3470
        // Apply the requested changes to the node announcement.
3✔
3471
        for _, modifier := range modifiers {
6✔
3472
                modifier(s.currentNodeAnn)
3✔
3473
        }
3✔
3474

3475
        // Sign a new update after applying all of the passed modifiers.
3476
        err := netann.SignNodeAnnouncement(
3✔
3477
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3478
        )
3✔
3479
        if err != nil {
3✔
3480
                return lnwire.NodeAnnouncement{}, err
×
3481
        }
×
3482

3483
        return *s.currentNodeAnn, nil
3✔
3484
}
3485

3486
// updateAndBroadcastSelfNode generates a new node announcement
3487
// applying the giving modifiers and updating the time stamp
3488
// to ensure it propagates through the network. Then it broadcasts
3489
// it to the network.
3490
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3491
        modifiers ...netann.NodeAnnModifier) error {
3✔
3492

3✔
3493
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3494
        if err != nil {
6✔
3495
                return fmt.Errorf("unable to generate new node "+
3✔
3496
                        "announcement: %v", err)
3✔
3497
        }
3✔
3498

3499
        // Update the on-disk version of our announcement.
3500
        // Load and modify self node istead of creating anew instance so we
3501
        // don't risk overwriting any existing values.
3502
        selfNode, err := s.graphDB.SourceNode()
3✔
3503
        if err != nil {
3✔
3504
                return fmt.Errorf("unable to get current source node: %w", err)
×
3505
        }
×
3506

3507
        selfNode.HaveNodeAnnouncement = true
3✔
3508
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3509
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3510
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3511
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3512
        selfNode.Color = newNodeAnn.RGBColor
3✔
3513
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3514

3✔
3515
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
3516

3✔
3517
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3✔
3518
                return fmt.Errorf("can't set self node: %w", err)
×
3519
        }
×
3520

3521
        // Finally, propagate it to the nodes in the network.
3522
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3523
        if err != nil {
3✔
3524
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3525
                        "announcement to peers: %v", err)
×
3526
                return err
×
3527
        }
×
3528

3529
        return nil
3✔
3530
}
3531

3532
type nodeAddresses struct {
3533
        pubKey    *btcec.PublicKey
3534
        addresses []net.Addr
3535
}
3536

3537
// establishPersistentConnections attempts to establish persistent connections
3538
// to all our direct channel collaborators. In order to promote liveness of our
3539
// active channels, we instruct the connection manager to attempt to establish
3540
// and maintain persistent connections to all our direct channel counterparties.
3541
func (s *server) establishPersistentConnections() error {
3✔
3542
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3543
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3544
        // since other PubKey forms can't be compared.
3✔
3545
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3546

3✔
3547
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3548
        // attempt to connect to based on our set of previous connections. Set
3✔
3549
        // the reconnection port to the default peer port.
3✔
3550
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3551
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3552
                return err
×
3553
        }
×
3554
        for _, node := range linkNodes {
6✔
3555
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3556
                nodeAddrs := &nodeAddresses{
3✔
3557
                        pubKey:    node.IdentityPub,
3✔
3558
                        addresses: node.Addresses,
3✔
3559
                }
3✔
3560
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3561
        }
3✔
3562

3563
        // After checking our previous connections for addresses to connect to,
3564
        // iterate through the nodes in our channel graph to find addresses
3565
        // that have been added via NodeAnnouncement messages.
3566
        sourceNode, err := s.graphDB.SourceNode()
3✔
3567
        if err != nil {
3✔
3568
                return err
×
3569
        }
×
3570

3571
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3572
        // each of the nodes.
3573
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3574
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3575
                tx kvdb.RTx,
3✔
3576
                chanInfo *models.ChannelEdgeInfo,
3✔
3577
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3578

3✔
3579
                // If the remote party has announced the channel to us, but we
3✔
3580
                // haven't yet, then we won't have a policy. However, we don't
3✔
3581
                // need this to connect to the peer, so we'll log it and move on.
3✔
3582
                if policy == nil {
3✔
3583
                        srvrLog.Warnf("No channel policy found for "+
×
3584
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3585
                }
×
3586

3587
                // We'll now fetch the peer opposite from us within this
3588
                // channel so we can queue up a direct connection to them.
3589
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3590
                        tx, chanInfo, selfPub,
3✔
3591
                )
3✔
3592
                if err != nil {
3✔
3593
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3594
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3595
                                err)
×
3596
                }
×
3597

3598
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3599

3✔
3600
                // Add all unique addresses from channel
3✔
3601
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3602
                // connect to for this peer.
3✔
3603
                addrSet := make(map[string]net.Addr)
3✔
3604
                for _, addr := range channelPeer.Addresses {
6✔
3605
                        switch addr.(type) {
3✔
3606
                        case *net.TCPAddr:
3✔
3607
                                addrSet[addr.String()] = addr
3✔
3608

3609
                        // We'll only attempt to connect to Tor addresses if Tor
3610
                        // outbound support is enabled.
3611
                        case *tor.OnionAddr:
×
3612
                                if s.cfg.Tor.Active {
×
3613
                                        addrSet[addr.String()] = addr
×
3614
                                }
×
3615
                        }
3616
                }
3617

3618
                // If this peer is also recorded as a link node, we'll add any
3619
                // additional addresses that have not already been selected.
3620
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3621
                if ok {
6✔
3622
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3623
                                switch lnAddress.(type) {
3✔
3624
                                case *net.TCPAddr:
3✔
3625
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3626

3627
                                // We'll only attempt to connect to Tor
3628
                                // addresses if Tor outbound support is enabled.
3629
                                case *tor.OnionAddr:
×
3630
                                        if s.cfg.Tor.Active {
×
3631
                                                addrSet[lnAddress.String()] = lnAddress
×
3632
                                        }
×
3633
                                }
3634
                        }
3635
                }
3636

3637
                // Construct a slice of the deduped addresses.
3638
                var addrs []net.Addr
3✔
3639
                for _, addr := range addrSet {
6✔
3640
                        addrs = append(addrs, addr)
3✔
3641
                }
3✔
3642

3643
                n := &nodeAddresses{
3✔
3644
                        addresses: addrs,
3✔
3645
                }
3✔
3646
                n.pubKey, err = channelPeer.PubKey()
3✔
3647
                if err != nil {
3✔
3648
                        return err
×
3649
                }
×
3650

3651
                nodeAddrsMap[pubStr] = n
3✔
3652
                return nil
3✔
3653
        })
3654
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3655
                return err
×
3656
        }
×
3657

3658
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3659
                len(nodeAddrsMap))
3✔
3660

3✔
3661
        // Acquire and hold server lock until all persistent connection requests
3✔
3662
        // have been recorded and sent to the connection manager.
3✔
3663
        s.mu.Lock()
3✔
3664
        defer s.mu.Unlock()
3✔
3665

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

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

3✔
3689
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3690
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3691
                }
3✔
3692

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

3✔
3703
                        go s.connectToPersistentPeer(pubStr)
3✔
3704
                } else {
3✔
3705
                        go s.delayInitialReconnect(pubStr)
×
3706
                }
×
3707

3708
                numOutboundConns++
3✔
3709
        }
3710

3711
        return nil
3✔
3712
}
3713

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

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

3✔
3733
        s.mu.Lock()
3✔
3734
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3735
                delete(s.persistentPeers, pubKeyStr)
3✔
3736
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3737
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3738
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3739
                s.mu.Unlock()
3✔
3740

3✔
3741
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3742
                        "peer has no open channels", compressedPubKey)
3✔
3743

3✔
3744
                return
3✔
3745
        }
3✔
3746
        s.mu.Unlock()
3✔
3747
}
3748

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

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

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

3789
                peers = append(peers, sPeer)
3✔
3790
        }
3791
        s.mu.RUnlock()
3✔
3792

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

3✔
3800
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3801
                wg.Add(1)
3✔
3802
                s.wg.Add(1)
3✔
3803
                go func(p lnpeer.Peer) {
6✔
3804
                        defer s.wg.Done()
3✔
3805
                        defer wg.Done()
3✔
3806

3✔
3807
                        p.SendMessageLazy(false, msgs...)
3✔
3808
                }(sPeer)
3✔
3809
        }
3810

3811
        // Wait for all messages to have been dispatched before returning to
3812
        // caller.
3813
        wg.Wait()
3✔
3814

3✔
3815
        return nil
3✔
3816
}
3817

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

3✔
3825
        s.mu.Lock()
3✔
3826

3✔
3827
        // Compute the target peer's identifier.
3✔
3828
        pubStr := string(peerKey[:])
3✔
3829

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

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

3852
                // Connected, can return early.
3853
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3854

3✔
3855
                select {
3✔
3856
                case peerChan <- peer:
3✔
3857
                case <-s.quit:
×
3858
                }
3859

3860
                return
3✔
3861
        }
3862

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

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

3✔
3878
        c := make(chan struct{})
3✔
3879

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

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

3✔
3896
        return c
3✔
3897
}
3898

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

3✔
3908
        pubStr := string(peerKey.SerializeCompressed())
3✔
3909

3✔
3910
        return s.findPeerByPubStr(pubStr)
3✔
3911
}
3✔
3912

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

3✔
3922
        return s.findPeerByPubStr(pubStr)
3✔
3923
}
3✔
3924

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

3933
        return peer, nil
3✔
3934
}
3935

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

3✔
3942
        // Now, determine the appropriate backoff to use for the retry.
3✔
3943
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3944
        if !ok {
6✔
3945
                // If an existing backoff was unknown, use the default.
3✔
3946
                return s.cfg.MinBackoff
3✔
3947
        }
3✔
3948

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

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

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

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

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

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

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

4008
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4009
        pubSer := nodePub.SerializeCompressed()
3✔
4010
        pubStr := string(pubSer)
3✔
4011

3✔
4012
        var pubBytes [33]byte
3✔
4013
        copy(pubBytes[:], pubSer)
3✔
4014

3✔
4015
        s.mu.Lock()
3✔
4016
        defer s.mu.Unlock()
3✔
4017

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

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

×
4029
                conn.Close()
×
4030

×
4031
                return
×
4032
        }
×
4033

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

3✔
4041
                conn.Close()
3✔
4042
                return
3✔
4043
        }
3✔
4044

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

4055
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3✔
4056

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

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

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

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

×
4092
                s.cancelConnReqs(pubStr, nil)
×
4093

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

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

4115
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4116
        pubSer := nodePub.SerializeCompressed()
3✔
4117
        pubStr := string(pubSer)
3✔
4118

3✔
4119
        var pubBytes [33]byte
3✔
4120
        copy(pubBytes[:], pubSer)
3✔
4121

3✔
4122
        s.mu.Lock()
3✔
4123
        defer s.mu.Unlock()
3✔
4124

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

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

×
4135
                if connReq != nil {
×
4136
                        s.connMgr.Remove(connReq.ID())
×
4137
                }
×
4138

4139
                conn.Close()
×
4140

×
4141
                return
×
4142
        }
4143

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

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

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

×
4170
                if connReq != nil {
×
4171
                        s.connMgr.Remove(connReq.ID())
×
4172
                }
×
4173

4174
                conn.Close()
×
4175
                return
×
4176
        }
4177

4178
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4179
                conn.RemoteAddr())
3✔
4180

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

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

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

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

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

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

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

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

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

4269
        for _, connReq := range connReqs {
6✔
4270
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4271

3✔
4272
                // Atomically capture the current request identifier.
3✔
4273
                connID := connReq.ID()
3✔
4274

3✔
4275
                // Skip any zero IDs, this indicates the request has not
3✔
4276
                // yet been schedule.
3✔
4277
                if connID == UnassignedConnID {
3✔
4278
                        continue
×
4279
                }
4280

4281
                // Skip a particular connection ID if instructed.
4282
                if skip != nil && connID == *skip {
6✔
4283
                        continue
3✔
4284
                }
4285

4286
                s.connMgr.Remove(connID)
3✔
4287
        }
4288

4289
        delete(s.persistentConnReqs, pubStr)
3✔
4290
}
4291

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

3✔
4298
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4299
                Peer: peer,
3✔
4300
                Msg:  msg,
3✔
4301
        })
3✔
4302
}
3✔
4303

4304
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4305
// messages.
4306
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4307
        return s.customMessageServer.Subscribe()
3✔
4308
}
3✔
4309

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

3✔
4315
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4316
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4317
                return err
3✔
4318
        }
3✔
4319

4320
        // Notify subscribers about this open channel event.
4321
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4322

3✔
4323
        return nil
3✔
4324
}
4325

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

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

4337
        // Notify subscribers about this event.
4338
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4339

3✔
4340
        return nil
3✔
4341
}
4342

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

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

4358
        // Notify subscribers about this event.
4359
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4360

3✔
4361
        return nil
3✔
4362
}
4363

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

3✔
4371
        brontideConn := conn.(*brontide.Conn)
3✔
4372
        addr := conn.RemoteAddr()
3✔
4373
        pubKey := brontideConn.RemotePub()
3✔
4374

3✔
4375
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4376
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4377

3✔
4378
        peerAddr := &lnwire.NetAddress{
3✔
4379
                IdentityKey: pubKey,
3✔
4380
                Address:     addr,
3✔
4381
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4382
        }
3✔
4383

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

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

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

4413
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4414
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4415

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

3✔
4459
                        return s.genNodeAnnouncement(nil)
3✔
4460
                },
3✔
4461

4462
                PongBuf: s.pongBuf,
4463

4464
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4465

4466
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4467

4468
                FundingManager: s.fundingMgr,
4469

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

4499
                        return clock.NewDefaultClock().Now().Before(
3✔
4500
                                EndorsementExperimentEnd,
3✔
4501
                        )
3✔
4502
                },
4503
        }
4504

4505
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4506
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4507

3✔
4508
        p := peer.NewBrontide(pCfg)
3✔
4509

3✔
4510
        // Update the access manager with the access permission for this peer.
3✔
4511
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4512

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

3✔
4516
        s.addPeer(p)
3✔
4517

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

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

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

4537
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4538

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

×
4545
                return
×
4546
        }
×
4547

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

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

3✔
4557
        s.peersByPub[pubStr] = p
3✔
4558

3✔
4559
        if p.Inbound() {
6✔
4560
                s.inboundPeers[pubStr] = p
3✔
4561
        } else {
6✔
4562
                s.outboundPeers[pubStr] = p
3✔
4563
        }
3✔
4564

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

3✔
4570
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4571
}
4572

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

3✔
4585
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4586

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

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

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

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

3✔
4613
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4614
                return
3✔
4615
        }
3✔
4616

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

3✔
4621
        s.mu.Lock()
3✔
4622
        defer s.mu.Unlock()
3✔
4623

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

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

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

3✔
4654
        p.WaitForDisconnect(ready)
3✔
4655

3✔
4656
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4657

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

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

3✔
4671
        pubKey := p.IdentityKey()
3✔
4672

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

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

4687
        for _, link := range links {
6✔
4688
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4689
        }
3✔
4690

4691
        s.mu.Lock()
3✔
4692
        defer s.mu.Unlock()
3✔
4693

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

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

×
4708
                pubKey := p.PubKey()
×
4709
                pubStr := string(pubKey[:])
×
4710

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

4724
        // First, cleanup any remaining state the server has regarding the peer
4725
        // in question.
4726
        s.removePeer(p)
3✔
4727

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

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

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

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

4754
                // Fall back to the existing peer address if
4755
                // we're not accepting connections over Tor.
4756
                if s.torController == nil {
6✔
4757
                        break
3✔
4758
                }
4759

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

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

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

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

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

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

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

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

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

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

3✔
4834
                s.connectToPersistentPeer(pubStr)
3✔
4835
        }()
4836
}
4837

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

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

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

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

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

4888
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4889

3✔
4890
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4891
        if !ok {
6✔
4892
                cancelChan = make(chan struct{})
3✔
4893
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4894
        }
3✔
4895

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

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

3✔
4913
                        s.mu.Lock()
3✔
4914
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4915
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4916
                        )
3✔
4917
                        s.mu.Unlock()
3✔
4918

3✔
4919
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4920
                                "channel peer %v", addr)
3✔
4921

3✔
4922
                        go s.connMgr.Connect(connReq)
3✔
4923

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

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

4942
        srvrLog.Debugf("removing peer %v", p)
3✔
4943

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

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

4953
        // Ignore deleting peers if we're shutting down.
4954
        if s.Stopped() {
3✔
4955
                return
×
4956
        }
×
4957

4958
        pKey := p.PubKey()
3✔
4959
        pubSer := pKey[:]
3✔
4960
        pubStr := string(pubSer)
3✔
4961

3✔
4962
        delete(s.peersByPub, pubStr)
3✔
4963

3✔
4964
        if p.Inbound() {
6✔
4965
                delete(s.inboundPeers, pubStr)
3✔
4966
        } else {
6✔
4967
                delete(s.outboundPeers, pubStr)
3✔
4968
        }
3✔
4969

4970
        // Remove the peer's access permission from the access manager.
4971
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4972

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

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

3✔
4984
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4985
}
4986

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

3✔
4995
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4996

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

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

5010
        // Peer was not found, continue to pursue connection with peer.
5011

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

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

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

3✔
5043
                go s.connMgr.Connect(connReq)
3✔
5044

3✔
5045
                return nil
3✔
5046
        }
5047
        s.mu.Unlock()
3✔
5048

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

3✔
5056
        select {
3✔
5057
        case err := <-errChan:
3✔
5058
                return err
3✔
5059
        case <-s.quit:
×
5060
                return ErrServerShuttingDown
×
5061
        }
5062
}
5063

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

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

5082
        close(errChan)
3✔
5083

3✔
5084
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5085
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5086

3✔
5087
        s.OutboundPeerConnected(nil, conn)
3✔
5088
}
5089

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

3✔
5098
        s.mu.Lock()
3✔
5099
        defer s.mu.Unlock()
3✔
5100

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

5109
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5110

3✔
5111
        s.cancelConnReqs(pubStr, nil)
3✔
5112

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

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

3✔
5123
        return nil
3✔
5124
}
5125

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

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

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

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

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

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

×
5173
                return req.Updates, req.Err
×
5174
        }
×
5175

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

3✔
5182
        return req.Updates, req.Err
3✔
5183
}
5184

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

3✔
5192
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5193
        for _, peer := range s.peersByPub {
6✔
5194
                peers = append(peers, peer)
3✔
5195
        }
3✔
5196

5197
        return peers
3✔
5198
}
5199

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

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

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

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

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

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

5239
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5240
        if err != nil {
6✔
5241
                return nil, err
3✔
5242
        }
3✔
5243

5244
        if len(node.Addresses) == 0 {
6✔
5245
                return nil, errNoAdvertisedAddr
3✔
5246
        }
3✔
5247

5248
        return node.Addresses, nil
3✔
5249
}
5250

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

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

5263
                return netann.ExtractChannelUpdate(
3✔
5264
                        ourPubKey[:], info, edge1, edge2,
3✔
5265
                )
3✔
5266
        }
5267
}
5268

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

3✔
5275
        var (
3✔
5276
                peerAlias    *lnwire.ShortChannelID
3✔
5277
                defaultAlias lnwire.ShortChannelID
3✔
5278
        )
3✔
5279

3✔
5280
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5281

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

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

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

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

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

5321
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5322
        if err != nil {
6✔
5323
                return err
3✔
5324
        }
3✔
5325

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

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

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

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

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

5360
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5361
                        DeliveryAddress: addr,
3✔
5362
                        InternalKey:     internalKeyDesc,
3✔
5363
                })
3✔
5364
        }
5365
}
5366

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

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

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

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

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

5414
        for _, c := range pendings {
6✔
5415
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5416
                        continue
3✔
5417
                }
5418

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

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

5427
        return closedSCIDs
3✔
5428
}
5429

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

3✔
5436
        // We should get a notification with the current best block immediately
3✔
5437
        // by passing a nil block.
3✔
5438
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5439
        if err != nil {
3✔
5440
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5441
        }
×
5442
        defer blockEpochs.Cancel()
3✔
5443

3✔
5444
        // We registered for the block epochs with a nil request. The notifier
3✔
5445
        // should send us the current best block immediately. So we need to
3✔
5446
        // wait for it here because we need to know the current best height.
3✔
5447
        select {
3✔
5448
        case bestBlock := <-blockEpochs.Epochs:
3✔
5449
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5450
                        bestBlock.Hash, bestBlock.Height)
3✔
5451

3✔
5452
                // Update the current blockbeat.
3✔
5453
                beat = chainio.NewBeat(*bestBlock)
3✔
5454

5455
        case <-s.quit:
×
5456
                srvrLog.Debug("LND shutting down")
×
5457
        }
5458

5459
        return beat, nil
3✔
5460
}
5461

5462
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5463
// point has an active RBF chan closer.
5464
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5465
        chanPoint wire.OutPoint) bool {
3✔
5466

3✔
5467
        pubBytes := peerPub.SerializeCompressed()
3✔
5468

3✔
5469
        s.mu.RLock()
3✔
5470
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5471
        s.mu.RUnlock()
3✔
5472
        if !ok {
3✔
5473
                return false
×
5474
        }
×
5475

5476
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5477
}
5478

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

3✔
5487
        // First, we'll attempt to look up the channel based on it's
3✔
5488
        // ChannelPoint.
3✔
5489
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5490
        if err != nil {
3✔
5491
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5492
        }
×
5493

5494
        // From the channel, we can now get the pubkey of the peer, then use
5495
        // that to eventually get the chan closer.
5496
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5497

3✔
5498
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5499
        s.mu.RLock()
3✔
5500
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5501
        s.mu.RUnlock()
3✔
5502
        if !ok {
3✔
5503
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5504
                        "not online", chanPoint)
×
5505
        }
×
5506

5507
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5508
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5509
        )
3✔
5510
        if err != nil {
3✔
5511
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5512
                        "%w", err)
×
5513
        }
×
5514

5515
        return closeUpdates, nil
3✔
5516
}
5517

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

3✔
5526
        // If the channel is present in the switch, then the request should flow
3✔
5527
        // through the switch instead.
3✔
5528
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5529
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5530
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5531
                        "invalid request", chanPoint)
×
5532
        }
×
5533

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

5544
        return updates, nil
3✔
5545
}
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