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

lightningnetwork / lnd / 12395709513

18 Dec 2024 03:04PM UTC coverage: 57.495% (-1.1%) from 58.595%
12395709513

Pull #8777

github

ziggie1984
funding: refactor gossip msg code

We almost never need to create all messages at the same time
(ChanUpdate,ChanAnnouncement,Proof) so we split it up into own
functions.
Pull Request #8777: multi: make reassignment of alias channel edge atomic

196 of 330 new or added lines in 7 files covered. (59.39%)

19293 existing lines in 251 files now uncovered.

102055 of 177501 relevant lines covered (57.5%)

24852.05 hits per line

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

0.29
/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/chainreg"
32
        "github.com/lightningnetwork/lnd/chanacceptor"
33
        "github.com/lightningnetwork/lnd/chanbackup"
34
        "github.com/lightningnetwork/lnd/chanfitness"
35
        "github.com/lightningnetwork/lnd/channeldb"
36
        "github.com/lightningnetwork/lnd/channelnotifier"
37
        "github.com/lightningnetwork/lnd/clock"
38
        "github.com/lightningnetwork/lnd/cluster"
39
        "github.com/lightningnetwork/lnd/contractcourt"
40
        "github.com/lightningnetwork/lnd/discovery"
41
        "github.com/lightningnetwork/lnd/feature"
42
        "github.com/lightningnetwork/lnd/fn/v2"
43
        "github.com/lightningnetwork/lnd/funding"
44
        "github.com/lightningnetwork/lnd/graph"
45
        graphdb "github.com/lightningnetwork/lnd/graph/db"
46
        "github.com/lightningnetwork/lnd/graph/db/models"
47
        "github.com/lightningnetwork/lnd/graph/graphsession"
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

145
// errPeerAlreadyConnected is an error returned by the server when we're
146
// commanded to connect to a peer, but they're already connected.
147
type errPeerAlreadyConnected struct {
148
        peer *peer.Brontide
149
}
150

151
// Error returns the human readable version of this error type.
152
//
153
// NOTE: Part of the error interface.
UNCOV
154
func (e *errPeerAlreadyConnected) Error() string {
×
UNCOV
155
        return fmt.Sprintf("already connected to peer: %v", e.peer)
×
UNCOV
156
}
×
157

158
// server is the main server of the Lightning Network Daemon. The server houses
159
// global state pertaining to the wallet, database, and the rpcserver.
160
// Additionally, the server is also used as a central messaging bus to interact
161
// with any of its companion objects.
162
type server struct {
163
        active   int32 // atomic
164
        stopping int32 // atomic
165

166
        start sync.Once
167
        stop  sync.Once
168

169
        cfg *Config
170

171
        implCfg *ImplementationCfg
172

173
        // identityECDH is an ECDH capable wrapper for the private key used
174
        // to authenticate any incoming connections.
175
        identityECDH keychain.SingleKeyECDH
176

177
        // identityKeyLoc is the key locator for the above wrapped identity key.
178
        identityKeyLoc keychain.KeyLocator
179

180
        // nodeSigner is an implementation of the MessageSigner implementation
181
        // that's backed by the identity private key of the running lnd node.
182
        nodeSigner *netann.NodeSigner
183

184
        chanStatusMgr *netann.ChanStatusManager
185

186
        // listenAddrs is the list of addresses the server is currently
187
        // listening on.
188
        listenAddrs []net.Addr
189

190
        // torController is a client that will communicate with a locally
191
        // running Tor server. This client will handle initiating and
192
        // authenticating the connection to the Tor server, automatically
193
        // creating and setting up onion services, etc.
194
        torController *tor.Controller
195

196
        // natTraversal is the specific NAT traversal technique used to
197
        // automatically set up port forwarding rules in order to advertise to
198
        // the network that the node is accepting inbound connections.
199
        natTraversal nat.Traversal
200

201
        // lastDetectedIP is the last IP detected by the NAT traversal technique
202
        // above. This IP will be watched periodically in a goroutine in order
203
        // to handle dynamic IP changes.
204
        lastDetectedIP net.IP
205

206
        mu sync.RWMutex
207

208
        // peersByPub is a map of the active peers.
209
        //
210
        // NOTE: The key used here is the raw bytes of the peer's public key to
211
        // string conversion, which means it cannot be printed using `%s` as it
212
        // will just print the binary.
213
        //
214
        // TODO(yy): Use the hex string instead.
215
        peersByPub map[string]*peer.Brontide
216

217
        inboundPeers  map[string]*peer.Brontide
218
        outboundPeers map[string]*peer.Brontide
219

220
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
221
        peerDisconnectedListeners map[string][]chan<- struct{}
222

223
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
224
        // will continue to send messages even if there are no active channels
225
        // and the value below is false. Once it's pruned, all its connections
226
        // will be closed, thus the Brontide.Start will return an error.
227
        persistentPeers        map[string]bool
228
        persistentPeersBackoff map[string]time.Duration
229
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
230
        persistentConnReqs     map[string][]*connmgr.ConnReq
231
        persistentRetryCancels map[string]chan struct{}
232

233
        // peerErrors keeps a set of peer error buffers for peers that have
234
        // disconnected from us. This allows us to track historic peer errors
235
        // over connections. The string of the peer's compressed pubkey is used
236
        // as a key for this map.
237
        peerErrors map[string]*queue.CircularBuffer
238

239
        // ignorePeerTermination tracks peers for which the server has initiated
240
        // a disconnect. Adding a peer to this map causes the peer termination
241
        // watcher to short circuit in the event that peers are purposefully
242
        // disconnected.
243
        ignorePeerTermination map[*peer.Brontide]struct{}
244

245
        // scheduledPeerConnection maps a pubkey string to a callback that
246
        // should be executed in the peerTerminationWatcher the prior peer with
247
        // the same pubkey exits.  This allows the server to wait until the
248
        // prior peer has cleaned up successfully, before adding the new peer
249
        // intended to replace it.
250
        scheduledPeerConnection map[string]func()
251

252
        // pongBuf is a shared pong reply buffer we'll use across all active
253
        // peer goroutines. We know the max size of a pong message
254
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
255
        // avoid allocations each time we need to send a pong message.
256
        pongBuf []byte
257

258
        cc *chainreg.ChainControl
259

260
        fundingMgr *funding.Manager
261

262
        graphDB *graphdb.ChannelGraph
263

264
        chanStateDB *channeldb.ChannelStateDB
265

266
        addrSource channeldb.AddrSource
267

268
        // miscDB is the DB that contains all "other" databases within the main
269
        // channel DB that haven't been separated out yet.
270
        miscDB *channeldb.DB
271

272
        invoicesDB invoices.InvoiceDB
273

274
        aliasMgr *aliasmgr.Manager
275

276
        htlcSwitch *htlcswitch.Switch
277

278
        interceptableSwitch *htlcswitch.InterceptableSwitch
279

280
        invoices *invoices.InvoiceRegistry
281

282
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
283

284
        channelNotifier *channelnotifier.ChannelNotifier
285

286
        peerNotifier *peernotifier.PeerNotifier
287

288
        htlcNotifier *htlcswitch.HtlcNotifier
289

290
        witnessBeacon contractcourt.WitnessBeacon
291

292
        breachArbitrator *contractcourt.BreachArbitrator
293

294
        missionController *routing.MissionController
295
        defaultMC         *routing.MissionControl
296

297
        graphBuilder *graph.Builder
298

299
        chanRouter *routing.ChannelRouter
300

301
        controlTower routing.ControlTower
302

303
        authGossiper *discovery.AuthenticatedGossiper
304

305
        localChanMgr *localchans.Manager
306

307
        utxoNursery *contractcourt.UtxoNursery
308

309
        sweeper *sweep.UtxoSweeper
310

311
        chainArb *contractcourt.ChainArbitrator
312

313
        sphinx *hop.OnionProcessor
314

315
        towerClientMgr *wtclient.Manager
316

317
        connMgr *connmgr.ConnManager
318

319
        sigPool *lnwallet.SigPool
320

321
        writePool *pool.Write
322

323
        readPool *pool.Read
324

325
        tlsManager *TLSManager
326

327
        // featureMgr dispatches feature vectors for various contexts within the
328
        // daemon.
329
        featureMgr *feature.Manager
330

331
        // currentNodeAnn is the node announcement that has been broadcast to
332
        // the network upon startup, if the attributes of the node (us) has
333
        // changed since last start.
334
        currentNodeAnn *lnwire.NodeAnnouncement
335

336
        // chansToRestore is the set of channels that upon starting, the server
337
        // should attempt to restore/recover.
338
        chansToRestore walletunlocker.ChannelsToRecover
339

340
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
341
        // backups are consistent at all times. It interacts with the
342
        // channelNotifier to be notified of newly opened and closed channels.
343
        chanSubSwapper *chanbackup.SubSwapper
344

345
        // chanEventStore tracks the behaviour of channels and their remote peers to
346
        // provide insights into their health and performance.
347
        chanEventStore *chanfitness.ChannelEventStore
348

349
        hostAnn *netann.HostAnnouncer
350

351
        // livenessMonitor monitors that lnd has access to critical resources.
352
        livenessMonitor *healthcheck.Monitor
353

354
        customMessageServer *subscribe.Server
355

356
        // txPublisher is a publisher with fee-bumping capability.
357
        txPublisher *sweep.TxPublisher
358

359
        quit chan struct{}
360

361
        wg sync.WaitGroup
362
}
363

364
// updatePersistentPeerAddrs subscribes to topology changes and stores
365
// advertised addresses for any NodeAnnouncements from our persisted peers.
UNCOV
366
func (s *server) updatePersistentPeerAddrs() error {
×
UNCOV
367
        graphSub, err := s.graphBuilder.SubscribeTopology()
×
UNCOV
368
        if err != nil {
×
369
                return err
×
370
        }
×
371

UNCOV
372
        s.wg.Add(1)
×
UNCOV
373
        go func() {
×
UNCOV
374
                defer func() {
×
UNCOV
375
                        graphSub.Cancel()
×
UNCOV
376
                        s.wg.Done()
×
UNCOV
377
                }()
×
378

UNCOV
379
                for {
×
UNCOV
380
                        select {
×
UNCOV
381
                        case <-s.quit:
×
UNCOV
382
                                return
×
383

UNCOV
384
                        case topChange, ok := <-graphSub.TopologyChanges:
×
UNCOV
385
                                // If the router is shutting down, then we will
×
UNCOV
386
                                // as well.
×
UNCOV
387
                                if !ok {
×
388
                                        return
×
389
                                }
×
390

UNCOV
391
                                for _, update := range topChange.NodeUpdates {
×
UNCOV
392
                                        pubKeyStr := string(
×
UNCOV
393
                                                update.IdentityKey.
×
UNCOV
394
                                                        SerializeCompressed(),
×
UNCOV
395
                                        )
×
UNCOV
396

×
UNCOV
397
                                        // We only care about updates from
×
UNCOV
398
                                        // our persistentPeers.
×
UNCOV
399
                                        s.mu.RLock()
×
UNCOV
400
                                        _, ok := s.persistentPeers[pubKeyStr]
×
UNCOV
401
                                        s.mu.RUnlock()
×
UNCOV
402
                                        if !ok {
×
UNCOV
403
                                                continue
×
404
                                        }
405

UNCOV
406
                                        addrs := make([]*lnwire.NetAddress, 0,
×
UNCOV
407
                                                len(update.Addresses))
×
UNCOV
408

×
UNCOV
409
                                        for _, addr := range update.Addresses {
×
UNCOV
410
                                                addrs = append(addrs,
×
UNCOV
411
                                                        &lnwire.NetAddress{
×
UNCOV
412
                                                                IdentityKey: update.IdentityKey,
×
UNCOV
413
                                                                Address:     addr,
×
UNCOV
414
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
415
                                                        },
×
UNCOV
416
                                                )
×
UNCOV
417
                                        }
×
418

UNCOV
419
                                        s.mu.Lock()
×
UNCOV
420

×
UNCOV
421
                                        // Update the stored addresses for this
×
UNCOV
422
                                        // to peer to reflect the new set.
×
UNCOV
423
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
UNCOV
424

×
UNCOV
425
                                        // If there are no outstanding
×
UNCOV
426
                                        // connection requests for this peer
×
UNCOV
427
                                        // then our work is done since we are
×
UNCOV
428
                                        // not currently trying to connect to
×
UNCOV
429
                                        // them.
×
UNCOV
430
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
×
UNCOV
431
                                                s.mu.Unlock()
×
UNCOV
432
                                                continue
×
433
                                        }
434

UNCOV
435
                                        s.mu.Unlock()
×
UNCOV
436

×
UNCOV
437
                                        s.connectToPersistentPeer(pubKeyStr)
×
438
                                }
439
                        }
440
                }
441
        }()
442

UNCOV
443
        return nil
×
444
}
445

446
// CustomMessage is a custom message that is received from a peer.
447
type CustomMessage struct {
448
        // Peer is the peer pubkey
449
        Peer [33]byte
450

451
        // Msg is the custom wire message.
452
        Msg *lnwire.Custom
453
}
454

455
// parseAddr parses an address from its string format to a net.Addr.
UNCOV
456
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
UNCOV
457
        var (
×
UNCOV
458
                host string
×
UNCOV
459
                port int
×
UNCOV
460
        )
×
UNCOV
461

×
UNCOV
462
        // Split the address into its host and port components.
×
UNCOV
463
        h, p, err := net.SplitHostPort(address)
×
UNCOV
464
        if err != nil {
×
465
                // If a port wasn't specified, we'll assume the address only
×
466
                // contains the host so we'll use the default port.
×
467
                host = address
×
468
                port = defaultPeerPort
×
UNCOV
469
        } else {
×
UNCOV
470
                // Otherwise, we'll note both the host and ports.
×
UNCOV
471
                host = h
×
UNCOV
472
                portNum, err := strconv.Atoi(p)
×
UNCOV
473
                if err != nil {
×
474
                        return nil, err
×
475
                }
×
UNCOV
476
                port = portNum
×
477
        }
478

UNCOV
479
        if tor.IsOnionHost(host) {
×
480
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
481
        }
×
482

483
        // If the host is part of a TCP address, we'll use the network
484
        // specific ResolveTCPAddr function in order to resolve these
485
        // addresses over Tor in order to prevent leaking your real IP
486
        // address.
UNCOV
487
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
×
UNCOV
488
        return netCfg.ResolveTCPAddr("tcp", hostPort)
×
489
}
490

491
// noiseDial is a factory function which creates a connmgr compliant dialing
492
// function by returning a closure which includes the server's identity key.
493
func noiseDial(idKey keychain.SingleKeyECDH,
UNCOV
494
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
×
UNCOV
495

×
UNCOV
496
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
497
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
498
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
499
        }
×
500
}
501

502
// newServer creates a new instance of the server which is to listen using the
503
// passed listener address.
504
func newServer(cfg *Config, listenAddrs []net.Addr,
505
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
506
        nodeKeyDesc *keychain.KeyDescriptor,
507
        chansToRestore walletunlocker.ChannelsToRecover,
508
        chanPredicate chanacceptor.ChannelAcceptor,
509
        torController *tor.Controller, tlsManager *TLSManager,
510
        leaderElector cluster.LeaderElector,
UNCOV
511
        implCfg *ImplementationCfg) (*server, error) {
×
UNCOV
512

×
UNCOV
513
        var (
×
UNCOV
514
                err         error
×
UNCOV
515
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
UNCOV
516

×
UNCOV
517
                // We just derived the full descriptor, so we know the public
×
UNCOV
518
                // key is set on it.
×
UNCOV
519
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
×
UNCOV
520
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
×
UNCOV
521
                )
×
UNCOV
522
        )
×
UNCOV
523

×
UNCOV
524
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
525
        for i, listenAddr := range listenAddrs {
×
UNCOV
526
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
527
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
528
                // since we are resolving a local address.
×
UNCOV
529
                listeners[i], err = brontide.NewListener(
×
UNCOV
530
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
531
                )
×
UNCOV
532
                if err != nil {
×
533
                        return nil, err
×
534
                }
×
535
        }
536

UNCOV
537
        var serializedPubKey [33]byte
×
UNCOV
538
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
539

×
UNCOV
540
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
541

×
UNCOV
542
        // Initialize the sphinx router.
×
UNCOV
543
        replayLog := htlcswitch.NewDecayedLog(
×
UNCOV
544
                dbs.DecayedLogDB, cc.ChainNotifier,
×
UNCOV
545
        )
×
UNCOV
546
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
UNCOV
547

×
UNCOV
548
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
549
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
550
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
551
        )
×
UNCOV
552

×
UNCOV
553
        writePool := pool.NewWrite(
×
UNCOV
554
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
UNCOV
555
        )
×
UNCOV
556

×
UNCOV
557
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
558
                pool.DefaultReadBufferGCInterval,
×
UNCOV
559
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
560
        )
×
UNCOV
561

×
UNCOV
562
        readPool := pool.NewRead(
×
UNCOV
563
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
UNCOV
564
        )
×
UNCOV
565

×
UNCOV
566
        // If the taproot overlay flag is set, but we don't have an aux funding
×
UNCOV
567
        // controller, then we'll exit as this is incompatible.
×
UNCOV
568
        if cfg.ProtocolOptions.TaprootOverlayChans &&
×
UNCOV
569
                implCfg.AuxFundingController.IsNone() {
×
570

×
571
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
572
                        "aux controllers")
×
573
        }
×
574

575
        //nolint:ll
UNCOV
576
        featureMgr, err := feature.NewManager(feature.Config{
×
UNCOV
577
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
×
UNCOV
578
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
×
UNCOV
579
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
×
UNCOV
580
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
581
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
×
UNCOV
582
                NoKeysend:                 !cfg.AcceptKeySend,
×
UNCOV
583
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
×
UNCOV
584
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
×
UNCOV
585
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
×
UNCOV
586
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
×
UNCOV
587
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
×
UNCOV
588
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
×
UNCOV
589
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
×
UNCOV
590
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
×
UNCOV
591
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
×
UNCOV
592
        })
×
UNCOV
593
        if err != nil {
×
594
                return nil, err
×
595
        }
×
596

UNCOV
597
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
UNCOV
598
        registryConfig := invoices.RegistryConfig{
×
UNCOV
599
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
600
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
UNCOV
601
                Clock:                       clock.NewDefaultClock(),
×
UNCOV
602
                AcceptKeySend:               cfg.AcceptKeySend,
×
UNCOV
603
                AcceptAMP:                   cfg.AcceptAMP,
×
UNCOV
604
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
UNCOV
605
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
UNCOV
606
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
UNCOV
607
                HtlcInterceptor:             invoiceHtlcModifier,
×
UNCOV
608
        }
×
UNCOV
609

×
UNCOV
610
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
611

×
UNCOV
612
        s := &server{
×
UNCOV
613
                cfg:            cfg,
×
UNCOV
614
                implCfg:        implCfg,
×
UNCOV
615
                graphDB:        dbs.GraphDB,
×
UNCOV
616
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
617
                addrSource:     addrSource,
×
UNCOV
618
                miscDB:         dbs.ChanStateDB,
×
UNCOV
619
                invoicesDB:     dbs.InvoiceDB,
×
UNCOV
620
                cc:             cc,
×
UNCOV
621
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
×
UNCOV
622
                writePool:      writePool,
×
UNCOV
623
                readPool:       readPool,
×
UNCOV
624
                chansToRestore: chansToRestore,
×
UNCOV
625

×
UNCOV
626
                channelNotifier: channelnotifier.New(
×
UNCOV
627
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
628
                ),
×
UNCOV
629

×
UNCOV
630
                identityECDH:   nodeKeyECDH,
×
UNCOV
631
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
632
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
633

×
UNCOV
634
                listenAddrs: listenAddrs,
×
UNCOV
635

×
UNCOV
636
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
637
                // schedule
×
UNCOV
638
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
639

×
UNCOV
640
                torController: torController,
×
UNCOV
641

×
UNCOV
642
                persistentPeers:         make(map[string]bool),
×
UNCOV
643
                persistentPeersBackoff:  make(map[string]time.Duration),
×
UNCOV
644
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
UNCOV
645
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
UNCOV
646
                persistentRetryCancels:  make(map[string]chan struct{}),
×
UNCOV
647
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
UNCOV
648
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
UNCOV
649
                scheduledPeerConnection: make(map[string]func()),
×
UNCOV
650
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
UNCOV
651

×
UNCOV
652
                peersByPub:                make(map[string]*peer.Brontide),
×
UNCOV
653
                inboundPeers:              make(map[string]*peer.Brontide),
×
UNCOV
654
                outboundPeers:             make(map[string]*peer.Brontide),
×
UNCOV
655
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
UNCOV
656
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
UNCOV
657

×
UNCOV
658
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
659

×
UNCOV
660
                customMessageServer: subscribe.NewServer(),
×
UNCOV
661

×
UNCOV
662
                tlsManager: tlsManager,
×
UNCOV
663

×
UNCOV
664
                featureMgr: featureMgr,
×
UNCOV
665
                quit:       make(chan struct{}),
×
UNCOV
666
        }
×
UNCOV
667

×
UNCOV
668
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
669
        if err != nil {
×
670
                return nil, err
×
671
        }
×
672

UNCOV
673
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
674
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
675
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
676
        )
×
UNCOV
677
        s.invoices = invoices.NewRegistry(
×
UNCOV
678
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
679
        )
×
UNCOV
680

×
UNCOV
681
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
682

×
UNCOV
683
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
684
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
685

×
UNCOV
686
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
687
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
688
                if err != nil {
×
689
                        return err
×
690
                }
×
691

UNCOV
692
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
693

×
UNCOV
694
                return nil
×
695
        }
696

UNCOV
697
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
698
        if err != nil {
×
699
                return nil, err
×
700
        }
×
701

UNCOV
702
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
703
                DB:                   dbs.ChanStateDB,
×
UNCOV
704
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
UNCOV
705
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
706
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
707
                LocalChannelClose: func(pubKey []byte,
×
UNCOV
708
                        request *htlcswitch.ChanClose) {
×
UNCOV
709

×
UNCOV
710
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
UNCOV
711
                        if err != nil {
×
712
                                srvrLog.Errorf("unable to close channel, peer"+
×
713
                                        " with %v id can't be found: %v",
×
714
                                        pubKey, err,
×
715
                                )
×
716
                                return
×
717
                        }
×
718

UNCOV
719
                        peer.HandleLocalCloseChanReqs(request)
×
720
                },
721
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
722
                SwitchPackager:         channeldb.NewSwitchPackager(),
723
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
724
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
725
                Notifier:               s.cc.ChainNotifier,
726
                HtlcNotifier:           s.htlcNotifier,
727
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
728
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
729
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
730
                AllowCircularRoute:     cfg.AllowCircularRoute,
731
                RejectHTLC:             cfg.RejectHTLC,
732
                Clock:                  clock.NewDefaultClock(),
733
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
734
                MaxFeeExposure:         thresholdMSats,
735
                SignAliasUpdate:        s.signAliasUpdate,
736
                IsAlias:                aliasmgr.IsAlias,
737
        }, uint32(currentHeight))
UNCOV
738
        if err != nil {
×
739
                return nil, err
×
740
        }
×
UNCOV
741
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
UNCOV
742
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
743
                        Switch:             s.htlcSwitch,
×
UNCOV
744
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
745
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
UNCOV
746
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
UNCOV
747
                        Notifier:           s.cc.ChainNotifier,
×
UNCOV
748
                },
×
UNCOV
749
        )
×
UNCOV
750
        if err != nil {
×
751
                return nil, err
×
752
        }
×
753

UNCOV
754
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
755
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
756
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
757
        )
×
UNCOV
758

×
UNCOV
759
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
760
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
761
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
UNCOV
762
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
UNCOV
763
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
764
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
765
                MessageSigner:            s.nodeSigner,
×
UNCOV
766
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
UNCOV
767
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
768
                DB:                       s.chanStateDB,
×
UNCOV
769
                Graph:                    dbs.GraphDB,
×
UNCOV
770
        }
×
UNCOV
771

×
UNCOV
772
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
773
        if err != nil {
×
774
                return nil, err
×
775
        }
×
UNCOV
776
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
777

×
UNCOV
778
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
779
        // port forwarding for users behind a NAT.
×
UNCOV
780
        if cfg.NAT {
×
781
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
782

×
783
                discoveryTimeout := time.Duration(10 * time.Second)
×
784

×
785
                ctx, cancel := context.WithTimeout(
×
786
                        context.Background(), discoveryTimeout,
×
787
                )
×
788
                defer cancel()
×
789
                upnp, err := nat.DiscoverUPnP(ctx)
×
790
                if err == nil {
×
791
                        s.natTraversal = upnp
×
792
                } else {
×
793
                        // If we were not able to discover a UPnP enabled device
×
794
                        // on the local network, we'll fall back to attempting
×
795
                        // to discover a NAT-PMP enabled device.
×
796
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
797
                                "device on the local network: %v", err)
×
798

×
799
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
800
                                "enabled device")
×
801

×
802
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
803
                        if err != nil {
×
804
                                err := fmt.Errorf("unable to discover a "+
×
805
                                        "NAT-PMP enabled device on the local "+
×
806
                                        "network: %v", err)
×
807
                                srvrLog.Error(err)
×
808
                                return nil, err
×
809
                        }
×
810

811
                        s.natTraversal = pmp
×
812
                }
813
        }
814

815
        // If we were requested to automatically configure port forwarding,
816
        // we'll use the ports that the server will be listening on.
UNCOV
817
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
818
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
819
                externalIPStrings[idx] = ip.String()
×
UNCOV
820
        }
×
UNCOV
821
        if s.natTraversal != nil {
×
822
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
823
                for _, listenAddr := range listenAddrs {
×
824
                        // At this point, the listen addresses should have
×
825
                        // already been normalized, so it's safe to ignore the
×
826
                        // errors.
×
827
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
828
                        port, _ := strconv.Atoi(portStr)
×
829

×
830
                        listenPorts = append(listenPorts, uint16(port))
×
831
                }
×
832

833
                ips, err := s.configurePortForwarding(listenPorts...)
×
834
                if err != nil {
×
835
                        srvrLog.Errorf("Unable to automatically set up port "+
×
836
                                "forwarding using %s: %v",
×
837
                                s.natTraversal.Name(), err)
×
838
                } else {
×
839
                        srvrLog.Infof("Automatically set up port forwarding "+
×
840
                                "using %s to advertise external IP",
×
841
                                s.natTraversal.Name())
×
842
                        externalIPStrings = append(externalIPStrings, ips...)
×
843
                }
×
844
        }
845

846
        // If external IP addresses have been specified, add those to the list
847
        // of this server's addresses.
UNCOV
848
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
849
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
850
                cfg.net.ResolveTCPAddr,
×
UNCOV
851
        )
×
UNCOV
852
        if err != nil {
×
853
                return nil, err
×
854
        }
×
855

UNCOV
856
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
UNCOV
857
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
858

×
UNCOV
859
        // We'll now reconstruct a node announcement based on our current
×
UNCOV
860
        // configuration so we can send it out as a sort of heart beat within
×
UNCOV
861
        // the network.
×
UNCOV
862
        //
×
UNCOV
863
        // We'll start by parsing the node color from configuration.
×
UNCOV
864
        color, err := lncfg.ParseHexColor(cfg.Color)
×
UNCOV
865
        if err != nil {
×
866
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
867
                return nil, err
×
868
        }
×
869

870
        // If no alias is provided, default to first 10 characters of public
871
        // key.
UNCOV
872
        alias := cfg.Alias
×
UNCOV
873
        if alias == "" {
×
UNCOV
874
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
875
        }
×
UNCOV
876
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
877
        if err != nil {
×
878
                return nil, err
×
879
        }
×
UNCOV
880
        selfNode := &models.LightningNode{
×
UNCOV
881
                HaveNodeAnnouncement: true,
×
UNCOV
882
                LastUpdate:           time.Now(),
×
UNCOV
883
                Addresses:            selfAddrs,
×
UNCOV
884
                Alias:                nodeAlias.String(),
×
UNCOV
885
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
886
                Color:                color,
×
UNCOV
887
        }
×
UNCOV
888
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
889

×
UNCOV
890
        // Based on the disk representation of the node announcement generated
×
UNCOV
891
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
892
        // network so we can properly sign it.
×
UNCOV
893
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
894
        if err != nil {
×
895
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
896
        }
×
897

898
        // With the announcement generated, we'll sign it to properly
899
        // authenticate the message on the network.
UNCOV
900
        authSig, err := netann.SignAnnouncement(
×
UNCOV
901
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
902
        )
×
UNCOV
903
        if err != nil {
×
904
                return nil, fmt.Errorf("unable to generate signature for "+
×
905
                        "self node announcement: %v", err)
×
906
        }
×
UNCOV
907
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
908
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
909
                selfNode.AuthSigBytes,
×
UNCOV
910
        )
×
UNCOV
911
        if err != nil {
×
912
                return nil, err
×
913
        }
×
914

915
        // Finally, we'll update the representation on disk, and update our
916
        // cached in-memory version as well.
UNCOV
917
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
×
918
                return nil, fmt.Errorf("can't set self node: %w", err)
×
919
        }
×
UNCOV
920
        s.currentNodeAnn = nodeAnn
×
UNCOV
921

×
UNCOV
922
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
923
        // can generate unique payment IDs.
×
UNCOV
924
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
925
        if err != nil {
×
926
                return nil, err
×
927
        }
×
928

929
        // Instantiate mission control with config from the sub server.
930
        //
931
        // TODO(joostjager): When we are further in the process of moving to sub
932
        // servers, the mission control instance itself can be moved there too.
UNCOV
933
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
934

×
UNCOV
935
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
936
        var estimator routing.Estimator
×
UNCOV
937
        if cfg.Estimator != nil {
×
938
                estimator = cfg.Estimator
×
UNCOV
939
        } else {
×
UNCOV
940
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
941
                case routing.AprioriEstimatorName:
×
UNCOV
942
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
943
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
944
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
945
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
946
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
947
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
948
                        }
×
UNCOV
949

×
UNCOV
950
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
951
                                aprioriConfig,
×
UNCOV
952
                        )
×
UNCOV
953
                        if err != nil {
×
954
                                return nil, err
×
955
                        }
×
956

957
                case routing.BimodalEstimatorName:
×
958
                        bCfg := routingConfig.BimodalConfig
×
959
                        bimodalConfig := routing.BimodalConfig{
×
960
                                BimodalNodeWeight: bCfg.NodeWeight,
×
961
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
962
                                        bCfg.Scale,
×
963
                                ),
×
964
                                BimodalDecayTime: bCfg.DecayTime,
×
965
                        }
×
966

×
967
                        estimator, err = routing.NewBimodalEstimator(
×
968
                                bimodalConfig,
×
969
                        )
×
970
                        if err != nil {
×
971
                                return nil, err
×
972
                        }
×
973

974
                default:
×
975
                        return nil, fmt.Errorf("unknown estimator type %v",
×
976
                                routingConfig.ProbabilityEstimatorType)
×
977
                }
978
        }
979

UNCOV
980
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
981
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
982
                Estimator:               estimator,
×
UNCOV
983
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
984
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
985
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
986
        }
×
UNCOV
987

×
UNCOV
988
        s.missionController, err = routing.NewMissionController(
×
UNCOV
989
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
990
        )
×
UNCOV
991
        if err != nil {
×
992
                return nil, fmt.Errorf("can't create mission control "+
×
993
                        "manager: %w", err)
×
994
        }
×
UNCOV
995
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
996
                routing.DefaultMissionControlNamespace,
×
UNCOV
997
        )
×
UNCOV
998
        if err != nil {
×
999
                return nil, fmt.Errorf("can't create mission control in the "+
×
1000
                        "default namespace: %w", err)
×
1001
        }
×
1002

UNCOV
1003
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
1004
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
1005
                int64(routingConfig.AttemptCost),
×
UNCOV
1006
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
1007
                routingConfig.MinRouteProbability)
×
UNCOV
1008

×
UNCOV
1009
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
1010
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
1011
                        routingConfig.AttemptCost,
×
UNCOV
1012
                ),
×
UNCOV
1013
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
1014
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1015
        }
×
UNCOV
1016

×
UNCOV
1017
        sourceNode, err := dbs.GraphDB.SourceNode()
×
UNCOV
1018
        if err != nil {
×
1019
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1020
        }
×
UNCOV
1021
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1022
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
×
UNCOV
1023
                        dbs.GraphDB,
×
UNCOV
1024
                ),
×
UNCOV
1025
                SourceNode:        sourceNode,
×
UNCOV
1026
                MissionControl:    s.defaultMC,
×
UNCOV
1027
                GetLink:           s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1028
                PathFindingConfig: pathFindingConfig,
×
UNCOV
1029
        }
×
UNCOV
1030

×
UNCOV
1031
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1032

×
UNCOV
1033
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1034

×
UNCOV
1035
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1036
                cfg.Routing.StrictZombiePruning
×
UNCOV
1037

×
UNCOV
1038
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1039
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1040
                Graph:               dbs.GraphDB,
×
UNCOV
1041
                Chain:               cc.ChainIO,
×
UNCOV
1042
                ChainView:           cc.ChainView,
×
UNCOV
1043
                Notifier:            cc.ChainNotifier,
×
UNCOV
1044
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1045
                GraphPruneInterval:  time.Hour,
×
UNCOV
1046
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1047
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1048
                StrictZombiePruning: strictPruning,
×
UNCOV
1049
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1050
        })
×
UNCOV
1051
        if err != nil {
×
1052
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1053
        }
×
1054

UNCOV
1055
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1056
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1057
                RoutingGraph:       graphsession.NewRoutingGraph(dbs.GraphDB),
×
UNCOV
1058
                Chain:              cc.ChainIO,
×
UNCOV
1059
                Payer:              s.htlcSwitch,
×
UNCOV
1060
                Control:            s.controlTower,
×
UNCOV
1061
                MissionControl:     s.defaultMC,
×
UNCOV
1062
                SessionSource:      paymentSessionSource,
×
UNCOV
1063
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1064
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1065
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1066
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1067
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1068
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1069
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1070
        })
×
UNCOV
1071
        if err != nil {
×
1072
                return nil, fmt.Errorf("can't create router: %w", err)
×
1073
        }
×
1074

UNCOV
1075
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1076
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1077
        if err != nil {
×
1078
                return nil, err
×
1079
        }
×
UNCOV
1080
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1081
        if err != nil {
×
1082
                return nil, err
×
1083
        }
×
1084

UNCOV
1085
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1086

×
UNCOV
1087
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1088
                Graph:                 s.graphBuilder,
×
UNCOV
1089
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1090
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1091
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1092
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1093
                ChanSeries:            chanSeries,
×
UNCOV
1094
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1095
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1096
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1097
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1098
                        error) {
×
1099

×
1100
                        return s.genNodeAnnouncement(nil)
×
1101
                },
×
1102
                ProofMatureDelta:        0,
1103
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1104
                RetransmitTicker:        ticker.New(time.Minute * 30),
1105
                RebroadcastInterval:     time.Hour * 24,
1106
                WaitingProofStore:       waitingProofStore,
1107
                MessageStore:            gossipMessageStore,
1108
                AnnSigner:               s.nodeSigner,
1109
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1110
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1111
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1112
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1113
                MinimumBatchSize:        10,
1114
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1115
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1116
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1117
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1118
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1119
                IsAlias:                 aliasmgr.IsAlias,
1120
                SignAliasUpdate:         s.signAliasUpdate,
1121
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1122
                GetAlias:                s.aliasMgr.GetPeerAlias,
1123
                FindChannel:             s.findChannel,
1124
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1125
                ScidCloser:              scidCloserMan,
1126
        }, nodeKeyDesc)
1127

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

×
UNCOV
1136
                        return s.graphDB.ForEachNodeChannel(selfVertex,
×
UNCOV
1137
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
×
UNCOV
1138
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1139
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1140

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
1357
                        // Get the circuit map.
×
UNCOV
1358
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1359

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

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

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

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

1383
        // Wrap the `ReAddChannelEdge` method so that the funding manager can
1384
        // use it without depending on several layers of indirection.
NEW
1385
        reAssignSCID := func(aliasScID, newScID lnwire.ShortChannelID) (
×
UNCOV
1386
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1387

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

1401
                // We create a new ChannelEdgeInfo with the new SCID.
NEW
1402
                newEdgeInfo := new(models.ChannelEdgeInfo)
×
NEW
1403
                *newEdgeInfo = *info
×
NEW
1404
                newEdgeInfo.ChannelID = newScID.ToUint64()
×
NEW
1405

×
NEW
1406
                // We also readd the channel policy from our side with the new
×
NEW
1407
                // short channel id so we grab our key to find our policy.
×
UNCOV
1408
                var ourKey [33]byte
×
UNCOV
1409
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1410

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

UNCOV
1418
                if ourPolicy == nil {
×
NEW
1419
                        // We should always have our policy available. If that
×
NEW
1420
                        // is not the case there might be an error in the
×
NEW
1421
                        // ChannelUpdate msg logic so we return early.
×
NEW
1422
                        return nil, fmt.Errorf("edge policy not found")
×
UNCOV
1423
                }
×
1424

1425
                // Update the policy data, this invalidates the signature
1426
                // therefore we need to resign the data.
NEW
1427
                ourPolicy.ChannelID = newEdgeInfo.ChannelID
×
NEW
1428
                chanUpdate := netann.UnsignedChannelUpdateFromEdge(
×
NEW
1429
                        newEdgeInfo, ourPolicy,
×
UNCOV
1430
                )
×
NEW
1431

×
NEW
1432
                data, err := chanUpdate.DataToSign()
×
NEW
1433
                if err != nil {
×
NEW
1434
                        return nil, err
×
NEW
1435
                }
×
1436

NEW
1437
                nodeSig, err := cc.MsgSigner.SignMessage(
×
NEW
1438
                        nodeKeyDesc.KeyLocator, data, true,
×
NEW
1439
                )
×
NEW
1440
                if err != nil {
×
NEW
1441
                        return nil, err
×
NEW
1442
                }
×
1443

NEW
1444
                sig, err := lnwire.NewSigFromSignature(nodeSig)
×
NEW
1445
                if err != nil {
×
NEW
1446
                        return nil, err
×
NEW
1447
                }
×
NEW
1448
                ourPolicy.SetSigBytes(sig.ToSignatureBytes())
×
NEW
1449

×
NEW
1450
                // Delete the old edge information under the alias SCID and add
×
NEW
1451
                // the updated data with the new SCID.
×
NEW
1452
                err = s.graphDB.ReAddChannelEdge(
×
NEW
1453
                        aliasScID.ToUint64(), newEdgeInfo, ourPolicy,
×
NEW
1454
                )
×
NEW
1455

×
UNCOV
1456
                return ourPolicy, err
×
1457
        }
1458

1459
        // For the reservationTimeout and the zombieSweeperInterval different
1460
        // values are set in case we are in a dev environment so enhance test
1461
        // capacilities.
UNCOV
1462
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1463
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1464

×
UNCOV
1465
        // Get the development config for funding manager. If we are not in
×
UNCOV
1466
        // development mode, this would be nil.
×
UNCOV
1467
        var devCfg *funding.DevConfig
×
UNCOV
1468
        if lncfg.IsDevBuild() {
×
UNCOV
1469
                devCfg = &funding.DevConfig{
×
UNCOV
1470
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1471
                }
×
UNCOV
1472

×
UNCOV
1473
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1474
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1475

×
UNCOV
1476
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1477
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1478
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1479
        }
×
1480

1481
        //nolint:ll
UNCOV
1482
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1483
                Dev:                devCfg,
×
UNCOV
1484
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1485
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1486
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1487
                Wallet:             cc.Wallet,
×
UNCOV
1488
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1489
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1490
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1491
                },
×
1492
                Notifier:     cc.ChainNotifier,
1493
                ChannelDB:    s.chanStateDB,
1494
                FeeEstimator: cc.FeeEstimator,
1495
                SignMessage:  cc.MsgSigner.SignMessage,
1496
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1497
                        error) {
×
UNCOV
1498

×
UNCOV
1499
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1500
                },
×
1501
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1502
                NotifyWhenOnline:     s.NotifyWhenOnline,
1503
                TempChanIDSeed:       chanIDSeed,
1504
                FindChannel:          s.findChannel,
1505
                DefaultRoutingPolicy: cc.RoutingPolicy,
1506
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1507
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1508
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1509
                        // For large channels we increase the number
×
UNCOV
1510
                        // of confirmations we require for the
×
UNCOV
1511
                        // channel to be considered open. As it is
×
UNCOV
1512
                        // always the responder that gets to choose
×
UNCOV
1513
                        // value, the pushAmt is value being pushed
×
UNCOV
1514
                        // to us. This means we have more to lose
×
UNCOV
1515
                        // in the case this gets re-orged out, and
×
UNCOV
1516
                        // we will require more confirmations before
×
UNCOV
1517
                        // we consider it open.
×
UNCOV
1518

×
UNCOV
1519
                        // In case the user has explicitly specified
×
UNCOV
1520
                        // a default value for the number of
×
UNCOV
1521
                        // confirmations, we use it.
×
UNCOV
1522
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1523
                        if defaultConf != 0 {
×
UNCOV
1524
                                return defaultConf
×
UNCOV
1525
                        }
×
1526

1527
                        minConf := uint64(3)
×
1528
                        maxConf := uint64(6)
×
1529

×
1530
                        // If this is a wumbo channel, then we'll require the
×
1531
                        // max amount of confirmations.
×
1532
                        if chanAmt > MaxFundingAmount {
×
1533
                                return uint16(maxConf)
×
1534
                        }
×
1535

1536
                        // If not we return a value scaled linearly
1537
                        // between 3 and 6, depending on channel size.
1538
                        // TODO(halseth): Use 1 as minimum?
1539
                        maxChannelSize := uint64(
×
1540
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1541
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1542
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1543
                        if conf < minConf {
×
1544
                                conf = minConf
×
1545
                        }
×
1546
                        if conf > maxConf {
×
1547
                                conf = maxConf
×
1548
                        }
×
1549
                        return uint16(conf)
×
1550
                },
UNCOV
1551
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1552
                        // We scale the remote CSV delay (the time the
×
UNCOV
1553
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1554
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1555
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1556
                        // for channels of size MaxFundingAmount.
×
UNCOV
1557

×
UNCOV
1558
                        // In case the user has explicitly specified
×
UNCOV
1559
                        // a default value for the remote delay, we
×
UNCOV
1560
                        // use it.
×
UNCOV
1561
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1562
                        if defaultDelay > 0 {
×
UNCOV
1563
                                return defaultDelay
×
UNCOV
1564
                        }
×
1565

1566
                        // If this is a wumbo channel, then we'll require the
1567
                        // max value.
1568
                        if chanAmt > MaxFundingAmount {
×
1569
                                return maxRemoteDelay
×
1570
                        }
×
1571

1572
                        // If not we scale according to channel size.
1573
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1574
                                chanAmt / MaxFundingAmount)
×
1575
                        if delay < minRemoteDelay {
×
1576
                                delay = minRemoteDelay
×
1577
                        }
×
1578
                        if delay > maxRemoteDelay {
×
1579
                                delay = maxRemoteDelay
×
1580
                        }
×
1581
                        return delay
×
1582
                },
1583
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1584
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1585

×
UNCOV
1586
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1587
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1588
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1589
                        // we'll set false to prevent the server from continuing
×
UNCOV
1590
                        // to connect to this peer even if the number of
×
UNCOV
1591
                        // channels with this peer is zero.
×
UNCOV
1592
                        s.mu.Lock()
×
UNCOV
1593
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1594
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1595
                                s.persistentPeers[pubStr] = false
×
UNCOV
1596
                        }
×
UNCOV
1597
                        s.mu.Unlock()
×
UNCOV
1598

×
UNCOV
1599
                        // With that taken care of, we'll send this channel to
×
UNCOV
1600
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1601
                        return s.chainArb.WatchNewChannel(channel)
×
1602
                },
UNCOV
1603
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1604
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1605
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1606
                },
×
1607
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1608
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1609

×
UNCOV
1610
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1611
                        // at least 1% of the total channel capacity at all
×
UNCOV
1612
                        // times. If this value ends up dipping below the dust
×
UNCOV
1613
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1614
                        // reserve as required by BOLT #2.
×
UNCOV
1615
                        reserve := chanAmt / 100
×
UNCOV
1616
                        if reserve < dustLimit {
×
UNCOV
1617
                                reserve = dustLimit
×
UNCOV
1618
                        }
×
1619

UNCOV
1620
                        return reserve
×
1621
                },
UNCOV
1622
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1623
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1624
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1625
                        // required reserve.
×
UNCOV
1626
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1627
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1628
                },
×
UNCOV
1629
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1630
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1631
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1632
                        }
×
1633

1634
                        // By default, we'll permit them to utilize the full
1635
                        // channel bandwidth.
1636
                        return uint16(input.MaxHTLCNumber / 2)
×
1637
                },
1638
                ZombieSweeperInterval:         zombieSweeperInterval,
1639
                ReservationTimeout:            reservationTimeout,
1640
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1641
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1642
                MaxPendingChannels:            cfg.MaxPendingChannels,
1643
                RejectPush:                    cfg.RejectPush,
1644
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1645
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1646
                OpenChannelPredicate:          chanPredicate,
1647
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1648
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1649
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1650
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1651
                ReAssignSCID:         reAssignSCID,
1652
                AliasManager:         s.aliasMgr,
1653
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1654
                AuxFundingController: implCfg.AuxFundingController,
1655
                AuxSigner:            implCfg.AuxSigner,
1656
                AuxResolver:          implCfg.AuxContractResolver,
1657
        })
UNCOV
1658
        if err != nil {
×
1659
                return nil, err
×
1660
        }
×
1661

1662
        // Next, we'll assemble the sub-system that will maintain an on-disk
1663
        // static backup of the latest channel state.
UNCOV
1664
        chanNotifier := &channelNotifier{
×
UNCOV
1665
                chanNotifier: s.channelNotifier,
×
UNCOV
1666
                addrs:        s.addrSource,
×
UNCOV
1667
        }
×
UNCOV
1668
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
×
UNCOV
1669
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1670
                s.chanStateDB, s.addrSource,
×
UNCOV
1671
        )
×
UNCOV
1672
        if err != nil {
×
1673
                return nil, err
×
1674
        }
×
UNCOV
1675
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1676
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1677
        )
×
UNCOV
1678
        if err != nil {
×
1679
                return nil, err
×
1680
        }
×
1681

1682
        // Assemble a peer notifier which will provide clients with subscriptions
1683
        // to peer online and offline events.
UNCOV
1684
        s.peerNotifier = peernotifier.New()
×
UNCOV
1685

×
UNCOV
1686
        // Create a channel event store which monitors all open channels.
×
UNCOV
1687
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1688
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1689
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1690
                },
×
UNCOV
1691
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1692
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1693
                },
×
1694
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1695
                Clock:           clock.NewDefaultClock(),
1696
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1697
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1698
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1699
        })
1700

UNCOV
1701
        if cfg.WtClient.Active {
×
UNCOV
1702
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1703
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1704

×
UNCOV
1705
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1706
                // protocol operations on sat/kw.
×
UNCOV
1707
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1708
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1709
                )
×
UNCOV
1710

×
UNCOV
1711
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1712

×
UNCOV
1713
                if err := policy.Validate(); err != nil {
×
1714
                        return nil, err
×
1715
                }
×
1716

1717
                // authDial is the wrapper around the btrontide.Dial for the
1718
                // watchtower.
UNCOV
1719
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1720
                        netAddr *lnwire.NetAddress,
×
UNCOV
1721
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1722

×
UNCOV
1723
                        return brontide.Dial(
×
UNCOV
1724
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1725
                        )
×
UNCOV
1726
                }
×
1727

1728
                // buildBreachRetribution is a call-back that can be used to
1729
                // query the BreachRetribution info and channel type given a
1730
                // channel ID and commitment height.
UNCOV
1731
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1732
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1733
                        channeldb.ChannelType, error) {
×
UNCOV
1734

×
UNCOV
1735
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1736
                                nil, chanID,
×
UNCOV
1737
                        )
×
UNCOV
1738
                        if err != nil {
×
1739
                                return nil, 0, err
×
1740
                        }
×
1741

UNCOV
1742
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1743
                                channel, commitHeight, 0, nil,
×
UNCOV
1744
                                implCfg.AuxLeafStore,
×
UNCOV
1745
                                implCfg.AuxContractResolver,
×
UNCOV
1746
                        )
×
UNCOV
1747
                        if err != nil {
×
1748
                                return nil, 0, err
×
1749
                        }
×
1750

UNCOV
1751
                        return br, channel.ChanType, nil
×
1752
                }
1753

UNCOV
1754
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1755

×
UNCOV
1756
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1757
                // signalling support for anchor channels.
×
UNCOV
1758
                anchorPolicy := policy
×
UNCOV
1759
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1760

×
UNCOV
1761
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1762
                // signalling support for taproot channels.
×
UNCOV
1763
                taprootPolicy := policy
×
UNCOV
1764
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1765
                        blob.FlagTaprootChannel,
×
UNCOV
1766
                )
×
UNCOV
1767

×
UNCOV
1768
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1769
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1770
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1771
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1772
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1773
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1774
                                error) {
×
UNCOV
1775

×
UNCOV
1776
                                return s.channelNotifier.
×
UNCOV
1777
                                        SubscribeChannelEvents()
×
UNCOV
1778
                        },
×
1779
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1780
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1781
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1782
                                        cc.Wallet, netParams,
×
UNCOV
1783
                                )().Unpack()
×
UNCOV
1784
                                if err != nil {
×
1785
                                        return nil, err
×
1786
                                }
×
1787

UNCOV
1788
                                return addr.DeliveryAddress, nil
×
1789
                        },
1790
                        SecretKeyRing:      s.cc.KeyRing,
1791
                        Dial:               cfg.net.Dial,
1792
                        AuthDial:           authDial,
1793
                        DB:                 dbs.TowerClientDB,
1794
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1795
                        MinBackoff:         10 * time.Second,
1796
                        MaxBackoff:         5 * time.Minute,
1797
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1798
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1799
                if err != nil {
×
1800
                        return nil, err
×
1801
                }
×
1802
        }
1803

UNCOV
1804
        if len(cfg.ExternalHosts) != 0 {
×
1805
                advertisedIPs := make(map[string]struct{})
×
1806
                for _, addr := range s.currentNodeAnn.Addresses {
×
1807
                        advertisedIPs[addr.String()] = struct{}{}
×
1808
                }
×
1809

1810
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1811
                        Hosts:         cfg.ExternalHosts,
×
1812
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1813
                        LookupHost: func(host string) (net.Addr, error) {
×
1814
                                return lncfg.ParseAddressString(
×
1815
                                        host, strconv.Itoa(defaultPeerPort),
×
1816
                                        cfg.net.ResolveTCPAddr,
×
1817
                                )
×
1818
                        },
×
1819
                        AdvertisedIPs: advertisedIPs,
1820
                        AnnounceNewIPs: netann.IPAnnouncer(
1821
                                func(modifier ...netann.NodeAnnModifier) (
1822
                                        lnwire.NodeAnnouncement, error) {
×
1823

×
1824
                                        return s.genNodeAnnouncement(
×
1825
                                                nil, modifier...,
×
1826
                                        )
×
1827
                                }),
×
1828
                })
1829
        }
1830

1831
        // Create liveness monitor.
UNCOV
1832
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1833

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

×
UNCOV
1852
        return s, nil
×
1853
}
1854

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

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

×
UNCOV
1865
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1866
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1867
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1868
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1869
                targetCfg.HopProbability = c.AprioriHopProbability
×
1870

UNCOV
1871
        case routing.BimodalConfig:
×
UNCOV
1872
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1873
                        routing.BimodalEstimatorName
×
UNCOV
1874

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

UNCOV
1881
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1882
}
1883

1884
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1885
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1886
// may differ from what is on disk.
1887
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1888
        error) {
×
UNCOV
1889

×
UNCOV
1890
        data, err := u.DataToSign()
×
UNCOV
1891
        if err != nil {
×
1892
                return nil, err
×
1893
        }
×
1894

UNCOV
1895
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1896
}
1897

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

×
UNCOV
1911
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
1912
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1913
                srvrLog.Info("Disabling chain backend checks for " +
×
1914
                        "nochainbackend mode")
×
1915

×
1916
                chainBackendAttempts = 0
×
1917
        }
×
1918

UNCOV
1919
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1920
                "chain backend",
×
UNCOV
1921
                cc.HealthCheck,
×
UNCOV
1922
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1923
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
1924
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1925
                chainBackendAttempts,
×
UNCOV
1926
        )
×
UNCOV
1927

×
UNCOV
1928
        diskCheck := healthcheck.NewObservation(
×
UNCOV
1929
                "disk space",
×
UNCOV
1930
                func() error {
×
1931
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1932
                                cfg.LndDir,
×
1933
                        )
×
1934
                        if err != nil {
×
1935
                                return err
×
1936
                        }
×
1937

1938
                        // If we have more free space than we require,
1939
                        // we return a nil error.
1940
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1941
                                return nil
×
1942
                        }
×
1943

1944
                        return fmt.Errorf("require: %v free space, got: %v",
×
1945
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1946
                                free)
×
1947
                },
1948
                cfg.HealthChecks.DiskCheck.Interval,
1949
                cfg.HealthChecks.DiskCheck.Timeout,
1950
                cfg.HealthChecks.DiskCheck.Backoff,
1951
                cfg.HealthChecks.DiskCheck.Attempts,
1952
        )
1953

UNCOV
1954
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
1955
                "tls",
×
UNCOV
1956
                func() error {
×
1957
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1958
                                s.cc.KeyRing,
×
1959
                        )
×
1960
                        if err != nil {
×
1961
                                return err
×
1962
                        }
×
1963
                        if expired {
×
1964
                                return fmt.Errorf("TLS certificate is "+
×
1965
                                        "expired as of %v", expTime)
×
1966
                        }
×
1967

1968
                        // If the certificate is not outdated, no error needs
1969
                        // to be returned
1970
                        return nil
×
1971
                },
1972
                cfg.HealthChecks.TLSCheck.Interval,
1973
                cfg.HealthChecks.TLSCheck.Timeout,
1974
                cfg.HealthChecks.TLSCheck.Backoff,
1975
                cfg.HealthChecks.TLSCheck.Attempts,
1976
        )
1977

UNCOV
1978
        checks := []*healthcheck.Observation{
×
UNCOV
1979
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
1980
        }
×
UNCOV
1981

×
UNCOV
1982
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
1983
        if s.torController != nil {
×
1984
                torConnectionCheck := healthcheck.NewObservation(
×
1985
                        "tor connection",
×
1986
                        func() error {
×
1987
                                return healthcheck.CheckTorServiceStatus(
×
1988
                                        s.torController,
×
1989
                                        s.createNewHiddenService,
×
1990
                                )
×
1991
                        },
×
1992
                        cfg.HealthChecks.TorConnection.Interval,
1993
                        cfg.HealthChecks.TorConnection.Timeout,
1994
                        cfg.HealthChecks.TorConnection.Backoff,
1995
                        cfg.HealthChecks.TorConnection.Attempts,
1996
                )
1997
                checks = append(checks, torConnectionCheck)
×
1998
        }
1999

2000
        // If remote signing is enabled, add the healthcheck for the remote
2001
        // signing RPC interface.
UNCOV
2002
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
2003
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
2004
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
2005
                // returns exactly on time.
×
UNCOV
2006
                overhead := time.Millisecond * 10
×
UNCOV
2007

×
UNCOV
2008
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2009
                        "remote signer connection",
×
UNCOV
2010
                        rpcwallet.HealthCheck(
×
UNCOV
2011
                                s.cfg.RemoteSigner,
×
UNCOV
2012

×
UNCOV
2013
                                // For the health check we might to be even
×
UNCOV
2014
                                // stricter than the initial/normal connect, so
×
UNCOV
2015
                                // we use the health check timeout here.
×
UNCOV
2016
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2017
                        ),
×
UNCOV
2018
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2019
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2020
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2021
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2022
                )
×
UNCOV
2023
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2024
        }
×
2025

2026
        // If we have a leader elector, we add a health check to ensure we are
2027
        // still the leader. During normal operation, we should always be the
2028
        // leader, but there are circumstances where this may change, such as
2029
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2030
        if leaderElector != nil {
×
2031
                leaderCheck := healthcheck.NewObservation(
×
2032
                        "leader status",
×
2033
                        func() error {
×
2034
                                // Check if we are still the leader. Note that
×
2035
                                // we don't need to use a timeout context here
×
2036
                                // as the healthcheck observer will handle the
×
2037
                                // timeout case for us.
×
2038
                                timeoutCtx, cancel := context.WithTimeout(
×
2039
                                        context.Background(),
×
2040
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2041
                                )
×
2042
                                defer cancel()
×
2043

×
2044
                                leader, err := leaderElector.IsLeader(
×
2045
                                        timeoutCtx,
×
2046
                                )
×
2047
                                if err != nil {
×
2048
                                        return fmt.Errorf("unable to check if "+
×
2049
                                                "still leader: %v", err)
×
2050
                                }
×
2051

2052
                                if !leader {
×
2053
                                        srvrLog.Debug("Not the current leader")
×
2054
                                        return fmt.Errorf("not the current " +
×
2055
                                                "leader")
×
2056
                                }
×
2057

2058
                                return nil
×
2059
                        },
2060
                        cfg.HealthChecks.LeaderCheck.Interval,
2061
                        cfg.HealthChecks.LeaderCheck.Timeout,
2062
                        cfg.HealthChecks.LeaderCheck.Backoff,
2063
                        cfg.HealthChecks.LeaderCheck.Attempts,
2064
                )
2065

2066
                checks = append(checks, leaderCheck)
×
2067
        }
2068

2069
        // If we have not disabled all of our health checks, we create a
2070
        // liveness monitor with our configured checks.
UNCOV
2071
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2072
                &healthcheck.Config{
×
UNCOV
2073
                        Checks:   checks,
×
UNCOV
2074
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2075
                },
×
UNCOV
2076
        )
×
2077
}
2078

2079
// Started returns true if the server has been started, and false otherwise.
2080
// NOTE: This function is safe for concurrent access.
UNCOV
2081
func (s *server) Started() bool {
×
UNCOV
2082
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2083
}
×
2084

2085
// cleaner is used to aggregate "cleanup" functions during an operation that
2086
// starts several subsystems. In case one of the subsystem fails to start
2087
// and a proper resource cleanup is required, the "run" method achieves this
2088
// by running all these added "cleanup" functions.
2089
type cleaner []func() error
2090

2091
// add is used to add a cleanup function to be called when
2092
// the run function is executed.
UNCOV
2093
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2094
        return append(c, cleanup)
×
UNCOV
2095
}
×
2096

2097
// run is used to run all the previousely added cleanup functions.
2098
func (c cleaner) run() {
×
2099
        for i := len(c) - 1; i >= 0; i-- {
×
2100
                if err := c[i](); err != nil {
×
2101
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2102
                }
×
2103
        }
2104
}
2105

2106
// Start starts the main daemon server, all requested listeners, and any helper
2107
// goroutines.
2108
// NOTE: This function is safe for concurrent access.
2109
//
2110
//nolint:funlen
UNCOV
2111
func (s *server) Start() error {
×
UNCOV
2112
        var startErr error
×
UNCOV
2113

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

×
UNCOV
2119
        s.start.Do(func() {
×
UNCOV
2120
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2121
                if err := s.customMessageServer.Start(); err != nil {
×
2122
                        startErr = err
×
2123
                        return
×
2124
                }
×
2125

UNCOV
2126
                if s.hostAnn != nil {
×
2127
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2128
                        if err := s.hostAnn.Start(); err != nil {
×
2129
                                startErr = err
×
2130
                                return
×
2131
                        }
×
2132
                }
2133

UNCOV
2134
                if s.livenessMonitor != nil {
×
UNCOV
2135
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
UNCOV
2136
                        if err := s.livenessMonitor.Start(); err != nil {
×
2137
                                startErr = err
×
2138
                                return
×
2139
                        }
×
2140
                }
2141

2142
                // Start the notification server. This is used so channel
2143
                // management goroutines can be notified when a funding
2144
                // transaction reaches a sufficient number of confirmations, or
2145
                // when the input for the funding transaction is spent in an
2146
                // attempt at an uncooperative close by the counterparty.
UNCOV
2147
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2148
                if err := s.sigPool.Start(); err != nil {
×
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152

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

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

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

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

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

UNCOV
2183
                cleanup = cleanup.add(func() error {
×
2184
                        return s.peerNotifier.Stop()
×
2185
                })
×
UNCOV
2186
                if err := s.peerNotifier.Start(); err != nil {
×
2187
                        startErr = err
×
2188
                        return
×
2189
                }
×
2190

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

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

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

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

UNCOV
2217
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2218
                if err := s.utxoNursery.Start(); err != nil {
×
2219
                        startErr = err
×
2220
                        return
×
2221
                }
×
2222

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

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

2235
                // htlcSwitch must be started before chainArb since the latter
2236
                // relies on htlcSwitch to deliver resolution message upon
2237
                // start.
UNCOV
2238
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2239
                if err := s.htlcSwitch.Start(); err != nil {
×
2240
                        startErr = err
×
2241
                        return
×
2242
                }
×
2243

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

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

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

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

UNCOV
2268
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2269
                if err := s.chanRouter.Start(); err != nil {
×
2270
                        startErr = err
×
2271
                        return
×
2272
                }
×
2273
                // The authGossiper depends on the chanRouter and therefore
2274
                // should be started after it.
UNCOV
2275
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2276
                if err := s.authGossiper.Start(); err != nil {
×
2277
                        startErr = err
×
2278
                        return
×
2279
                }
×
2280

UNCOV
2281
                cleanup = cleanup.add(s.invoices.Stop)
×
UNCOV
2282
                if err := s.invoices.Start(); err != nil {
×
2283
                        startErr = err
×
2284
                        return
×
2285
                }
×
2286

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

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

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

UNCOV
2305
                cleanup.add(func() error {
×
2306
                        s.missionController.StopStoreTickers()
×
2307
                        return nil
×
2308
                })
×
UNCOV
2309
                s.missionController.RunStoreTickers()
×
UNCOV
2310

×
UNCOV
2311
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2312
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2313
                // that have all the information we need to handle channel
×
UNCOV
2314
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2315
                chanRestorer := &chanDBRestorer{
×
UNCOV
2316
                        db:         s.chanStateDB,
×
UNCOV
2317
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2318
                        chainArb:   s.chainArb,
×
UNCOV
2319
                }
×
UNCOV
2320
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2321
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2322
                                s.chansToRestore.PackedSingleChanBackups,
×
2323
                                s.cc.KeyRing, chanRestorer, s,
×
2324
                        )
×
2325
                        if err != nil {
×
2326
                                startErr = fmt.Errorf("unable to unpack single "+
×
2327
                                        "backups: %v", err)
×
2328
                                return
×
2329
                        }
×
2330
                }
UNCOV
2331
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2332
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2333
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2334
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2335
                        )
×
UNCOV
2336
                        if err != nil {
×
2337
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2338
                                        "backup: %v", err)
×
2339
                                return
×
2340
                        }
×
2341
                }
2342

2343
                // chanSubSwapper must be started after the `channelNotifier`
2344
                // because it depends on channel events as a synchronization
2345
                // point.
UNCOV
2346
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2347
                if err := s.chanSubSwapper.Start(); err != nil {
×
2348
                        startErr = err
×
2349
                        return
×
2350
                }
×
2351

UNCOV
2352
                if s.torController != nil {
×
2353
                        cleanup = cleanup.add(s.torController.Stop)
×
2354
                        if err := s.createNewHiddenService(); err != nil {
×
2355
                                startErr = err
×
2356
                                return
×
2357
                        }
×
2358
                }
2359

UNCOV
2360
                if s.natTraversal != nil {
×
2361
                        s.wg.Add(1)
×
2362
                        go s.watchExternalIP()
×
2363
                }
×
2364

2365
                // Start connmgr last to prevent connections before init.
UNCOV
2366
                cleanup = cleanup.add(func() error {
×
2367
                        s.connMgr.Stop()
×
2368
                        return nil
×
2369
                })
×
UNCOV
2370
                s.connMgr.Start()
×
UNCOV
2371

×
UNCOV
2372
                // If peers are specified as a config option, we'll add those
×
UNCOV
2373
                // peers first.
×
UNCOV
2374
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2375
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2376
                                peerAddrCfg,
×
UNCOV
2377
                        )
×
UNCOV
2378
                        if err != nil {
×
2379
                                startErr = fmt.Errorf("unable to parse peer "+
×
2380
                                        "pubkey from config: %v", err)
×
2381
                                return
×
2382
                        }
×
UNCOV
2383
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2384
                        if err != nil {
×
2385
                                startErr = fmt.Errorf("unable to parse peer "+
×
2386
                                        "address provided as a config option: "+
×
2387
                                        "%v", err)
×
2388
                                return
×
2389
                        }
×
2390

UNCOV
2391
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2392
                                IdentityKey: parsedPubkey,
×
UNCOV
2393
                                Address:     addr,
×
UNCOV
2394
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2395
                        }
×
UNCOV
2396

×
UNCOV
2397
                        err = s.ConnectToPeer(
×
UNCOV
2398
                                peerAddr, true,
×
UNCOV
2399
                                s.cfg.ConnectionTimeout,
×
UNCOV
2400
                        )
×
UNCOV
2401
                        if err != nil {
×
2402
                                startErr = fmt.Errorf("unable to connect to "+
×
2403
                                        "peer address provided as a config "+
×
2404
                                        "option: %v", err)
×
2405
                                return
×
2406
                        }
×
2407
                }
2408

2409
                // Subscribe to NodeAnnouncements that advertise new addresses
2410
                // our persistent peers.
UNCOV
2411
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2412
                        startErr = err
×
2413
                        return
×
2414
                }
×
2415

2416
                // With all the relevant sub-systems started, we'll now attempt
2417
                // to establish persistent connections to our direct channel
2418
                // collaborators within the network. Before doing so however,
2419
                // we'll prune our set of link nodes found within the database
2420
                // to ensure we don't reconnect to any nodes we no longer have
2421
                // open channels with.
UNCOV
2422
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2423
                        startErr = err
×
2424
                        return
×
2425
                }
×
UNCOV
2426
                if err := s.establishPersistentConnections(); err != nil {
×
2427
                        startErr = err
×
2428
                        return
×
2429
                }
×
2430

2431
                // setSeedList is a helper function that turns multiple DNS seed
2432
                // server tuples from the command line or config file into the
2433
                // data structure we need and does a basic formal sanity check
2434
                // in the process.
UNCOV
2435
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2436
                        if len(tuples) == 0 {
×
2437
                                return
×
2438
                        }
×
2439

2440
                        result := make([][2]string, len(tuples))
×
2441
                        for idx, tuple := range tuples {
×
2442
                                tuple = strings.TrimSpace(tuple)
×
2443
                                if len(tuple) == 0 {
×
2444
                                        return
×
2445
                                }
×
2446

2447
                                servers := strings.Split(tuple, ",")
×
2448
                                if len(servers) > 2 || len(servers) == 0 {
×
2449
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2450
                                                "seed tuple: %v", servers)
×
2451
                                        return
×
2452
                                }
×
2453

2454
                                copy(result[idx][:], servers)
×
2455
                        }
2456

2457
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2458
                }
2459

2460
                // Let users overwrite the DNS seed nodes. We only allow them
2461
                // for bitcoin mainnet/testnet/signet.
UNCOV
2462
                if s.cfg.Bitcoin.MainNet {
×
2463
                        setSeedList(
×
2464
                                s.cfg.Bitcoin.DNSSeeds,
×
2465
                                chainreg.BitcoinMainnetGenesis,
×
2466
                        )
×
2467
                }
×
UNCOV
2468
                if s.cfg.Bitcoin.TestNet3 {
×
2469
                        setSeedList(
×
2470
                                s.cfg.Bitcoin.DNSSeeds,
×
2471
                                chainreg.BitcoinTestnetGenesis,
×
2472
                        )
×
2473
                }
×
UNCOV
2474
                if s.cfg.Bitcoin.SigNet {
×
2475
                        setSeedList(
×
2476
                                s.cfg.Bitcoin.DNSSeeds,
×
2477
                                chainreg.BitcoinSignetGenesis,
×
2478
                        )
×
2479
                }
×
2480

2481
                // If network bootstrapping hasn't been disabled, then we'll
2482
                // configure the set of active bootstrappers, and launch a
2483
                // dedicated goroutine to maintain a set of persistent
2484
                // connections.
UNCOV
2485
                if shouldPeerBootstrap(s.cfg) {
×
2486
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2487
                        if err != nil {
×
2488
                                startErr = err
×
2489
                                return
×
2490
                        }
×
2491

2492
                        s.wg.Add(1)
×
2493
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
UNCOV
2494
                } else {
×
UNCOV
2495
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2496
                }
×
2497

2498
                // Set the active flag now that we've completed the full
2499
                // startup.
UNCOV
2500
                atomic.StoreInt32(&s.active, 1)
×
2501
        })
2502

UNCOV
2503
        if startErr != nil {
×
2504
                cleanup.run()
×
2505
        }
×
UNCOV
2506
        return startErr
×
2507
}
2508

2509
// Stop gracefully shutsdown the main daemon server. This function will signal
2510
// any active goroutines, or helper objects to exit, then blocks until they've
2511
// all successfully exited. Additionally, any/all listeners are closed.
2512
// NOTE: This function is safe for concurrent access.
UNCOV
2513
func (s *server) Stop() error {
×
UNCOV
2514
        s.stop.Do(func() {
×
UNCOV
2515
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2516

×
UNCOV
2517
                close(s.quit)
×
UNCOV
2518

×
UNCOV
2519
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2520
                s.connMgr.Stop()
×
UNCOV
2521

×
UNCOV
2522
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2523
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2524
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2525
                }
×
UNCOV
2526
                if err := s.htlcSwitch.Stop(); err != nil {
×
2527
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2528
                }
×
UNCOV
2529
                if err := s.sphinx.Stop(); err != nil {
×
2530
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2531
                }
×
UNCOV
2532
                if err := s.invoices.Stop(); err != nil {
×
2533
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2534
                }
×
UNCOV
2535
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2536
                        srvrLog.Warnf("failed to stop interceptable "+
×
2537
                                "switch: %v", err)
×
2538
                }
×
UNCOV
2539
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2540
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2541
                                "modifier: %v", err)
×
2542
                }
×
UNCOV
2543
                if err := s.chanRouter.Stop(); err != nil {
×
2544
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2545
                }
×
UNCOV
2546
                if err := s.graphBuilder.Stop(); err != nil {
×
2547
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2548
                }
×
UNCOV
2549
                if err := s.chainArb.Stop(); err != nil {
×
2550
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2551
                }
×
UNCOV
2552
                if err := s.fundingMgr.Stop(); err != nil {
×
2553
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2554
                }
×
UNCOV
2555
                if err := s.breachArbitrator.Stop(); err != nil {
×
2556
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2557
                                err)
×
2558
                }
×
UNCOV
2559
                if err := s.utxoNursery.Stop(); err != nil {
×
2560
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2561
                }
×
UNCOV
2562
                if err := s.authGossiper.Stop(); err != nil {
×
2563
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2564
                }
×
UNCOV
2565
                if err := s.sweeper.Stop(); err != nil {
×
2566
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2567
                }
×
UNCOV
2568
                if err := s.txPublisher.Stop(); err != nil {
×
2569
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2570
                }
×
UNCOV
2571
                if err := s.channelNotifier.Stop(); err != nil {
×
2572
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2573
                }
×
UNCOV
2574
                if err := s.peerNotifier.Stop(); err != nil {
×
2575
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2576
                }
×
UNCOV
2577
                if err := s.htlcNotifier.Stop(); err != nil {
×
2578
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2579
                }
×
2580

2581
                // Update channel.backup file. Make sure to do it before
2582
                // stopping chanSubSwapper.
UNCOV
2583
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2584
                        s.chanStateDB, s.addrSource,
×
UNCOV
2585
                )
×
UNCOV
2586
                if err != nil {
×
2587
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2588
                                err)
×
UNCOV
2589
                } else {
×
UNCOV
2590
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2591
                        if err != nil {
×
UNCOV
2592
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2593
                                        "backup failed: %v", err)
×
UNCOV
2594
                        }
×
2595
                }
2596

UNCOV
2597
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2598
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2599
                }
×
UNCOV
2600
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2601
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2602
                }
×
UNCOV
2603
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2604
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2605
                                err)
×
2606
                }
×
UNCOV
2607
                if err := s.chanEventStore.Stop(); err != nil {
×
2608
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2609
                                err)
×
2610
                }
×
UNCOV
2611
                s.missionController.StopStoreTickers()
×
UNCOV
2612

×
UNCOV
2613
                // Disconnect from each active peers to ensure that
×
UNCOV
2614
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2615
                for _, peer := range s.Peers() {
×
UNCOV
2616
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2617
                        if err != nil {
×
2618
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2619
                                        "received error: %v", peer.IdentityKey(),
×
2620
                                        err,
×
2621
                                )
×
2622
                        }
×
2623
                }
2624

2625
                // Now that all connections have been torn down, stop the tower
2626
                // client which will reliably flush all queued states to the
2627
                // tower. If this is halted for any reason, the force quit timer
2628
                // will kick in and abort to allow this method to return.
UNCOV
2629
                if s.towerClientMgr != nil {
×
UNCOV
2630
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2631
                                srvrLog.Warnf("Unable to shut down tower "+
×
2632
                                        "client manager: %v", err)
×
2633
                        }
×
2634
                }
2635

UNCOV
2636
                if s.hostAnn != nil {
×
2637
                        if err := s.hostAnn.Stop(); err != nil {
×
2638
                                srvrLog.Warnf("unable to shut down host "+
×
2639
                                        "annoucner: %v", err)
×
2640
                        }
×
2641
                }
2642

UNCOV
2643
                if s.livenessMonitor != nil {
×
UNCOV
2644
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2645
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2646
                                        "monitor: %v", err)
×
2647
                        }
×
2648
                }
2649

2650
                // Wait for all lingering goroutines to quit.
UNCOV
2651
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2652
                s.wg.Wait()
×
UNCOV
2653

×
UNCOV
2654
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2655
                s.sigPool.Stop()
×
UNCOV
2656
                s.writePool.Stop()
×
UNCOV
2657
                s.readPool.Stop()
×
2658
        })
2659

UNCOV
2660
        return nil
×
2661
}
2662

2663
// Stopped returns true if the server has been instructed to shutdown.
2664
// NOTE: This function is safe for concurrent access.
UNCOV
2665
func (s *server) Stopped() bool {
×
UNCOV
2666
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2667
}
×
2668

2669
// configurePortForwarding attempts to set up port forwarding for the different
2670
// ports that the server will be listening on.
2671
//
2672
// NOTE: This should only be used when using some kind of NAT traversal to
2673
// automatically set up forwarding rules.
2674
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2675
        ip, err := s.natTraversal.ExternalIP()
×
2676
        if err != nil {
×
2677
                return nil, err
×
2678
        }
×
2679
        s.lastDetectedIP = ip
×
2680

×
2681
        externalIPs := make([]string, 0, len(ports))
×
2682
        for _, port := range ports {
×
2683
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2684
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2685
                        continue
×
2686
                }
2687

2688
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2689
                externalIPs = append(externalIPs, hostIP)
×
2690
        }
2691

2692
        return externalIPs, nil
×
2693
}
2694

2695
// removePortForwarding attempts to clear the forwarding rules for the different
2696
// ports the server is currently listening on.
2697
//
2698
// NOTE: This should only be used when using some kind of NAT traversal to
2699
// automatically set up forwarding rules.
2700
func (s *server) removePortForwarding() {
×
2701
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2702
        for _, port := range forwardedPorts {
×
2703
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2704
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2705
                                "port %d: %v", port, err)
×
2706
                }
×
2707
        }
2708
}
2709

2710
// watchExternalIP continuously checks for an updated external IP address every
2711
// 15 minutes. Once a new IP address has been detected, it will automatically
2712
// handle port forwarding rules and send updated node announcements to the
2713
// currently connected peers.
2714
//
2715
// NOTE: This MUST be run as a goroutine.
2716
func (s *server) watchExternalIP() {
×
2717
        defer s.wg.Done()
×
2718

×
2719
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2720
        // up by the server.
×
2721
        defer s.removePortForwarding()
×
2722

×
2723
        // Keep track of the external IPs set by the user to avoid replacing
×
2724
        // them when detecting a new IP.
×
2725
        ipsSetByUser := make(map[string]struct{})
×
2726
        for _, ip := range s.cfg.ExternalIPs {
×
2727
                ipsSetByUser[ip.String()] = struct{}{}
×
2728
        }
×
2729

2730
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2731

×
2732
        ticker := time.NewTicker(15 * time.Minute)
×
2733
        defer ticker.Stop()
×
2734
out:
×
2735
        for {
×
2736
                select {
×
2737
                case <-ticker.C:
×
2738
                        // We'll start off by making sure a new IP address has
×
2739
                        // been detected.
×
2740
                        ip, err := s.natTraversal.ExternalIP()
×
2741
                        if err != nil {
×
2742
                                srvrLog.Debugf("Unable to retrieve the "+
×
2743
                                        "external IP address: %v", err)
×
2744
                                continue
×
2745
                        }
2746

2747
                        // Periodically renew the NAT port forwarding.
2748
                        for _, port := range forwardedPorts {
×
2749
                                err := s.natTraversal.AddPortMapping(port)
×
2750
                                if err != nil {
×
2751
                                        srvrLog.Warnf("Unable to automatically "+
×
2752
                                                "re-create port forwarding using %s: %v",
×
2753
                                                s.natTraversal.Name(), err)
×
2754
                                } else {
×
2755
                                        srvrLog.Debugf("Automatically re-created "+
×
2756
                                                "forwarding for port %d using %s to "+
×
2757
                                                "advertise external IP",
×
2758
                                                port, s.natTraversal.Name())
×
2759
                                }
×
2760
                        }
2761

2762
                        if ip.Equal(s.lastDetectedIP) {
×
2763
                                continue
×
2764
                        }
2765

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

×
2768
                        // Next, we'll craft the new addresses that will be
×
2769
                        // included in the new node announcement and advertised
×
2770
                        // to the network. Each address will consist of the new
×
2771
                        // IP detected and one of the currently advertised
×
2772
                        // ports.
×
2773
                        var newAddrs []net.Addr
×
2774
                        for _, port := range forwardedPorts {
×
2775
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2776
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2777
                                if err != nil {
×
2778
                                        srvrLog.Debugf("Unable to resolve "+
×
2779
                                                "host %v: %v", addr, err)
×
2780
                                        continue
×
2781
                                }
2782

2783
                                newAddrs = append(newAddrs, addr)
×
2784
                        }
2785

2786
                        // Skip the update if we weren't able to resolve any of
2787
                        // the new addresses.
2788
                        if len(newAddrs) == 0 {
×
2789
                                srvrLog.Debug("Skipping node announcement " +
×
2790
                                        "update due to not being able to " +
×
2791
                                        "resolve any new addresses")
×
2792
                                continue
×
2793
                        }
2794

2795
                        // Now, we'll need to update the addresses in our node's
2796
                        // announcement in order to propagate the update
2797
                        // throughout the network. We'll only include addresses
2798
                        // that have a different IP from the previous one, as
2799
                        // the previous IP is no longer valid.
2800
                        currentNodeAnn := s.getNodeAnnouncement()
×
2801

×
2802
                        for _, addr := range currentNodeAnn.Addresses {
×
2803
                                host, _, err := net.SplitHostPort(addr.String())
×
2804
                                if err != nil {
×
2805
                                        srvrLog.Debugf("Unable to determine "+
×
2806
                                                "host from address %v: %v",
×
2807
                                                addr, err)
×
2808
                                        continue
×
2809
                                }
2810

2811
                                // We'll also make sure to include external IPs
2812
                                // set manually by the user.
2813
                                _, setByUser := ipsSetByUser[addr.String()]
×
2814
                                if setByUser || host != s.lastDetectedIP.String() {
×
2815
                                        newAddrs = append(newAddrs, addr)
×
2816
                                }
×
2817
                        }
2818

2819
                        // Then, we'll generate a new timestamped node
2820
                        // announcement with the updated addresses and broadcast
2821
                        // it to our peers.
2822
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2823
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2824
                        )
×
2825
                        if err != nil {
×
2826
                                srvrLog.Debugf("Unable to generate new node "+
×
2827
                                        "announcement: %v", err)
×
2828
                                continue
×
2829
                        }
2830

2831
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2832
                        if err != nil {
×
2833
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2834
                                        "announcement to peers: %v", err)
×
2835
                                continue
×
2836
                        }
2837

2838
                        // Finally, update the last IP seen to the current one.
2839
                        s.lastDetectedIP = ip
×
2840
                case <-s.quit:
×
2841
                        break out
×
2842
                }
2843
        }
2844
}
2845

2846
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2847
// based on the server, and currently active bootstrap mechanisms as defined
2848
// within the current configuration.
2849
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2850
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2851

×
2852
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2853

×
2854
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2855
        // this can be used by default if we've already partially seeded the
×
2856
        // network.
×
2857
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2858
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2859
        if err != nil {
×
2860
                return nil, err
×
2861
        }
×
2862
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2863

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

×
2869
                // If we have a set of DNS seeds for this chain, then we'll add
×
2870
                // it as an additional bootstrapping source.
×
2871
                if ok {
×
2872
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2873
                                "seeds: %v", dnsSeeds)
×
2874

×
2875
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2876
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2877
                        )
×
2878
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2879
                }
×
2880
        }
2881

2882
        return bootStrappers, nil
×
2883
}
2884

2885
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2886
// needs to ignore, which is made of three parts,
2887
//   - the node itself needs to be skipped as it doesn't make sense to connect
2888
//     to itself.
2889
//   - the peers that already have connections with, as in s.peersByPub.
2890
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2891
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2892
        s.mu.RLock()
×
2893
        defer s.mu.RUnlock()
×
2894

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

×
2897
        // We should ignore ourselves from bootstrapping.
×
2898
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2899
        ignore[selfKey] = struct{}{}
×
2900

×
2901
        // Ignore all connected peers.
×
2902
        for _, peer := range s.peersByPub {
×
2903
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2904
                ignore[nID] = struct{}{}
×
2905
        }
×
2906

2907
        // Ignore all persistent peers as they have a dedicated reconnecting
2908
        // process.
2909
        for pubKeyStr := range s.persistentPeers {
×
2910
                var nID autopilot.NodeID
×
2911
                copy(nID[:], []byte(pubKeyStr))
×
2912
                ignore[nID] = struct{}{}
×
2913
        }
×
2914

2915
        return ignore
×
2916
}
2917

2918
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2919
// and maintain a target minimum number of outbound connections. With this
2920
// invariant, we ensure that our node is connected to a diverse set of peers
2921
// and that nodes newly joining the network receive an up to date network view
2922
// as soon as possible.
2923
func (s *server) peerBootstrapper(numTargetPeers uint32,
2924
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2925

×
2926
        defer s.wg.Done()
×
2927

×
2928
        // Before we continue, init the ignore peers map.
×
2929
        ignoreList := s.createBootstrapIgnorePeers()
×
2930

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

×
2935
        // Once done, we'll attempt to maintain our target minimum number of
×
2936
        // peers.
×
2937
        //
×
2938
        // We'll use a 15 second backoff, and double the time every time an
×
2939
        // epoch fails up to a ceiling.
×
2940
        backOff := time.Second * 15
×
2941

×
2942
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2943
        // see if we've reached our minimum number of peers.
×
2944
        sampleTicker := time.NewTicker(backOff)
×
2945
        defer sampleTicker.Stop()
×
2946

×
2947
        // We'll use the number of attempts and errors to determine if we need
×
2948
        // to increase the time between discovery epochs.
×
2949
        var epochErrors uint32 // To be used atomically.
×
2950
        var epochAttempts uint32
×
2951

×
2952
        for {
×
2953
                select {
×
2954
                // The ticker has just woken us up, so we'll need to check if
2955
                // we need to attempt to connect our to any more peers.
2956
                case <-sampleTicker.C:
×
2957
                        // Obtain the current number of peers, so we can gauge
×
2958
                        // if we need to sample more peers or not.
×
2959
                        s.mu.RLock()
×
2960
                        numActivePeers := uint32(len(s.peersByPub))
×
2961
                        s.mu.RUnlock()
×
2962

×
2963
                        // If we have enough peers, then we can loop back
×
2964
                        // around to the next round as we're done here.
×
2965
                        if numActivePeers >= numTargetPeers {
×
2966
                                continue
×
2967
                        }
2968

2969
                        // If all of our attempts failed during this last back
2970
                        // off period, then will increase our backoff to 5
2971
                        // minute ceiling to avoid an excessive number of
2972
                        // queries
2973
                        //
2974
                        // TODO(roasbeef): add reverse policy too?
2975

2976
                        if epochAttempts > 0 &&
×
2977
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2978

×
2979
                                sampleTicker.Stop()
×
2980

×
2981
                                backOff *= 2
×
2982
                                if backOff > bootstrapBackOffCeiling {
×
2983
                                        backOff = bootstrapBackOffCeiling
×
2984
                                }
×
2985

2986
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2987
                                        "%v", backOff)
×
2988
                                sampleTicker = time.NewTicker(backOff)
×
2989
                                continue
×
2990
                        }
2991

2992
                        atomic.StoreUint32(&epochErrors, 0)
×
2993
                        epochAttempts = 0
×
2994

×
2995
                        // Since we know need more peers, we'll compute the
×
2996
                        // exact number we need to reach our threshold.
×
2997
                        numNeeded := numTargetPeers - numActivePeers
×
2998

×
2999
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3000
                                "peers", numNeeded)
×
3001

×
3002
                        // With the number of peers we need calculated, we'll
×
3003
                        // query the network bootstrappers to sample a set of
×
3004
                        // random addrs for us.
×
3005
                        //
×
3006
                        // Before we continue, get a copy of the ignore peers
×
3007
                        // map.
×
3008
                        ignoreList = s.createBootstrapIgnorePeers()
×
3009

×
3010
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3011
                                ignoreList, numNeeded*2, bootstrappers...,
×
3012
                        )
×
3013
                        if err != nil {
×
3014
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3015
                                        "peers: %v", err)
×
3016
                                continue
×
3017
                        }
3018

3019
                        // Finally, we'll launch a new goroutine for each
3020
                        // prospective peer candidates.
3021
                        for _, addr := range peerAddrs {
×
3022
                                epochAttempts++
×
3023

×
3024
                                go func(a *lnwire.NetAddress) {
×
3025
                                        // TODO(roasbeef): can do AS, subnet,
×
3026
                                        // country diversity, etc
×
3027
                                        errChan := make(chan error, 1)
×
3028
                                        s.connectToPeer(
×
3029
                                                a, errChan,
×
3030
                                                s.cfg.ConnectionTimeout,
×
3031
                                        )
×
3032
                                        select {
×
3033
                                        case err := <-errChan:
×
3034
                                                if err == nil {
×
3035
                                                        return
×
3036
                                                }
×
3037

3038
                                                srvrLog.Errorf("Unable to "+
×
3039
                                                        "connect to %v: %v",
×
3040
                                                        a, err)
×
3041
                                                atomic.AddUint32(&epochErrors, 1)
×
3042
                                        case <-s.quit:
×
3043
                                        }
3044
                                }(addr)
3045
                        }
3046
                case <-s.quit:
×
3047
                        return
×
3048
                }
3049
        }
3050
}
3051

3052
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3053
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3054
// query back off each time we encounter a failure.
3055
const bootstrapBackOffCeiling = time.Minute * 5
3056

3057
// initialPeerBootstrap attempts to continuously connect to peers on startup
3058
// until the target number of peers has been reached. This ensures that nodes
3059
// receive an up to date network view as soon as possible.
3060
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3061
        numTargetPeers uint32,
3062
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3063

×
3064
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3065
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3066

×
3067
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3068
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3069
        var delaySignal <-chan time.Time
×
3070
        delayTime := time.Second * 2
×
3071

×
3072
        // As want to be more aggressive, we'll use a lower back off celling
×
3073
        // then the main peer bootstrap logic.
×
3074
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3075

×
3076
        for attempts := 0; ; attempts++ {
×
3077
                // Check if the server has been requested to shut down in order
×
3078
                // to prevent blocking.
×
3079
                if s.Stopped() {
×
3080
                        return
×
3081
                }
×
3082

3083
                // We can exit our aggressive initial peer bootstrapping stage
3084
                // if we've reached out target number of peers.
3085
                s.mu.RLock()
×
3086
                numActivePeers := uint32(len(s.peersByPub))
×
3087
                s.mu.RUnlock()
×
3088

×
3089
                if numActivePeers >= numTargetPeers {
×
3090
                        return
×
3091
                }
×
3092

3093
                if attempts > 0 {
×
3094
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3095
                                "bootstrap peers (attempt #%v)", delayTime,
×
3096
                                attempts)
×
3097

×
3098
                        // We've completed at least one iterating and haven't
×
3099
                        // finished, so we'll start to insert a delay period
×
3100
                        // between each attempt.
×
3101
                        delaySignal = time.After(delayTime)
×
3102
                        select {
×
3103
                        case <-delaySignal:
×
3104
                        case <-s.quit:
×
3105
                                return
×
3106
                        }
3107

3108
                        // After our delay, we'll double the time we wait up to
3109
                        // the max back off period.
3110
                        delayTime *= 2
×
3111
                        if delayTime > backOffCeiling {
×
3112
                                delayTime = backOffCeiling
×
3113
                        }
×
3114
                }
3115

3116
                // Otherwise, we'll request for the remaining number of peers
3117
                // in order to reach our target.
3118
                peersNeeded := numTargetPeers - numActivePeers
×
3119
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3120
                        ignore, peersNeeded, bootstrappers...,
×
3121
                )
×
3122
                if err != nil {
×
3123
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3124
                                "peers: %v", err)
×
3125
                        continue
×
3126
                }
3127

3128
                // Then, we'll attempt to establish a connection to the
3129
                // different peer addresses retrieved by our bootstrappers.
3130
                var wg sync.WaitGroup
×
3131
                for _, bootstrapAddr := range bootstrapAddrs {
×
3132
                        wg.Add(1)
×
3133
                        go func(addr *lnwire.NetAddress) {
×
3134
                                defer wg.Done()
×
3135

×
3136
                                errChan := make(chan error, 1)
×
3137
                                go s.connectToPeer(
×
3138
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3139
                                )
×
3140

×
3141
                                // We'll only allow this connection attempt to
×
3142
                                // take up to 3 seconds. This allows us to move
×
3143
                                // quickly by discarding peers that are slowing
×
3144
                                // us down.
×
3145
                                select {
×
3146
                                case err := <-errChan:
×
3147
                                        if err == nil {
×
3148
                                                return
×
3149
                                        }
×
3150
                                        srvrLog.Errorf("Unable to connect to "+
×
3151
                                                "%v: %v", addr, err)
×
3152
                                // TODO: tune timeout? 3 seconds might be *too*
3153
                                // aggressive but works well.
3154
                                case <-time.After(3 * time.Second):
×
3155
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3156
                                                "to not establishing a "+
×
3157
                                                "connection within 3 seconds",
×
3158
                                                addr)
×
3159
                                case <-s.quit:
×
3160
                                }
3161
                        }(bootstrapAddr)
3162
                }
3163

3164
                wg.Wait()
×
3165
        }
3166
}
3167

3168
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3169
// order to listen for inbound connections over Tor.
3170
func (s *server) createNewHiddenService() error {
×
3171
        // Determine the different ports the server is listening on. The onion
×
3172
        // service's virtual port will map to these ports and one will be picked
×
3173
        // at random when the onion service is being accessed.
×
3174
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3175
        for _, listenAddr := range s.listenAddrs {
×
3176
                port := listenAddr.(*net.TCPAddr).Port
×
3177
                listenPorts = append(listenPorts, port)
×
3178
        }
×
3179

3180
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3181
        if err != nil {
×
3182
                return err
×
3183
        }
×
3184

3185
        // Once the port mapping has been set, we can go ahead and automatically
3186
        // create our onion service. The service's private key will be saved to
3187
        // disk in order to regain access to this service when restarting `lnd`.
3188
        onionCfg := tor.AddOnionConfig{
×
3189
                VirtualPort: defaultPeerPort,
×
3190
                TargetPorts: listenPorts,
×
3191
                Store: tor.NewOnionFile(
×
3192
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3193
                        encrypter,
×
3194
                ),
×
3195
        }
×
3196

×
3197
        switch {
×
3198
        case s.cfg.Tor.V2:
×
3199
                onionCfg.Type = tor.V2
×
3200
        case s.cfg.Tor.V3:
×
3201
                onionCfg.Type = tor.V3
×
3202
        }
3203

3204
        addr, err := s.torController.AddOnion(onionCfg)
×
3205
        if err != nil {
×
3206
                return err
×
3207
        }
×
3208

3209
        // Now that the onion service has been created, we'll add the onion
3210
        // address it can be reached at to our list of advertised addresses.
3211
        newNodeAnn, err := s.genNodeAnnouncement(
×
3212
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3213
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3214
                },
×
3215
        )
3216
        if err != nil {
×
3217
                return fmt.Errorf("unable to generate new node "+
×
3218
                        "announcement: %v", err)
×
3219
        }
×
3220

3221
        // Finally, we'll update the on-disk version of our announcement so it
3222
        // will eventually propagate to nodes in the network.
3223
        selfNode := &models.LightningNode{
×
3224
                HaveNodeAnnouncement: true,
×
3225
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3226
                Addresses:            newNodeAnn.Addresses,
×
3227
                Alias:                newNodeAnn.Alias.String(),
×
3228
                Features: lnwire.NewFeatureVector(
×
3229
                        newNodeAnn.Features, lnwire.Features,
×
3230
                ),
×
3231
                Color:        newNodeAnn.RGBColor,
×
3232
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3233
        }
×
3234
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3235
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3236
                return fmt.Errorf("can't set self node: %w", err)
×
3237
        }
×
3238

3239
        return nil
×
3240
}
3241

3242
// findChannel finds a channel given a public key and ChannelID. It is an
3243
// optimization that is quicker than seeking for a channel given only the
3244
// ChannelID.
3245
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3246
        *channeldb.OpenChannel, error) {
×
UNCOV
3247

×
UNCOV
3248
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3249
        if err != nil {
×
3250
                return nil, err
×
3251
        }
×
3252

UNCOV
3253
        for _, channel := range nodeChans {
×
UNCOV
3254
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3255
                        return channel, nil
×
UNCOV
3256
                }
×
3257
        }
3258

UNCOV
3259
        return nil, fmt.Errorf("unable to find channel")
×
3260
}
3261

3262
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3263
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3264
        s.mu.Lock()
×
UNCOV
3265
        defer s.mu.Unlock()
×
UNCOV
3266

×
UNCOV
3267
        return *s.currentNodeAnn
×
UNCOV
3268
}
×
3269

3270
// genNodeAnnouncement generates and returns the current fully signed node
3271
// announcement. The time stamp of the announcement will be updated in order
3272
// to ensure it propagates through the network.
3273
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3274
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3275

×
UNCOV
3276
        s.mu.Lock()
×
UNCOV
3277
        defer s.mu.Unlock()
×
UNCOV
3278

×
UNCOV
3279
        // First, try to update our feature manager with the updated set of
×
UNCOV
3280
        // features.
×
UNCOV
3281
        if features != nil {
×
UNCOV
3282
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3283
                        feature.SetNodeAnn: features,
×
UNCOV
3284
                }
×
UNCOV
3285
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3286
                if err != nil {
×
UNCOV
3287
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3288
                }
×
3289

3290
                // If we could successfully update our feature manager, add
3291
                // an update modifier to include these new features to our
3292
                // set.
UNCOV
3293
                modifiers = append(
×
UNCOV
3294
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3295
                )
×
3296
        }
3297

3298
        // Always update the timestamp when refreshing to ensure the update
3299
        // propagates.
UNCOV
3300
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3301

×
UNCOV
3302
        // Apply the requested changes to the node announcement.
×
UNCOV
3303
        for _, modifier := range modifiers {
×
UNCOV
3304
                modifier(s.currentNodeAnn)
×
UNCOV
3305
        }
×
3306

3307
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3308
        err := netann.SignNodeAnnouncement(
×
UNCOV
3309
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
UNCOV
3310
        )
×
UNCOV
3311
        if err != nil {
×
3312
                return lnwire.NodeAnnouncement{}, err
×
3313
        }
×
3314

UNCOV
3315
        return *s.currentNodeAnn, nil
×
3316
}
3317

3318
// updateAndBroadcastSelfNode generates a new node announcement
3319
// applying the giving modifiers and updating the time stamp
3320
// to ensure it propagates through the network. Then it broadcasts
3321
// it to the network.
3322
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
UNCOV
3323
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3324

×
UNCOV
3325
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3326
        if err != nil {
×
UNCOV
3327
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3328
                        "announcement: %v", err)
×
UNCOV
3329
        }
×
3330

3331
        // Update the on-disk version of our announcement.
3332
        // Load and modify self node istead of creating anew instance so we
3333
        // don't risk overwriting any existing values.
UNCOV
3334
        selfNode, err := s.graphDB.SourceNode()
×
UNCOV
3335
        if err != nil {
×
3336
                return fmt.Errorf("unable to get current source node: %w", err)
×
3337
        }
×
3338

UNCOV
3339
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3340
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3341
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3342
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3343
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3344
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3345
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3346

×
UNCOV
3347
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
3348

×
UNCOV
3349
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3350
                return fmt.Errorf("can't set self node: %w", err)
×
3351
        }
×
3352

3353
        // Finally, propagate it to the nodes in the network.
UNCOV
3354
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3355
        if err != nil {
×
3356
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3357
                        "announcement to peers: %v", err)
×
3358
                return err
×
3359
        }
×
3360

UNCOV
3361
        return nil
×
3362
}
3363

3364
type nodeAddresses struct {
3365
        pubKey    *btcec.PublicKey
3366
        addresses []net.Addr
3367
}
3368

3369
// establishPersistentConnections attempts to establish persistent connections
3370
// to all our direct channel collaborators. In order to promote liveness of our
3371
// active channels, we instruct the connection manager to attempt to establish
3372
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3373
func (s *server) establishPersistentConnections() error {
×
UNCOV
3374
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3375
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3376
        // since other PubKey forms can't be compared.
×
UNCOV
3377
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3378

×
UNCOV
3379
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3380
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3381
        // the reconnection port to the default peer port.
×
UNCOV
3382
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3383
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3384
                return err
×
3385
        }
×
UNCOV
3386
        for _, node := range linkNodes {
×
UNCOV
3387
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3388
                nodeAddrs := &nodeAddresses{
×
UNCOV
3389
                        pubKey:    node.IdentityPub,
×
UNCOV
3390
                        addresses: node.Addresses,
×
UNCOV
3391
                }
×
UNCOV
3392
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3393
        }
×
3394

3395
        // After checking our previous connections for addresses to connect to,
3396
        // iterate through the nodes in our channel graph to find addresses
3397
        // that have been added via NodeAnnouncement messages.
UNCOV
3398
        sourceNode, err := s.graphDB.SourceNode()
×
UNCOV
3399
        if err != nil {
×
3400
                return err
×
3401
        }
×
3402

3403
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3404
        // each of the nodes.
UNCOV
3405
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
3406
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
×
UNCOV
3407
                tx kvdb.RTx,
×
UNCOV
3408
                chanInfo *models.ChannelEdgeInfo,
×
UNCOV
3409
                policy, _ *models.ChannelEdgePolicy) error {
×
UNCOV
3410

×
UNCOV
3411
                // If the remote party has announced the channel to us, but we
×
UNCOV
3412
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3413
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3414
                if policy == nil {
×
3415
                        srvrLog.Warnf("No channel policy found for "+
×
3416
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3417
                }
×
3418

3419
                // We'll now fetch the peer opposite from us within this
3420
                // channel so we can queue up a direct connection to them.
UNCOV
3421
                channelPeer, err := s.graphDB.FetchOtherNode(
×
UNCOV
3422
                        tx, chanInfo, selfPub,
×
UNCOV
3423
                )
×
UNCOV
3424
                if err != nil {
×
3425
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3426
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3427
                                err)
×
3428
                }
×
3429

UNCOV
3430
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3431

×
UNCOV
3432
                // Add all unique addresses from channel
×
UNCOV
3433
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3434
                // connect to for this peer.
×
UNCOV
3435
                addrSet := make(map[string]net.Addr)
×
UNCOV
3436
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3437
                        switch addr.(type) {
×
UNCOV
3438
                        case *net.TCPAddr:
×
UNCOV
3439
                                addrSet[addr.String()] = addr
×
3440

3441
                        // We'll only attempt to connect to Tor addresses if Tor
3442
                        // outbound support is enabled.
3443
                        case *tor.OnionAddr:
×
3444
                                if s.cfg.Tor.Active {
×
3445
                                        addrSet[addr.String()] = addr
×
3446
                                }
×
3447
                        }
3448
                }
3449

3450
                // If this peer is also recorded as a link node, we'll add any
3451
                // additional addresses that have not already been selected.
UNCOV
3452
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3453
                if ok {
×
UNCOV
3454
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3455
                                switch lnAddress.(type) {
×
UNCOV
3456
                                case *net.TCPAddr:
×
UNCOV
3457
                                        addrSet[lnAddress.String()] = lnAddress
×
3458

3459
                                // We'll only attempt to connect to Tor
3460
                                // addresses if Tor outbound support is enabled.
3461
                                case *tor.OnionAddr:
×
3462
                                        if s.cfg.Tor.Active {
×
3463
                                                addrSet[lnAddress.String()] = lnAddress
×
3464
                                        }
×
3465
                                }
3466
                        }
3467
                }
3468

3469
                // Construct a slice of the deduped addresses.
UNCOV
3470
                var addrs []net.Addr
×
UNCOV
3471
                for _, addr := range addrSet {
×
UNCOV
3472
                        addrs = append(addrs, addr)
×
UNCOV
3473
                }
×
3474

UNCOV
3475
                n := &nodeAddresses{
×
UNCOV
3476
                        addresses: addrs,
×
UNCOV
3477
                }
×
UNCOV
3478
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3479
                if err != nil {
×
3480
                        return err
×
3481
                }
×
3482

UNCOV
3483
                nodeAddrsMap[pubStr] = n
×
UNCOV
3484
                return nil
×
3485
        })
UNCOV
3486
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
×
3487
                return err
×
3488
        }
×
3489

UNCOV
3490
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3491
                len(nodeAddrsMap))
×
UNCOV
3492

×
UNCOV
3493
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3494
        // have been recorded and sent to the connection manager.
×
UNCOV
3495
        s.mu.Lock()
×
UNCOV
3496
        defer s.mu.Unlock()
×
UNCOV
3497

×
UNCOV
3498
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3499
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3500
        var numOutboundConns int
×
UNCOV
3501
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3502
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3503
                // persistent connection with. We set the value to false to
×
UNCOV
3504
                // indicate that we should not continue to reconnect if the
×
UNCOV
3505
                // number of channels returns to zero, since this peer has not
×
UNCOV
3506
                // been requested as perm by the user.
×
UNCOV
3507
                s.persistentPeers[pubStr] = false
×
UNCOV
3508
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3509
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3510
                }
×
3511

UNCOV
3512
                for _, address := range nodeAddr.addresses {
×
UNCOV
3513
                        // Create a wrapper address which couples the IP and
×
UNCOV
3514
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3515
                        // can be established.
×
UNCOV
3516
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3517
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3518
                                Address:     address,
×
UNCOV
3519
                        }
×
UNCOV
3520

×
UNCOV
3521
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3522
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3523
                }
×
3524

3525
                // We'll connect to the first 10 peers immediately, then
3526
                // randomly stagger any remaining connections if the
3527
                // stagger initial reconnect flag is set. This ensures
3528
                // that mobile nodes or nodes with a small number of
3529
                // channels obtain connectivity quickly, but larger
3530
                // nodes are able to disperse the costs of connecting to
3531
                // all peers at once.
UNCOV
3532
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3533
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3534

×
UNCOV
3535
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3536
                } else {
×
3537
                        go s.delayInitialReconnect(pubStr)
×
3538
                }
×
3539

UNCOV
3540
                numOutboundConns++
×
3541
        }
3542

UNCOV
3543
        return nil
×
3544
}
3545

3546
// delayInitialReconnect will attempt a reconnection to the given peer after
3547
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3548
//
3549
// NOTE: This method MUST be run as a goroutine.
3550
func (s *server) delayInitialReconnect(pubStr string) {
×
3551
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3552
        select {
×
3553
        case <-time.After(delay):
×
3554
                s.connectToPersistentPeer(pubStr)
×
3555
        case <-s.quit:
×
3556
        }
3557
}
3558

3559
// prunePersistentPeerConnection removes all internal state related to
3560
// persistent connections to a peer within the server. This is used to avoid
3561
// persistent connection retries to peers we do not have any open channels with.
UNCOV
3562
func (s *server) prunePersistentPeerConnection(compressedPubKey [33]byte) {
×
UNCOV
3563
        pubKeyStr := string(compressedPubKey[:])
×
UNCOV
3564

×
UNCOV
3565
        s.mu.Lock()
×
UNCOV
3566
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3567
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3568
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3569
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3570
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3571
                s.mu.Unlock()
×
UNCOV
3572

×
UNCOV
3573
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3574
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3575

×
UNCOV
3576
                return
×
UNCOV
3577
        }
×
UNCOV
3578
        s.mu.Unlock()
×
3579
}
3580

3581
// BroadcastMessage sends a request to the server to broadcast a set of
3582
// messages to all peers other than the one specified by the `skips` parameter.
3583
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3584
// the target peers.
3585
//
3586
// NOTE: This function is safe for concurrent access.
3587
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3588
        msgs ...lnwire.Message) error {
×
UNCOV
3589

×
UNCOV
3590
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3591
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3592
        // exact set of peers present at the time of invocation.
×
UNCOV
3593
        s.mu.RLock()
×
UNCOV
3594
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3595
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3596
                if skips != nil {
×
UNCOV
3597
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3598
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3599
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3600
                                continue
×
3601
                        }
3602
                }
3603

UNCOV
3604
                peers = append(peers, sPeer)
×
3605
        }
UNCOV
3606
        s.mu.RUnlock()
×
UNCOV
3607

×
UNCOV
3608
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3609
        // all messages to each of peers.
×
UNCOV
3610
        var wg sync.WaitGroup
×
UNCOV
3611
        for _, sPeer := range peers {
×
UNCOV
3612
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3613
                        sPeer.PubKey())
×
UNCOV
3614

×
UNCOV
3615
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3616
                wg.Add(1)
×
UNCOV
3617
                s.wg.Add(1)
×
UNCOV
3618
                go func(p lnpeer.Peer) {
×
UNCOV
3619
                        defer s.wg.Done()
×
UNCOV
3620
                        defer wg.Done()
×
UNCOV
3621

×
UNCOV
3622
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3623
                }(sPeer)
×
3624
        }
3625

3626
        // Wait for all messages to have been dispatched before returning to
3627
        // caller.
UNCOV
3628
        wg.Wait()
×
UNCOV
3629

×
UNCOV
3630
        return nil
×
3631
}
3632

3633
// NotifyWhenOnline can be called by other subsystems to get notified when a
3634
// particular peer comes online. The peer itself is sent across the peerChan.
3635
//
3636
// NOTE: This function is safe for concurrent access.
3637
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3638
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3639

×
UNCOV
3640
        s.mu.Lock()
×
UNCOV
3641

×
UNCOV
3642
        // Compute the target peer's identifier.
×
UNCOV
3643
        pubStr := string(peerKey[:])
×
UNCOV
3644

×
UNCOV
3645
        // Check if peer is connected.
×
UNCOV
3646
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3647
        if ok {
×
UNCOV
3648
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3649
                // waiting for the peer to become active.
×
UNCOV
3650
                s.mu.Unlock()
×
UNCOV
3651

×
UNCOV
3652
                // Wait until the peer signals that it is actually active
×
UNCOV
3653
                // rather than only in the server's maps.
×
UNCOV
3654
                select {
×
UNCOV
3655
                case <-peer.ActiveSignal():
×
3656
                case <-peer.QuitSignal():
×
3657
                        // The peer quit, so we'll add the channel to the slice
×
3658
                        // and return.
×
3659
                        s.mu.Lock()
×
3660
                        s.peerConnectedListeners[pubStr] = append(
×
3661
                                s.peerConnectedListeners[pubStr], peerChan,
×
3662
                        )
×
3663
                        s.mu.Unlock()
×
3664
                        return
×
3665
                }
3666

3667
                // Connected, can return early.
UNCOV
3668
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3669

×
UNCOV
3670
                select {
×
UNCOV
3671
                case peerChan <- peer:
×
3672
                case <-s.quit:
×
3673
                }
3674

UNCOV
3675
                return
×
3676
        }
3677

3678
        // Not connected, store this listener such that it can be notified when
3679
        // the peer comes online.
UNCOV
3680
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3681
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3682
        )
×
UNCOV
3683
        s.mu.Unlock()
×
3684
}
3685

3686
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3687
// the given public key has been disconnected. The notification is signaled by
3688
// closing the channel returned.
UNCOV
3689
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3690
        s.mu.Lock()
×
UNCOV
3691
        defer s.mu.Unlock()
×
UNCOV
3692

×
UNCOV
3693
        c := make(chan struct{})
×
UNCOV
3694

×
UNCOV
3695
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3696
        // notification.
×
UNCOV
3697
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3698
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3699
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3700
                close(c)
×
3701
                return c
×
3702
        }
×
3703

3704
        // Otherwise, the peer is online, so we'll keep track of the channel to
3705
        // trigger the notification once the server detects the peer
3706
        // disconnects.
UNCOV
3707
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3708
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3709
        )
×
UNCOV
3710

×
UNCOV
3711
        return c
×
3712
}
3713

3714
// FindPeer will return the peer that corresponds to the passed in public key.
3715
// This function is used by the funding manager, allowing it to update the
3716
// daemon's local representation of the remote peer.
3717
//
3718
// NOTE: This function is safe for concurrent access.
UNCOV
3719
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3720
        s.mu.RLock()
×
UNCOV
3721
        defer s.mu.RUnlock()
×
UNCOV
3722

×
UNCOV
3723
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3724

×
UNCOV
3725
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3726
}
×
3727

3728
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3729
// which should be a string representation of the peer's serialized, compressed
3730
// public key.
3731
//
3732
// NOTE: This function is safe for concurrent access.
UNCOV
3733
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3734
        s.mu.RLock()
×
UNCOV
3735
        defer s.mu.RUnlock()
×
UNCOV
3736

×
UNCOV
3737
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3738
}
×
3739

3740
// findPeerByPubStr is an internal method that retrieves the specified peer from
3741
// the server's internal state using.
UNCOV
3742
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3743
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3744
        if !ok {
×
UNCOV
3745
                return nil, ErrPeerNotConnected
×
UNCOV
3746
        }
×
3747

UNCOV
3748
        return peer, nil
×
3749
}
3750

3751
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3752
// exponential backoff. If no previous backoff was known, the default is
3753
// returned.
3754
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3755
        startTime time.Time) time.Duration {
×
UNCOV
3756

×
UNCOV
3757
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3758
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3759
        if !ok {
×
UNCOV
3760
                // If an existing backoff was unknown, use the default.
×
UNCOV
3761
                return s.cfg.MinBackoff
×
UNCOV
3762
        }
×
3763

3764
        // If the peer failed to start properly, we'll just use the previous
3765
        // backoff to compute the subsequent randomized exponential backoff
3766
        // duration. This will roughly double on average.
UNCOV
3767
        if startTime.IsZero() {
×
3768
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3769
        }
×
3770

3771
        // The peer succeeded in starting. If the connection didn't last long
3772
        // enough to be considered stable, we'll continue to back off retries
3773
        // with this peer.
UNCOV
3774
        connDuration := time.Since(startTime)
×
UNCOV
3775
        if connDuration < defaultStableConnDuration {
×
UNCOV
3776
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3777
        }
×
3778

3779
        // The peer succeed in starting and this was stable peer, so we'll
3780
        // reduce the timeout duration by the length of the connection after
3781
        // applying randomized exponential backoff. We'll only apply this in the
3782
        // case that:
3783
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3784
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3785
        if relaxedBackoff > s.cfg.MinBackoff {
×
3786
                return relaxedBackoff
×
3787
        }
×
3788

3789
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3790
        // the stable connection lasted much longer than our previous backoff.
3791
        // To reward such good behavior, we'll reconnect after the default
3792
        // timeout.
3793
        return s.cfg.MinBackoff
×
3794
}
3795

3796
// shouldDropLocalConnection determines if our local connection to a remote peer
3797
// should be dropped in the case of concurrent connection establishment. In
3798
// order to deterministically decide which connection should be dropped, we'll
3799
// utilize the ordering of the local and remote public key. If we didn't use
3800
// such a tie breaker, then we risk _both_ connections erroneously being
3801
// dropped.
3802
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3803
        localPubBytes := local.SerializeCompressed()
×
3804
        remotePubPbytes := remote.SerializeCompressed()
×
3805

×
3806
        // The connection that comes from the node with a "smaller" pubkey
×
3807
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3808
        // should drop our established connection.
×
3809
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3810
}
×
3811

3812
// InboundPeerConnected initializes a new peer in response to a new inbound
3813
// connection.
3814
//
3815
// NOTE: This function is safe for concurrent access.
UNCOV
3816
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3817
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3818
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3819
        if s.Stopped() {
×
3820
                return
×
3821
        }
×
3822

UNCOV
3823
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3824
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3825
        pubStr := string(pubSer)
×
UNCOV
3826

×
UNCOV
3827
        var pubBytes [33]byte
×
UNCOV
3828
        copy(pubBytes[:], pubSer)
×
UNCOV
3829

×
UNCOV
3830
        s.mu.Lock()
×
UNCOV
3831
        defer s.mu.Unlock()
×
UNCOV
3832

×
UNCOV
3833
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3834
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3835
        if dcErr != nil {
×
3836
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3837
                        "peer: %v", dcErr)
×
3838
                conn.Close()
×
3839

×
3840
                return
×
3841
        }
×
3842

UNCOV
3843
        if shouldDc {
×
3844
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3845
                        "banned.", pubSer)
×
3846

×
3847
                conn.Close()
×
3848

×
3849
                return
×
3850
        }
×
3851

3852
        // If we already have an outbound connection to this peer, then ignore
3853
        // this new connection.
UNCOV
3854
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
3855
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
3856
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
3857
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3858

×
UNCOV
3859
                conn.Close()
×
UNCOV
3860
                return
×
UNCOV
3861
        }
×
3862

3863
        // If we already have a valid connection that is scheduled to take
3864
        // precedence once the prior peer has finished disconnecting, we'll
3865
        // ignore this connection.
UNCOV
3866
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3867
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3868
                        "scheduled", conn.RemoteAddr(), p)
×
3869
                conn.Close()
×
3870
                return
×
3871
        }
×
3872

UNCOV
3873
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
×
UNCOV
3874

×
UNCOV
3875
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3876
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3877
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3878
        // default case as we expect these to be the only error values returned
×
UNCOV
3879
        // from findPeerByPubStr.
×
UNCOV
3880
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3881
        switch err {
×
UNCOV
3882
        case ErrPeerNotConnected:
×
UNCOV
3883
                // We were unable to locate an existing connection with the
×
UNCOV
3884
                // target peer, proceed to connect.
×
UNCOV
3885
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3886
                s.peerConnected(conn, nil, true)
×
3887

3888
        case nil:
×
3889
                // We already have a connection with the incoming peer. If the
×
3890
                // connection we've already established should be kept and is
×
3891
                // not of the same type of the new connection (inbound), then
×
3892
                // we'll close out the new connection s.t there's only a single
×
3893
                // connection between us.
×
3894
                localPub := s.identityECDH.PubKey()
×
3895
                if !connectedPeer.Inbound() &&
×
3896
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3897

×
3898
                        srvrLog.Warnf("Received inbound connection from "+
×
3899
                                "peer %v, but already have outbound "+
×
3900
                                "connection, dropping conn", connectedPeer)
×
3901
                        conn.Close()
×
3902
                        return
×
3903
                }
×
3904

3905
                // Otherwise, if we should drop the connection, then we'll
3906
                // disconnect our already connected peer.
3907
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3908
                        connectedPeer)
×
3909

×
3910
                s.cancelConnReqs(pubStr, nil)
×
3911

×
3912
                // Remove the current peer from the server's internal state and
×
3913
                // signal that the peer termination watcher does not need to
×
3914
                // execute for this peer.
×
3915
                s.removePeer(connectedPeer)
×
3916
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3917
                s.scheduledPeerConnection[pubStr] = func() {
×
3918
                        s.peerConnected(conn, nil, true)
×
3919
                }
×
3920
        }
3921
}
3922

3923
// OutboundPeerConnected initializes a new peer in response to a new outbound
3924
// connection.
3925
// NOTE: This function is safe for concurrent access.
UNCOV
3926
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
3927
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3928
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3929
        if s.Stopped() {
×
3930
                return
×
3931
        }
×
3932

UNCOV
3933
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3934
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3935
        pubStr := string(pubSer)
×
UNCOV
3936

×
UNCOV
3937
        var pubBytes [33]byte
×
UNCOV
3938
        copy(pubBytes[:], pubSer)
×
UNCOV
3939

×
UNCOV
3940
        s.mu.Lock()
×
UNCOV
3941
        defer s.mu.Unlock()
×
UNCOV
3942

×
UNCOV
3943
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3944
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3945
        if dcErr != nil {
×
3946
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3947
                        "peer: %v", dcErr)
×
3948
                conn.Close()
×
3949

×
3950
                return
×
3951
        }
×
3952

UNCOV
3953
        if shouldDc {
×
3954
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3955
                        "banned.", pubSer)
×
3956

×
3957
                if connReq != nil {
×
3958
                        s.connMgr.Remove(connReq.ID())
×
3959
                }
×
3960

3961
                conn.Close()
×
3962

×
3963
                return
×
3964
        }
3965

3966
        // If we already have an inbound connection to this peer, then ignore
3967
        // this new connection.
UNCOV
3968
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
3969
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
3970
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
3971
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3972

×
UNCOV
3973
                if connReq != nil {
×
UNCOV
3974
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
3975
                }
×
UNCOV
3976
                conn.Close()
×
UNCOV
3977
                return
×
3978
        }
UNCOV
3979
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
3980
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3981
                s.connMgr.Remove(connReq.ID())
×
3982
                conn.Close()
×
3983
                return
×
3984
        }
×
3985

3986
        // If we already have a valid connection that is scheduled to take
3987
        // precedence once the prior peer has finished disconnecting, we'll
3988
        // ignore this connection.
UNCOV
3989
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3990
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3991

×
3992
                if connReq != nil {
×
3993
                        s.connMgr.Remove(connReq.ID())
×
3994
                }
×
3995

3996
                conn.Close()
×
3997
                return
×
3998
        }
3999

UNCOV
4000
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
UNCOV
4001
                conn.RemoteAddr())
×
UNCOV
4002

×
UNCOV
4003
        if connReq != nil {
×
UNCOV
4004
                // A successful connection was returned by the connmgr.
×
UNCOV
4005
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4006
                // outbound connection we just established.
×
UNCOV
4007
                ignore := connReq.ID()
×
UNCOV
4008
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
4009
        } else {
×
UNCOV
4010
                // This was a successful connection made by some other
×
UNCOV
4011
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
4012
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4013
        }
×
4014

4015
        // If we already have a connection with this peer, decide whether or not
4016
        // we need to drop the stale connection. We forgo adding a default case
4017
        // as we expect these to be the only error values returned from
4018
        // findPeerByPubStr.
UNCOV
4019
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4020
        switch err {
×
UNCOV
4021
        case ErrPeerNotConnected:
×
UNCOV
4022
                // We were unable to locate an existing connection with the
×
UNCOV
4023
                // target peer, proceed to connect.
×
UNCOV
4024
                s.peerConnected(conn, connReq, false)
×
4025

4026
        case nil:
×
4027
                // We already have a connection with the incoming peer. If the
×
4028
                // connection we've already established should be kept and is
×
4029
                // not of the same type of the new connection (outbound), then
×
4030
                // we'll close out the new connection s.t there's only a single
×
4031
                // connection between us.
×
4032
                localPub := s.identityECDH.PubKey()
×
4033
                if connectedPeer.Inbound() &&
×
4034
                        shouldDropLocalConnection(localPub, nodePub) {
×
4035

×
4036
                        srvrLog.Warnf("Established outbound connection to "+
×
4037
                                "peer %v, but already have inbound "+
×
4038
                                "connection, dropping conn", connectedPeer)
×
4039
                        if connReq != nil {
×
4040
                                s.connMgr.Remove(connReq.ID())
×
4041
                        }
×
4042
                        conn.Close()
×
4043
                        return
×
4044
                }
4045

4046
                // Otherwise, _their_ connection should be dropped. So we'll
4047
                // disconnect the peer and send the now obsolete peer to the
4048
                // server for garbage collection.
4049
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4050
                        connectedPeer)
×
4051

×
4052
                // Remove the current peer from the server's internal state and
×
4053
                // signal that the peer termination watcher does not need to
×
4054
                // execute for this peer.
×
4055
                s.removePeer(connectedPeer)
×
4056
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4057
                s.scheduledPeerConnection[pubStr] = func() {
×
4058
                        s.peerConnected(conn, connReq, false)
×
4059
                }
×
4060
        }
4061
}
4062

4063
// UnassignedConnID is the default connection ID that a request can have before
4064
// it actually is submitted to the connmgr.
4065
// TODO(conner): move into connmgr package, or better, add connmgr method for
4066
// generating atomic IDs
4067
const UnassignedConnID uint64 = 0
4068

4069
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4070
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4071
// Afterwards, each connection request removed from the connmgr. The caller can
4072
// optionally specify a connection ID to ignore, which prevents us from
4073
// canceling a successful request. All persistent connreqs for the provided
4074
// pubkey are discarded after the operationjw.
UNCOV
4075
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4076
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4077
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4078
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4079
                close(cancelChan)
×
UNCOV
4080
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4081
        }
×
4082

4083
        // Next, check to see if we have any outstanding persistent connection
4084
        // requests to this peer. If so, then we'll remove all of these
4085
        // connection requests, and also delete the entry from the map.
UNCOV
4086
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4087
        if !ok {
×
UNCOV
4088
                return
×
UNCOV
4089
        }
×
4090

UNCOV
4091
        for _, connReq := range connReqs {
×
UNCOV
4092
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4093

×
UNCOV
4094
                // Atomically capture the current request identifier.
×
UNCOV
4095
                connID := connReq.ID()
×
UNCOV
4096

×
UNCOV
4097
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4098
                // yet been schedule.
×
UNCOV
4099
                if connID == UnassignedConnID {
×
4100
                        continue
×
4101
                }
4102

4103
                // Skip a particular connection ID if instructed.
UNCOV
4104
                if skip != nil && connID == *skip {
×
UNCOV
4105
                        continue
×
4106
                }
4107

UNCOV
4108
                s.connMgr.Remove(connID)
×
4109
        }
4110

UNCOV
4111
        delete(s.persistentConnReqs, pubStr)
×
4112
}
4113

4114
// handleCustomMessage dispatches an incoming custom peers message to
4115
// subscribers.
UNCOV
4116
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4117
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4118
                peer, msg.Type)
×
UNCOV
4119

×
UNCOV
4120
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4121
                Peer: peer,
×
UNCOV
4122
                Msg:  msg,
×
UNCOV
4123
        })
×
UNCOV
4124
}
×
4125

4126
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4127
// messages.
UNCOV
4128
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4129
        return s.customMessageServer.Subscribe()
×
UNCOV
4130
}
×
4131

4132
// peerConnected is a function that handles initialization a newly connected
4133
// peer by adding it to the server's global list of all active peers, and
4134
// starting all the goroutines the peer needs to function properly. The inbound
4135
// boolean should be true if the peer initiated the connection to us.
4136
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
UNCOV
4137
        inbound bool) {
×
UNCOV
4138

×
UNCOV
4139
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4140
        addr := conn.RemoteAddr()
×
UNCOV
4141
        pubKey := brontideConn.RemotePub()
×
UNCOV
4142

×
UNCOV
4143
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4144
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4145

×
UNCOV
4146
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4147
                IdentityKey: pubKey,
×
UNCOV
4148
                Address:     addr,
×
UNCOV
4149
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4150
        }
×
UNCOV
4151

×
UNCOV
4152
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4153
        // vectors to advertise to the remote node.
×
UNCOV
4154
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4155
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4156

×
UNCOV
4157
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4158
        // found, create a fresh buffer.
×
UNCOV
4159
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4160
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4161
        if !ok {
×
UNCOV
4162
                var err error
×
UNCOV
4163
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4164
                if err != nil {
×
4165
                        srvrLog.Errorf("unable to create peer %v", err)
×
4166
                        return
×
4167
                }
×
4168
        }
4169

4170
        // If we directly set the peer.Config TowerClient member to the
4171
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4172
        // the peer.Config's TowerClient member will not evaluate to nil even
4173
        // though the underlying value is nil. To avoid this gotcha which can
4174
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4175
        // TowerClient if needed.
UNCOV
4176
        var towerClient wtclient.ClientManager
×
UNCOV
4177
        if s.towerClientMgr != nil {
×
UNCOV
4178
                towerClient = s.towerClientMgr
×
UNCOV
4179
        }
×
4180

UNCOV
4181
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4182
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4183

×
UNCOV
4184
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4185
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4186
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4187
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4188
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4189
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4190
        pCfg := peer.Config{
×
UNCOV
4191
                Conn:                    brontideConn,
×
UNCOV
4192
                ConnReq:                 connReq,
×
UNCOV
4193
                Addr:                    peerAddr,
×
UNCOV
4194
                Inbound:                 inbound,
×
UNCOV
4195
                Features:                initFeatures,
×
UNCOV
4196
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4197
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4198
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4199
                ErrorBuffer:             errBuffer,
×
UNCOV
4200
                WritePool:               s.writePool,
×
UNCOV
4201
                ReadPool:                s.readPool,
×
UNCOV
4202
                Switch:                  s.htlcSwitch,
×
UNCOV
4203
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4204
                ChannelDB:               s.chanStateDB,
×
UNCOV
4205
                ChannelGraph:            s.graphDB,
×
UNCOV
4206
                ChainArb:                s.chainArb,
×
UNCOV
4207
                AuthGossiper:            s.authGossiper,
×
UNCOV
4208
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4209
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4210
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4211
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4212
                SigPool:                 s.sigPool,
×
UNCOV
4213
                Wallet:                  s.cc.Wallet,
×
UNCOV
4214
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4215
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4216
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4217
                Sphinx:                  s.sphinx,
×
UNCOV
4218
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4219
                Invoices:                s.invoices,
×
UNCOV
4220
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4221
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4222
                TowerClient:             towerClient,
×
UNCOV
4223
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4224
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4225
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4226

×
UNCOV
4227
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4228
                },
×
4229

4230
                PongBuf: s.pongBuf,
4231

4232
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4233

4234
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4235

4236
                FundingManager: s.fundingMgr,
4237

4238
                Hodl:                    s.cfg.Hodl,
4239
                UnsafeReplay:            s.cfg.UnsafeReplay,
4240
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4241
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4242
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4243
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4244
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4245
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4246
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4247
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4248
                HandleCustomMessage:    s.handleCustomMessage,
4249
                GetAliases:             s.aliasMgr.GetAliases,
4250
                RequestAlias:           s.aliasMgr.RequestAlias,
4251
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4252
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4253
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4254
                MaxFeeExposure:         thresholdMSats,
4255
                Quit:                   s.quit,
4256
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4257
                AuxSigner:              s.implCfg.AuxSigner,
4258
                MsgRouter:              s.implCfg.MsgRouter,
4259
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4260
                AuxResolver:            s.implCfg.AuxContractResolver,
4261
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
UNCOV
4262
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4263
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4264
                                return false
×
UNCOV
4265
                        }
×
4266

UNCOV
4267
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4268
                                EndorsementExperimentEnd,
×
UNCOV
4269
                        )
×
4270
                },
4271
        }
4272

UNCOV
4273
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4274
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4275

×
UNCOV
4276
        p := peer.NewBrontide(pCfg)
×
UNCOV
4277

×
UNCOV
4278
        // TODO(roasbeef): update IP address for link-node
×
UNCOV
4279
        //  * also mark last-seen, do it one single transaction?
×
UNCOV
4280

×
UNCOV
4281
        s.addPeer(p)
×
UNCOV
4282

×
UNCOV
4283
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4284
        // delete the previous error buffer from the server's map of error
×
UNCOV
4285
        // buffers.
×
UNCOV
4286
        delete(s.peerErrors, pkStr)
×
UNCOV
4287

×
UNCOV
4288
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4289
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4290
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4291
        s.wg.Add(1)
×
UNCOV
4292
        go s.peerInitializer(p)
×
4293
}
4294

4295
// addPeer adds the passed peer to the server's global state of all active
4296
// peers.
UNCOV
4297
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4298
        if p == nil {
×
4299
                return
×
4300
        }
×
4301

UNCOV
4302
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4303

×
UNCOV
4304
        // Ignore new peers if we're shutting down.
×
UNCOV
4305
        if s.Stopped() {
×
4306
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4307
                        pubBytes)
×
4308
                p.Disconnect(ErrServerShuttingDown)
×
4309

×
4310
                return
×
4311
        }
×
4312

4313
        // Track the new peer in our indexes so we can quickly look it up either
4314
        // according to its public key, or its peer ID.
4315
        // TODO(roasbeef): pipe all requests through to the
4316
        // queryHandler/peerManager
4317

4318
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4319
        // be human-readable.
UNCOV
4320
        pubStr := string(pubBytes)
×
UNCOV
4321

×
UNCOV
4322
        s.peersByPub[pubStr] = p
×
UNCOV
4323

×
UNCOV
4324
        if p.Inbound() {
×
UNCOV
4325
                s.inboundPeers[pubStr] = p
×
UNCOV
4326
        } else {
×
UNCOV
4327
                s.outboundPeers[pubStr] = p
×
UNCOV
4328
        }
×
4329

4330
        // Inform the peer notifier of a peer online event so that it can be reported
4331
        // to clients listening for peer events.
UNCOV
4332
        var pubKey [33]byte
×
UNCOV
4333
        copy(pubKey[:], pubBytes)
×
UNCOV
4334

×
UNCOV
4335
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4336
}
4337

4338
// peerInitializer asynchronously starts a newly connected peer after it has
4339
// been added to the server's peer map. This method sets up a
4340
// peerTerminationWatcher for the given peer, and ensures that it executes even
4341
// if the peer failed to start. In the event of a successful connection, this
4342
// method reads the negotiated, local feature-bits and spawns the appropriate
4343
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4344
// be signaled of the new peer once the method returns.
4345
//
4346
// NOTE: This MUST be launched as a goroutine.
UNCOV
4347
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4348
        defer s.wg.Done()
×
UNCOV
4349

×
UNCOV
4350
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4351

×
UNCOV
4352
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4353
        if s.Stopped() {
×
4354
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4355
                        pubBytes)
×
4356
                return
×
4357
        }
×
4358

4359
        // Create a channel that will be used to signal a successful start of
4360
        // the link. This prevents the peer termination watcher from beginning
4361
        // its duty too early.
UNCOV
4362
        ready := make(chan struct{})
×
UNCOV
4363

×
UNCOV
4364
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4365
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4366
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4367
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4368
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4369
        // that the server has already handled the removal of this peer.
×
UNCOV
4370
        s.wg.Add(1)
×
UNCOV
4371
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4372

×
UNCOV
4373
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4374
        // will unblock the peerTerminationWatcher.
×
UNCOV
4375
        if err := p.Start(); err != nil {
×
UNCOV
4376
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4377

×
UNCOV
4378
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4379
                return
×
UNCOV
4380
        }
×
4381

4382
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4383
        // was successful, and to begin watching the peer's wait group.
UNCOV
4384
        close(ready)
×
UNCOV
4385

×
UNCOV
4386
        s.mu.Lock()
×
UNCOV
4387
        defer s.mu.Unlock()
×
UNCOV
4388

×
UNCOV
4389
        // Check if there are listeners waiting for this peer to come online.
×
UNCOV
4390
        srvrLog.Debugf("Notifying that peer %v is online", p)
×
UNCOV
4391

×
UNCOV
4392
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4393
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4394
        pubStr := string(pubBytes)
×
UNCOV
4395
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4396
                select {
×
UNCOV
4397
                case peerChan <- p:
×
4398
                case <-s.quit:
×
4399
                        return
×
4400
                }
4401
        }
UNCOV
4402
        delete(s.peerConnectedListeners, pubStr)
×
4403
}
4404

4405
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4406
// and then cleans up all resources allocated to the peer, notifies relevant
4407
// sub-systems of its demise, and finally handles re-connecting to the peer if
4408
// it's persistent. If the server intentionally disconnects a peer, it should
4409
// have a corresponding entry in the ignorePeerTermination map which will cause
4410
// the cleanup routine to exit early. The passed `ready` chan is used to
4411
// synchronize when WaitForDisconnect should begin watching on the peer's
4412
// waitgroup. The ready chan should only be signaled if the peer starts
4413
// successfully, otherwise the peer should be disconnected instead.
4414
//
4415
// NOTE: This MUST be launched as a goroutine.
UNCOV
4416
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4417
        defer s.wg.Done()
×
UNCOV
4418

×
UNCOV
4419
        p.WaitForDisconnect(ready)
×
UNCOV
4420

×
UNCOV
4421
        srvrLog.Debugf("Peer %v has been disconnected", p)
×
UNCOV
4422

×
UNCOV
4423
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4424
        // the other sub-systems will already be shutting down.
×
UNCOV
4425
        if s.Stopped() {
×
UNCOV
4426
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4427
                return
×
UNCOV
4428
        }
×
4429

4430
        // Next, we'll cancel all pending funding reservations with this node.
4431
        // If we tried to initiate any funding flows that haven't yet finished,
4432
        // then we need to unlock those committed outputs so they're still
4433
        // available for use.
UNCOV
4434
        s.fundingMgr.CancelPeerReservations(p.PubKey())
×
UNCOV
4435

×
UNCOV
4436
        pubKey := p.IdentityKey()
×
UNCOV
4437

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

×
UNCOV
4442
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4443
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4444
        // with this interface should be closed.
×
UNCOV
4445
        //
×
UNCOV
4446
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4447
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4448
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4449
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4450
        }
×
4451

UNCOV
4452
        for _, link := range links {
×
UNCOV
4453
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4454
        }
×
4455

UNCOV
4456
        s.mu.Lock()
×
UNCOV
4457
        defer s.mu.Unlock()
×
UNCOV
4458

×
UNCOV
4459
        // If there were any notification requests for when this peer
×
UNCOV
4460
        // disconnected, we can trigger them now.
×
UNCOV
4461
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4462
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4463
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4464
                close(offlineChan)
×
UNCOV
4465
        }
×
UNCOV
4466
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4467

×
UNCOV
4468
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4469
        // peer termination watcher and skip cleanup.
×
UNCOV
4470
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4471
                delete(s.ignorePeerTermination, p)
×
4472

×
4473
                pubKey := p.PubKey()
×
4474
                pubStr := string(pubKey[:])
×
4475

×
4476
                // If a connection callback is present, we'll go ahead and
×
4477
                // execute it now that previous peer has fully disconnected. If
×
4478
                // the callback is not present, this likely implies the peer was
×
4479
                // purposefully disconnected via RPC, and that no reconnect
×
4480
                // should be attempted.
×
4481
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4482
                if ok {
×
4483
                        delete(s.scheduledPeerConnection, pubStr)
×
4484
                        connCallback()
×
4485
                }
×
4486
                return
×
4487
        }
4488

4489
        // First, cleanup any remaining state the server has regarding the peer
4490
        // in question.
UNCOV
4491
        s.removePeer(p)
×
UNCOV
4492

×
UNCOV
4493
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4494
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4495
                return
×
UNCOV
4496
        }
×
4497

4498
        // Get the last address that we used to connect to the peer.
UNCOV
4499
        addrs := []net.Addr{
×
UNCOV
4500
                p.NetAddress().Address,
×
UNCOV
4501
        }
×
UNCOV
4502

×
UNCOV
4503
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4504
        // reconnection purposes.
×
UNCOV
4505
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
UNCOV
4506
        switch {
×
4507
        // We found advertised addresses, so use them.
UNCOV
4508
        case err == nil:
×
UNCOV
4509
                addrs = advertisedAddrs
×
4510

4511
        // The peer doesn't have an advertised address.
UNCOV
4512
        case err == errNoAdvertisedAddr:
×
UNCOV
4513
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4514
                // peer address.
×
UNCOV
4515
                if !p.Inbound() {
×
UNCOV
4516
                        break
×
4517
                }
4518

4519
                // Fall back to the existing peer address if
4520
                // we're not accepting connections over Tor.
UNCOV
4521
                if s.torController == nil {
×
UNCOV
4522
                        break
×
4523
                }
4524

4525
                // If we are, the peer's address won't be known
4526
                // to us (we'll see a private address, which is
4527
                // the address used by our onion service to dial
4528
                // to lnd), so we don't have enough information
4529
                // to attempt a reconnect.
4530
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4531
                        "to inbound peer %v without "+
×
4532
                        "advertised address", p)
×
4533
                return
×
4534

4535
        // We came across an error retrieving an advertised
4536
        // address, log it, and fall back to the existing peer
4537
        // address.
UNCOV
4538
        default:
×
UNCOV
4539
                srvrLog.Errorf("Unable to retrieve advertised "+
×
UNCOV
4540
                        "address for node %x: %v", p.PubKey(),
×
UNCOV
4541
                        err)
×
4542
        }
4543

4544
        // Make an easy lookup map so that we can check if an address
4545
        // is already in the address list that we have stored for this peer.
UNCOV
4546
        existingAddrs := make(map[string]bool)
×
UNCOV
4547
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4548
                existingAddrs[addr.String()] = true
×
UNCOV
4549
        }
×
4550

4551
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4552
        for _, addr := range addrs {
×
UNCOV
4553
                if existingAddrs[addr.String()] {
×
4554
                        continue
×
4555
                }
4556

UNCOV
4557
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4558
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4559
                        &lnwire.NetAddress{
×
UNCOV
4560
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4561
                                Address:     addr,
×
UNCOV
4562
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4563
                        },
×
UNCOV
4564
                )
×
4565
        }
4566

4567
        // Record the computed backoff in the backoff map.
UNCOV
4568
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4569
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4570

×
UNCOV
4571
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4572
        // exist.
×
UNCOV
4573
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4574
        if !ok {
×
UNCOV
4575
                cancelChan = make(chan struct{})
×
UNCOV
4576
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4577
        }
×
4578

4579
        // We choose not to wait group this go routine since the Connect
4580
        // call can stall for arbitrarily long if we shutdown while an
4581
        // outbound connection attempt is being made.
UNCOV
4582
        go func() {
×
UNCOV
4583
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
UNCOV
4584
                        "persistent peer %x in %s",
×
UNCOV
4585
                        p.IdentityKey().SerializeCompressed(), backoff)
×
UNCOV
4586

×
UNCOV
4587
                select {
×
UNCOV
4588
                case <-time.After(backoff):
×
UNCOV
4589
                case <-cancelChan:
×
UNCOV
4590
                        return
×
UNCOV
4591
                case <-s.quit:
×
UNCOV
4592
                        return
×
4593
                }
4594

UNCOV
4595
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4596
                        "connection to peer %x",
×
UNCOV
4597
                        p.IdentityKey().SerializeCompressed())
×
UNCOV
4598

×
UNCOV
4599
                s.connectToPersistentPeer(pubStr)
×
4600
        }()
4601
}
4602

4603
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4604
// to connect to the peer. It creates connection requests if there are
4605
// currently none for a given address and it removes old connection requests
4606
// if the associated address is no longer in the latest address list for the
4607
// peer.
UNCOV
4608
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4609
        s.mu.Lock()
×
UNCOV
4610
        defer s.mu.Unlock()
×
UNCOV
4611

×
UNCOV
4612
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4613
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4614
        // connection requests for the associated address and then any leftover
×
UNCOV
4615
        // entries will indicate which addresses we should create new
×
UNCOV
4616
        // connection requests for.
×
UNCOV
4617
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4618
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4619
                addrMap[addr.String()] = addr
×
UNCOV
4620
        }
×
4621

4622
        // Go through each of the existing connection requests and
4623
        // check if they correspond to the latest set of addresses. If
4624
        // there is a connection requests that does not use one of the latest
4625
        // advertised addresses then remove that connection request.
UNCOV
4626
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4627
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4628
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4629

×
UNCOV
4630
                switch _, ok := addrMap[lnAddr]; ok {
×
4631
                // If the existing connection request is using one of the
4632
                // latest advertised addresses for the peer then we add it to
4633
                // updatedConnReqs and remove the associated address from
4634
                // addrMap so that we don't recreate this connReq later on.
4635
                case true:
×
4636
                        updatedConnReqs = append(
×
4637
                                updatedConnReqs, connReq,
×
4638
                        )
×
4639
                        delete(addrMap, lnAddr)
×
4640

4641
                // If the existing connection request is using an address that
4642
                // is not one of the latest advertised addresses for the peer
4643
                // then we remove the connecting request from the connection
4644
                // manager.
UNCOV
4645
                case false:
×
UNCOV
4646
                        srvrLog.Info(
×
UNCOV
4647
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4648
                        )
×
UNCOV
4649
                        s.connMgr.Remove(connReq.ID())
×
4650
                }
4651
        }
4652

UNCOV
4653
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4654

×
UNCOV
4655
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4656
        if !ok {
×
UNCOV
4657
                cancelChan = make(chan struct{})
×
UNCOV
4658
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4659
        }
×
4660

4661
        // Any addresses left in addrMap are new ones that we have not made
4662
        // connection requests for. So create new connection requests for those.
4663
        // If there is more than one address in the address map, stagger the
4664
        // creation of the connection requests for those.
UNCOV
4665
        go func() {
×
UNCOV
4666
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
4667
                defer ticker.Stop()
×
UNCOV
4668

×
UNCOV
4669
                for _, addr := range addrMap {
×
UNCOV
4670
                        // Send the persistent connection request to the
×
UNCOV
4671
                        // connection manager, saving the request itself so we
×
UNCOV
4672
                        // can cancel/restart the process as needed.
×
UNCOV
4673
                        connReq := &connmgr.ConnReq{
×
UNCOV
4674
                                Addr:      addr,
×
UNCOV
4675
                                Permanent: true,
×
UNCOV
4676
                        }
×
UNCOV
4677

×
UNCOV
4678
                        s.mu.Lock()
×
UNCOV
4679
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4680
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4681
                        )
×
UNCOV
4682
                        s.mu.Unlock()
×
UNCOV
4683

×
UNCOV
4684
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4685
                                "channel peer %v", addr)
×
UNCOV
4686

×
UNCOV
4687
                        go s.connMgr.Connect(connReq)
×
UNCOV
4688

×
UNCOV
4689
                        select {
×
UNCOV
4690
                        case <-s.quit:
×
UNCOV
4691
                                return
×
UNCOV
4692
                        case <-cancelChan:
×
UNCOV
4693
                                return
×
UNCOV
4694
                        case <-ticker.C:
×
4695
                        }
4696
                }
4697
        }()
4698
}
4699

4700
// removePeer removes the passed peer from the server's state of all active
4701
// peers.
UNCOV
4702
func (s *server) removePeer(p *peer.Brontide) {
×
UNCOV
4703
        if p == nil {
×
4704
                return
×
4705
        }
×
4706

UNCOV
4707
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4708

×
UNCOV
4709
        // As the peer is now finished, ensure that the TCP connection is
×
UNCOV
4710
        // closed and all of its related goroutines have exited.
×
UNCOV
4711
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
×
UNCOV
4712

×
UNCOV
4713
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4714
        if p.ConnReq() != nil {
×
UNCOV
4715
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4716
        }
×
4717

4718
        // Ignore deleting peers if we're shutting down.
UNCOV
4719
        if s.Stopped() {
×
4720
                return
×
4721
        }
×
4722

UNCOV
4723
        pKey := p.PubKey()
×
UNCOV
4724
        pubSer := pKey[:]
×
UNCOV
4725
        pubStr := string(pubSer)
×
UNCOV
4726

×
UNCOV
4727
        delete(s.peersByPub, pubStr)
×
UNCOV
4728

×
UNCOV
4729
        if p.Inbound() {
×
UNCOV
4730
                delete(s.inboundPeers, pubStr)
×
UNCOV
4731
        } else {
×
UNCOV
4732
                delete(s.outboundPeers, pubStr)
×
UNCOV
4733
        }
×
4734

4735
        // Copy the peer's error buffer across to the server if it has any items
4736
        // in it so that we can restore peer errors across connections.
UNCOV
4737
        if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4738
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4739
        }
×
4740

4741
        // Inform the peer notifier of a peer offline event so that it can be
4742
        // reported to clients listening for peer events.
UNCOV
4743
        var pubKey [33]byte
×
UNCOV
4744
        copy(pubKey[:], pubSer)
×
UNCOV
4745

×
UNCOV
4746
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4747
}
4748

4749
// ConnectToPeer requests that the server connect to a Lightning Network peer
4750
// at the specified address. This function will *block* until either a
4751
// connection is established, or the initial handshake process fails.
4752
//
4753
// NOTE: This function is safe for concurrent access.
4754
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
4755
        perm bool, timeout time.Duration) error {
×
UNCOV
4756

×
UNCOV
4757
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4758

×
UNCOV
4759
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
4760
        // better granularity.  In certain conditions, this method requires
×
UNCOV
4761
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4762
        // lock to be released, and subsequently reacquired.
×
UNCOV
4763
        s.mu.Lock()
×
UNCOV
4764

×
UNCOV
4765
        // Ensure we're not already connected to this peer.
×
UNCOV
4766
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4767
        if err == nil {
×
UNCOV
4768
                s.mu.Unlock()
×
UNCOV
4769
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4770
        }
×
4771

4772
        // Peer was not found, continue to pursue connection with peer.
4773

4774
        // If there's already a pending connection request for this pubkey,
4775
        // then we ignore this request to ensure we don't create a redundant
4776
        // connection.
UNCOV
4777
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
4778
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
4779
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4780
        }
×
4781

4782
        // If there's not already a pending or active connection to this node,
4783
        // then instruct the connection manager to attempt to establish a
4784
        // persistent connection to the peer.
UNCOV
4785
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4786
        if perm {
×
UNCOV
4787
                connReq := &connmgr.ConnReq{
×
UNCOV
4788
                        Addr:      addr,
×
UNCOV
4789
                        Permanent: true,
×
UNCOV
4790
                }
×
UNCOV
4791

×
UNCOV
4792
                // Since the user requested a permanent connection, we'll set
×
UNCOV
4793
                // the entry to true which will tell the server to continue
×
UNCOV
4794
                // reconnecting even if the number of channels with this peer is
×
UNCOV
4795
                // zero.
×
UNCOV
4796
                s.persistentPeers[targetPub] = true
×
UNCOV
4797
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4798
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4799
                }
×
UNCOV
4800
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4801
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4802
                )
×
UNCOV
4803
                s.mu.Unlock()
×
UNCOV
4804

×
UNCOV
4805
                go s.connMgr.Connect(connReq)
×
UNCOV
4806

×
UNCOV
4807
                return nil
×
4808
        }
UNCOV
4809
        s.mu.Unlock()
×
UNCOV
4810

×
UNCOV
4811
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4812
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
4813
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
4814
        // caller.
×
UNCOV
4815
        errChan := make(chan error, 1)
×
UNCOV
4816
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
4817

×
UNCOV
4818
        select {
×
UNCOV
4819
        case err := <-errChan:
×
UNCOV
4820
                return err
×
4821
        case <-s.quit:
×
4822
                return ErrServerShuttingDown
×
4823
        }
4824
}
4825

4826
// connectToPeer establishes a connection to a remote peer. errChan is used to
4827
// notify the caller if the connection attempt has failed. Otherwise, it will be
4828
// closed.
4829
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
4830
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4831

×
UNCOV
4832
        conn, err := brontide.Dial(
×
UNCOV
4833
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4834
        )
×
UNCOV
4835
        if err != nil {
×
UNCOV
4836
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4837
                select {
×
UNCOV
4838
                case errChan <- err:
×
4839
                case <-s.quit:
×
4840
                }
UNCOV
4841
                return
×
4842
        }
4843

UNCOV
4844
        close(errChan)
×
UNCOV
4845

×
UNCOV
4846
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
4847
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4848

×
UNCOV
4849
        s.OutboundPeerConnected(nil, conn)
×
4850
}
4851

4852
// DisconnectPeer sends the request to server to close the connection with peer
4853
// identified by public key.
4854
//
4855
// NOTE: This function is safe for concurrent access.
UNCOV
4856
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
4857
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
4858
        pubStr := string(pubBytes)
×
UNCOV
4859

×
UNCOV
4860
        s.mu.Lock()
×
UNCOV
4861
        defer s.mu.Unlock()
×
UNCOV
4862

×
UNCOV
4863
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
4864
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
4865
        // currently connected to.
×
UNCOV
4866
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4867
        if err == ErrPeerNotConnected {
×
UNCOV
4868
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
4869
        }
×
4870

UNCOV
4871
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
4872

×
UNCOV
4873
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
4874

×
UNCOV
4875
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
4876
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
4877
        // disconnect.
×
UNCOV
4878
        delete(s.persistentPeers, pubStr)
×
UNCOV
4879
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
4880

×
UNCOV
4881
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
4882
        // removePeer, which bypassed the peerTerminationWatcher.
×
UNCOV
4883
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
4884

×
UNCOV
4885
        return nil
×
4886
}
4887

4888
// OpenChannel sends a request to the server to open a channel to the specified
4889
// peer identified by nodeKey with the passed channel funding parameters.
4890
//
4891
// NOTE: This function is safe for concurrent access.
4892
func (s *server) OpenChannel(
UNCOV
4893
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
4894

×
UNCOV
4895
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
4896
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
4897
        // not blocked if the caller is not reading the updates.
×
UNCOV
4898
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
4899
        req.Err = make(chan error, 1)
×
UNCOV
4900

×
UNCOV
4901
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
4902
        // we're unable to locate the peer then this request will fail.
×
UNCOV
4903
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
4904
        s.mu.RLock()
×
UNCOV
4905
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
4906
        if !ok {
×
4907
                s.mu.RUnlock()
×
4908

×
4909
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4910
                return req.Updates, req.Err
×
4911
        }
×
UNCOV
4912
        req.Peer = peer
×
UNCOV
4913
        s.mu.RUnlock()
×
UNCOV
4914

×
UNCOV
4915
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
4916
        // opening process.
×
UNCOV
4917
        select {
×
UNCOV
4918
        case <-peer.ActiveSignal():
×
4919
        case <-peer.QuitSignal():
×
4920
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4921
                return req.Updates, req.Err
×
4922
        case <-s.quit:
×
4923
                req.Err <- ErrServerShuttingDown
×
4924
                return req.Updates, req.Err
×
4925
        }
4926

4927
        // If the fee rate wasn't specified at this point we fail the funding
4928
        // because of the missing fee rate information. The caller of the
4929
        // `OpenChannel` method needs to make sure that default values for the
4930
        // fee rate are set beforehand.
UNCOV
4931
        if req.FundingFeePerKw == 0 {
×
4932
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4933
                        "the channel opening transaction")
×
4934

×
4935
                return req.Updates, req.Err
×
4936
        }
×
4937

4938
        // Spawn a goroutine to send the funding workflow request to the funding
4939
        // manager. This allows the server to continue handling queries instead
4940
        // of blocking on this request which is exported as a synchronous
4941
        // request to the outside world.
UNCOV
4942
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
4943

×
UNCOV
4944
        return req.Updates, req.Err
×
4945
}
4946

4947
// Peers returns a slice of all active peers.
4948
//
4949
// NOTE: This function is safe for concurrent access.
UNCOV
4950
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
4951
        s.mu.RLock()
×
UNCOV
4952
        defer s.mu.RUnlock()
×
UNCOV
4953

×
UNCOV
4954
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
4955
        for _, peer := range s.peersByPub {
×
UNCOV
4956
                peers = append(peers, peer)
×
UNCOV
4957
        }
×
4958

UNCOV
4959
        return peers
×
4960
}
4961

4962
// computeNextBackoff uses a truncated exponential backoff to compute the next
4963
// backoff using the value of the exiting backoff. The returned duration is
4964
// randomized in either direction by 1/20 to prevent tight loops from
4965
// stabilizing.
UNCOV
4966
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
4967
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
4968
        nextBackoff := 2 * currBackoff
×
UNCOV
4969
        if nextBackoff > maxBackoff {
×
UNCOV
4970
                nextBackoff = maxBackoff
×
UNCOV
4971
        }
×
4972

4973
        // Using 1/10 of our duration as a margin, compute a random offset to
4974
        // avoid the nodes entering connection cycles.
UNCOV
4975
        margin := nextBackoff / 10
×
UNCOV
4976

×
UNCOV
4977
        var wiggle big.Int
×
UNCOV
4978
        wiggle.SetUint64(uint64(margin))
×
UNCOV
4979
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
4980
                // Randomizing is not mission critical, so we'll just return the
×
4981
                // current backoff.
×
4982
                return nextBackoff
×
4983
        }
×
4984

4985
        // Otherwise add in our wiggle, but subtract out half of the margin so
4986
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
4987
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
4988
}
4989

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

4994
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
UNCOV
4995
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
4996
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
4997
        if err != nil {
×
4998
                return nil, err
×
4999
        }
×
5000

UNCOV
5001
        node, err := s.graphDB.FetchLightningNode(vertex)
×
UNCOV
5002
        if err != nil {
×
UNCOV
5003
                return nil, err
×
UNCOV
5004
        }
×
5005

UNCOV
5006
        if len(node.Addresses) == 0 {
×
UNCOV
5007
                return nil, errNoAdvertisedAddr
×
UNCOV
5008
        }
×
5009

UNCOV
5010
        return node.Addresses, nil
×
5011
}
5012

5013
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5014
// channel update for a target channel.
5015
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5016
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5017

×
UNCOV
5018
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5019
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5020
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5021
                if err != nil {
×
UNCOV
5022
                        return nil, err
×
UNCOV
5023
                }
×
5024

UNCOV
5025
                return netann.ExtractChannelUpdate(
×
UNCOV
5026
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5027
                )
×
5028
        }
5029
}
5030

5031
// applyChannelUpdate applies the channel update to the different sub-systems of
5032
// the server. The useAlias boolean denotes whether or not to send an alias in
5033
// place of the real SCID.
5034
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5035
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5036

×
UNCOV
5037
        var (
×
UNCOV
5038
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5039
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5040
        )
×
UNCOV
5041

×
UNCOV
5042
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5043

×
UNCOV
5044
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5045
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5046
        if useAlias {
×
UNCOV
5047
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5048
                if foundAlias != defaultAlias {
×
UNCOV
5049
                        peerAlias = &foundAlias
×
UNCOV
5050
                }
×
5051
        }
5052

UNCOV
5053
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5054
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5055
        )
×
UNCOV
5056
        select {
×
UNCOV
5057
        case err := <-errChan:
×
UNCOV
5058
                return err
×
5059
        case <-s.quit:
×
5060
                return ErrServerShuttingDown
×
5061
        }
5062
}
5063

5064
// SendCustomMessage sends a custom message to the peer with the specified
5065
// pubkey.
5066
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5067
        data []byte) error {
×
UNCOV
5068

×
UNCOV
5069
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5070
        if err != nil {
×
5071
                return err
×
5072
        }
×
5073

5074
        // We'll wait until the peer is active.
UNCOV
5075
        select {
×
UNCOV
5076
        case <-peer.ActiveSignal():
×
5077
        case <-peer.QuitSignal():
×
5078
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5079
        case <-s.quit:
×
5080
                return ErrServerShuttingDown
×
5081
        }
5082

UNCOV
5083
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5084
        if err != nil {
×
UNCOV
5085
                return err
×
UNCOV
5086
        }
×
5087

5088
        // Send the message as low-priority. For now we assume that all
5089
        // application-defined message are low priority.
UNCOV
5090
        return peer.SendMessageLazy(true, msg)
×
5091
}
5092

5093
// newSweepPkScriptGen creates closure that generates a new public key script
5094
// which should be used to sweep any funds into the on-chain wallet.
5095
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5096
// (p2wkh) output.
5097
func newSweepPkScriptGen(
5098
        wallet lnwallet.WalletController,
UNCOV
5099
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5100

×
UNCOV
5101
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5102
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5103
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5104
                        lnwallet.DefaultAccountName,
×
UNCOV
5105
                )
×
UNCOV
5106
                if err != nil {
×
5107
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5108
                }
×
5109

UNCOV
5110
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5111
                if err != nil {
×
5112
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5113
                }
×
5114

UNCOV
5115
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5116
                        wallet, netParams, addr,
×
UNCOV
5117
                )
×
UNCOV
5118
                if err != nil {
×
5119
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5120
                }
×
5121

UNCOV
5122
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5123
                        DeliveryAddress: addr,
×
UNCOV
5124
                        InternalKey:     internalKeyDesc,
×
UNCOV
5125
                })
×
5126
        }
5127
}
5128

5129
// shouldPeerBootstrap returns true if we should attempt to perform peer
5130
// bootstrapping to actively seek our peers using the set of active network
5131
// bootstrappers.
5132
func shouldPeerBootstrap(cfg *Config) bool {
6✔
5133
        isSimnet := cfg.Bitcoin.SimNet
6✔
5134
        isSignet := cfg.Bitcoin.SigNet
6✔
5135
        isRegtest := cfg.Bitcoin.RegTest
6✔
5136
        isDevNetwork := isSimnet || isSignet || isRegtest
6✔
5137

6✔
5138
        // TODO(yy): remove the check on simnet/regtest such that the itest is
6✔
5139
        // covering the bootstrapping process.
6✔
5140
        return !cfg.NoNetBootstrap && !isDevNetwork
6✔
5141
}
6✔
5142

5143
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5144
// finished.
UNCOV
5145
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5146
        // Get a list of closed channels.
×
UNCOV
5147
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5148
        if err != nil {
×
5149
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5150
                return nil
×
5151
        }
×
5152

5153
        // Save the SCIDs in a map.
UNCOV
5154
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5155
        for _, c := range channels {
×
UNCOV
5156
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5157
                if !c.IsPending {
×
UNCOV
5158
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5159
                }
×
5160
        }
5161

5162
        // Double check whether the reported closed channel has indeed finished
5163
        // closing.
5164
        //
5165
        // NOTE: There are misalignments regarding when a channel's FC is
5166
        // marked as finalized. We double check the pending channels to make
5167
        // sure the returned SCIDs are indeed terminated.
5168
        //
5169
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5170
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5171
        if err != nil {
×
5172
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5173
                return nil
×
5174
        }
×
5175

UNCOV
5176
        for _, c := range pendings {
×
UNCOV
5177
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5178
                        continue
×
5179
                }
5180

5181
                // If the channel is still reported as pending, remove it from
5182
                // the map.
5183
                delete(closedSCIDs, c.ShortChannelID)
×
5184

×
5185
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5186
                        c.ShortChannelID)
×
5187
        }
5188

UNCOV
5189
        return closedSCIDs
×
5190
}
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