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

lightningnetwork / lnd / 12414491588

19 Dec 2024 02:18PM UTC coverage: 57.468% (+8.1%) from 49.414%
12414491588

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

129 of 274 new or added lines in 7 files covered. (47.08%)

19694 existing lines in 247 files now uncovered.

102586 of 178511 relevant lines covered (57.47%)

24598.76 hits per line

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

0.28
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

167
        start sync.Once
168
        stop  sync.Once
169

170
        cfg *Config
171

172
        implCfg *ImplementationCfg
173

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

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

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

185
        chanStatusMgr *netann.ChanStatusManager
186

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

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

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

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

207
        mu sync.RWMutex
208

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

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

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

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

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

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

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

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

259
        cc *chainreg.ChainControl
260

261
        fundingMgr *funding.Manager
262

263
        graphDB *graphdb.ChannelGraph
264

265
        chanStateDB *channeldb.ChannelStateDB
266

267
        addrSource channeldb.AddrSource
268

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

273
        invoicesDB invoices.InvoiceDB
274

275
        aliasMgr *aliasmgr.Manager
276

277
        htlcSwitch *htlcswitch.Switch
278

279
        interceptableSwitch *htlcswitch.InterceptableSwitch
280

281
        invoices *invoices.InvoiceRegistry
282

283
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
284

285
        channelNotifier *channelnotifier.ChannelNotifier
286

287
        peerNotifier *peernotifier.PeerNotifier
288

289
        htlcNotifier *htlcswitch.HtlcNotifier
290

291
        witnessBeacon contractcourt.WitnessBeacon
292

293
        breachArbitrator *contractcourt.BreachArbitrator
294

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

298
        graphBuilder *graph.Builder
299

300
        chanRouter *routing.ChannelRouter
301

302
        controlTower routing.ControlTower
303

304
        authGossiper *discovery.AuthenticatedGossiper
305

306
        localChanMgr *localchans.Manager
307

308
        utxoNursery *contractcourt.UtxoNursery
309

310
        sweeper *sweep.UtxoSweeper
311

312
        chainArb *contractcourt.ChainArbitrator
313

314
        sphinx *hop.OnionProcessor
315

316
        towerClientMgr *wtclient.Manager
317

318
        connMgr *connmgr.ConnManager
319

320
        sigPool *lnwallet.SigPool
321

322
        writePool *pool.Write
323

324
        readPool *pool.Read
325

326
        tlsManager *TLSManager
327

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

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

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

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

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

350
        hostAnn *netann.HostAnnouncer
351

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

355
        customMessageServer *subscribe.Server
356

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

360
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
361
        // of new blocks.
362
        blockbeatDispatcher *chainio.BlockbeatDispatcher
363

364
        quit chan struct{}
365

366
        wg sync.WaitGroup
367
}
368

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

UNCOV
377
        s.wg.Add(1)
×
UNCOV
378
        go func() {
×
UNCOV
379
                defer func() {
×
UNCOV
380
                        graphSub.Cancel()
×
UNCOV
381
                        s.wg.Done()
×
UNCOV
382
                }()
×
383

UNCOV
384
                for {
×
UNCOV
385
                        select {
×
UNCOV
386
                        case <-s.quit:
×
UNCOV
387
                                return
×
388

UNCOV
389
                        case topChange, ok := <-graphSub.TopologyChanges:
×
UNCOV
390
                                // If the router is shutting down, then we will
×
UNCOV
391
                                // as well.
×
UNCOV
392
                                if !ok {
×
393
                                        return
×
394
                                }
×
395

UNCOV
396
                                for _, update := range topChange.NodeUpdates {
×
UNCOV
397
                                        pubKeyStr := string(
×
UNCOV
398
                                                update.IdentityKey.
×
UNCOV
399
                                                        SerializeCompressed(),
×
UNCOV
400
                                        )
×
UNCOV
401

×
UNCOV
402
                                        // We only care about updates from
×
UNCOV
403
                                        // our persistentPeers.
×
UNCOV
404
                                        s.mu.RLock()
×
UNCOV
405
                                        _, ok := s.persistentPeers[pubKeyStr]
×
UNCOV
406
                                        s.mu.RUnlock()
×
UNCOV
407
                                        if !ok {
×
UNCOV
408
                                                continue
×
409
                                        }
410

UNCOV
411
                                        addrs := make([]*lnwire.NetAddress, 0,
×
UNCOV
412
                                                len(update.Addresses))
×
UNCOV
413

×
UNCOV
414
                                        for _, addr := range update.Addresses {
×
UNCOV
415
                                                addrs = append(addrs,
×
UNCOV
416
                                                        &lnwire.NetAddress{
×
UNCOV
417
                                                                IdentityKey: update.IdentityKey,
×
UNCOV
418
                                                                Address:     addr,
×
UNCOV
419
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
420
                                                        },
×
UNCOV
421
                                                )
×
UNCOV
422
                                        }
×
423

UNCOV
424
                                        s.mu.Lock()
×
UNCOV
425

×
UNCOV
426
                                        // Update the stored addresses for this
×
UNCOV
427
                                        // to peer to reflect the new set.
×
UNCOV
428
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
UNCOV
429

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

UNCOV
440
                                        s.mu.Unlock()
×
UNCOV
441

×
UNCOV
442
                                        s.connectToPersistentPeer(pubKeyStr)
×
443
                                }
444
                        }
445
                }
446
        }()
447

UNCOV
448
        return nil
×
449
}
450

451
// CustomMessage is a custom message that is received from a peer.
452
type CustomMessage struct {
453
        // Peer is the peer pubkey
454
        Peer [33]byte
455

456
        // Msg is the custom wire message.
457
        Msg *lnwire.Custom
458
}
459

460
// parseAddr parses an address from its string format to a net.Addr.
UNCOV
461
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
UNCOV
462
        var (
×
UNCOV
463
                host string
×
UNCOV
464
                port int
×
UNCOV
465
        )
×
UNCOV
466

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

UNCOV
484
        if tor.IsOnionHost(host) {
×
485
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
486
        }
×
487

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

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

×
UNCOV
501
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
502
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
503
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
504
        }
×
505
}
506

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

×
UNCOV
518
        var (
×
UNCOV
519
                err         error
×
UNCOV
520
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
UNCOV
521

×
UNCOV
522
                // We just derived the full descriptor, so we know the public
×
UNCOV
523
                // key is set on it.
×
UNCOV
524
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
×
UNCOV
525
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
×
UNCOV
526
                )
×
UNCOV
527
        )
×
UNCOV
528

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

UNCOV
542
        var serializedPubKey [33]byte
×
UNCOV
543
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
544

×
UNCOV
545
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
546

×
UNCOV
547
        // Initialize the sphinx router.
×
UNCOV
548
        replayLog := htlcswitch.NewDecayedLog(
×
UNCOV
549
                dbs.DecayedLogDB, cc.ChainNotifier,
×
UNCOV
550
        )
×
UNCOV
551
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
UNCOV
552

×
UNCOV
553
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
554
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
555
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
556
        )
×
UNCOV
557

×
UNCOV
558
        writePool := pool.NewWrite(
×
UNCOV
559
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
UNCOV
560
        )
×
UNCOV
561

×
UNCOV
562
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
563
                pool.DefaultReadBufferGCInterval,
×
UNCOV
564
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
565
        )
×
UNCOV
566

×
UNCOV
567
        readPool := pool.NewRead(
×
UNCOV
568
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
UNCOV
569
        )
×
UNCOV
570

×
UNCOV
571
        // If the taproot overlay flag is set, but we don't have an aux funding
×
UNCOV
572
        // controller, then we'll exit as this is incompatible.
×
UNCOV
573
        if cfg.ProtocolOptions.TaprootOverlayChans &&
×
UNCOV
574
                implCfg.AuxFundingController.IsNone() {
×
575

×
576
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
577
                        "aux controllers")
×
578
        }
×
579

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

UNCOV
602
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
UNCOV
603
        registryConfig := invoices.RegistryConfig{
×
UNCOV
604
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
605
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
UNCOV
606
                Clock:                       clock.NewDefaultClock(),
×
UNCOV
607
                AcceptKeySend:               cfg.AcceptKeySend,
×
UNCOV
608
                AcceptAMP:                   cfg.AcceptAMP,
×
UNCOV
609
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
UNCOV
610
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
UNCOV
611
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
UNCOV
612
                HtlcInterceptor:             invoiceHtlcModifier,
×
UNCOV
613
        }
×
UNCOV
614

×
UNCOV
615
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
×
UNCOV
616

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

×
UNCOV
631
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
×
UNCOV
632
                        cc.ChainNotifier,
×
UNCOV
633
                ),
×
UNCOV
634
                channelNotifier: channelnotifier.New(
×
UNCOV
635
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
636
                ),
×
UNCOV
637

×
UNCOV
638
                identityECDH:   nodeKeyECDH,
×
UNCOV
639
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
640
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
641

×
UNCOV
642
                listenAddrs: listenAddrs,
×
UNCOV
643

×
UNCOV
644
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
645
                // schedule
×
UNCOV
646
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
647

×
UNCOV
648
                torController: torController,
×
UNCOV
649

×
UNCOV
650
                persistentPeers:         make(map[string]bool),
×
UNCOV
651
                persistentPeersBackoff:  make(map[string]time.Duration),
×
UNCOV
652
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
UNCOV
653
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
UNCOV
654
                persistentRetryCancels:  make(map[string]chan struct{}),
×
UNCOV
655
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
UNCOV
656
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
UNCOV
657
                scheduledPeerConnection: make(map[string]func()),
×
UNCOV
658
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
UNCOV
659

×
UNCOV
660
                peersByPub:                make(map[string]*peer.Brontide),
×
UNCOV
661
                inboundPeers:              make(map[string]*peer.Brontide),
×
UNCOV
662
                outboundPeers:             make(map[string]*peer.Brontide),
×
UNCOV
663
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
UNCOV
664
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
UNCOV
665

×
UNCOV
666
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
667

×
UNCOV
668
                customMessageServer: subscribe.NewServer(),
×
UNCOV
669

×
UNCOV
670
                tlsManager: tlsManager,
×
UNCOV
671

×
UNCOV
672
                featureMgr: featureMgr,
×
UNCOV
673
                quit:       make(chan struct{}),
×
UNCOV
674
        }
×
UNCOV
675

×
UNCOV
676
        // Start the low-level services once they are initialized.
×
UNCOV
677
        //
×
UNCOV
678
        // TODO(yy): break the server startup into four steps,
×
UNCOV
679
        // 1. init the low-level services.
×
UNCOV
680
        // 2. start the low-level services.
×
UNCOV
681
        // 3. init the high-level services.
×
UNCOV
682
        // 4. start the high-level services.
×
UNCOV
683
        if err := s.startLowLevelServices(); err != nil {
×
684
                return nil, err
×
685
        }
×
686

UNCOV
687
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
688
        if err != nil {
×
689
                return nil, err
×
690
        }
×
691

UNCOV
692
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
693
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
694
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
695
        )
×
UNCOV
696
        s.invoices = invoices.NewRegistry(
×
UNCOV
697
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
698
        )
×
UNCOV
699

×
UNCOV
700
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
701

×
UNCOV
702
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
703
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
704

×
UNCOV
705
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
706
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
707
                if err != nil {
×
708
                        return err
×
709
                }
×
710

UNCOV
711
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
712

×
UNCOV
713
                return nil
×
714
        }
715

UNCOV
716
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
717
        if err != nil {
×
718
                return nil, err
×
719
        }
×
720

UNCOV
721
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
722
                DB:                   dbs.ChanStateDB,
×
UNCOV
723
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
UNCOV
724
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
725
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
726
                LocalChannelClose: func(pubKey []byte,
×
UNCOV
727
                        request *htlcswitch.ChanClose) {
×
UNCOV
728

×
UNCOV
729
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
UNCOV
730
                        if err != nil {
×
731
                                srvrLog.Errorf("unable to close channel, peer"+
×
732
                                        " with %v id can't be found: %v",
×
733
                                        pubKey, err,
×
734
                                )
×
735
                                return
×
736
                        }
×
737

UNCOV
738
                        peer.HandleLocalCloseChanReqs(request)
×
739
                },
740
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
741
                SwitchPackager:         channeldb.NewSwitchPackager(),
742
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
743
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
744
                Notifier:               s.cc.ChainNotifier,
745
                HtlcNotifier:           s.htlcNotifier,
746
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
747
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
748
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
749
                AllowCircularRoute:     cfg.AllowCircularRoute,
750
                RejectHTLC:             cfg.RejectHTLC,
751
                Clock:                  clock.NewDefaultClock(),
752
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
753
                MaxFeeExposure:         thresholdMSats,
754
                SignAliasUpdate:        s.signAliasUpdate,
755
                IsAlias:                aliasmgr.IsAlias,
756
        }, uint32(currentHeight))
UNCOV
757
        if err != nil {
×
758
                return nil, err
×
759
        }
×
UNCOV
760
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
UNCOV
761
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
762
                        Switch:             s.htlcSwitch,
×
UNCOV
763
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
764
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
UNCOV
765
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
UNCOV
766
                        Notifier:           s.cc.ChainNotifier,
×
UNCOV
767
                },
×
UNCOV
768
        )
×
UNCOV
769
        if err != nil {
×
770
                return nil, err
×
771
        }
×
772

UNCOV
773
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
774
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
775
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
776
        )
×
UNCOV
777

×
UNCOV
778
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
779
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
780
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
UNCOV
781
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
UNCOV
782
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
783
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
784
                MessageSigner:            s.nodeSigner,
×
UNCOV
785
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
UNCOV
786
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
787
                DB:                       s.chanStateDB,
×
UNCOV
788
                Graph:                    dbs.GraphDB,
×
UNCOV
789
        }
×
UNCOV
790

×
UNCOV
791
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
792
        if err != nil {
×
793
                return nil, err
×
794
        }
×
UNCOV
795
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
796

×
UNCOV
797
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
798
        // port forwarding for users behind a NAT.
×
UNCOV
799
        if cfg.NAT {
×
800
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
801

×
802
                discoveryTimeout := time.Duration(10 * time.Second)
×
803

×
804
                ctx, cancel := context.WithTimeout(
×
805
                        context.Background(), discoveryTimeout,
×
806
                )
×
807
                defer cancel()
×
808
                upnp, err := nat.DiscoverUPnP(ctx)
×
809
                if err == nil {
×
810
                        s.natTraversal = upnp
×
811
                } else {
×
812
                        // If we were not able to discover a UPnP enabled device
×
813
                        // on the local network, we'll fall back to attempting
×
814
                        // to discover a NAT-PMP enabled device.
×
815
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
816
                                "device on the local network: %v", err)
×
817

×
818
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
819
                                "enabled device")
×
820

×
821
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
822
                        if err != nil {
×
823
                                err := fmt.Errorf("unable to discover a "+
×
824
                                        "NAT-PMP enabled device on the local "+
×
825
                                        "network: %v", err)
×
826
                                srvrLog.Error(err)
×
827
                                return nil, err
×
828
                        }
×
829

830
                        s.natTraversal = pmp
×
831
                }
832
        }
833

834
        // If we were requested to automatically configure port forwarding,
835
        // we'll use the ports that the server will be listening on.
UNCOV
836
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
837
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
838
                externalIPStrings[idx] = ip.String()
×
UNCOV
839
        }
×
UNCOV
840
        if s.natTraversal != nil {
×
841
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
842
                for _, listenAddr := range listenAddrs {
×
843
                        // At this point, the listen addresses should have
×
844
                        // already been normalized, so it's safe to ignore the
×
845
                        // errors.
×
846
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
847
                        port, _ := strconv.Atoi(portStr)
×
848

×
849
                        listenPorts = append(listenPorts, uint16(port))
×
850
                }
×
851

852
                ips, err := s.configurePortForwarding(listenPorts...)
×
853
                if err != nil {
×
854
                        srvrLog.Errorf("Unable to automatically set up port "+
×
855
                                "forwarding using %s: %v",
×
856
                                s.natTraversal.Name(), err)
×
857
                } else {
×
858
                        srvrLog.Infof("Automatically set up port forwarding "+
×
859
                                "using %s to advertise external IP",
×
860
                                s.natTraversal.Name())
×
861
                        externalIPStrings = append(externalIPStrings, ips...)
×
862
                }
×
863
        }
864

865
        // If external IP addresses have been specified, add those to the list
866
        // of this server's addresses.
UNCOV
867
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
868
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
869
                cfg.net.ResolveTCPAddr,
×
UNCOV
870
        )
×
UNCOV
871
        if err != nil {
×
872
                return nil, err
×
873
        }
×
874

UNCOV
875
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
UNCOV
876
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
877

×
UNCOV
878
        // We'll now reconstruct a node announcement based on our current
×
UNCOV
879
        // configuration so we can send it out as a sort of heart beat within
×
UNCOV
880
        // the network.
×
UNCOV
881
        //
×
UNCOV
882
        // We'll start by parsing the node color from configuration.
×
UNCOV
883
        color, err := lncfg.ParseHexColor(cfg.Color)
×
UNCOV
884
        if err != nil {
×
885
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
886
                return nil, err
×
887
        }
×
888

889
        // If no alias is provided, default to first 10 characters of public
890
        // key.
UNCOV
891
        alias := cfg.Alias
×
UNCOV
892
        if alias == "" {
×
UNCOV
893
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
894
        }
×
UNCOV
895
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
896
        if err != nil {
×
897
                return nil, err
×
898
        }
×
UNCOV
899
        selfNode := &models.LightningNode{
×
UNCOV
900
                HaveNodeAnnouncement: true,
×
UNCOV
901
                LastUpdate:           time.Now(),
×
UNCOV
902
                Addresses:            selfAddrs,
×
UNCOV
903
                Alias:                nodeAlias.String(),
×
UNCOV
904
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
905
                Color:                color,
×
UNCOV
906
        }
×
UNCOV
907
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
908

×
UNCOV
909
        // Based on the disk representation of the node announcement generated
×
UNCOV
910
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
911
        // network so we can properly sign it.
×
UNCOV
912
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
913
        if err != nil {
×
914
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
915
        }
×
916

917
        // With the announcement generated, we'll sign it to properly
918
        // authenticate the message on the network.
UNCOV
919
        authSig, err := netann.SignAnnouncement(
×
UNCOV
920
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
921
        )
×
UNCOV
922
        if err != nil {
×
923
                return nil, fmt.Errorf("unable to generate signature for "+
×
924
                        "self node announcement: %v", err)
×
925
        }
×
UNCOV
926
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
927
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
928
                selfNode.AuthSigBytes,
×
UNCOV
929
        )
×
UNCOV
930
        if err != nil {
×
931
                return nil, err
×
932
        }
×
933

934
        // Finally, we'll update the representation on disk, and update our
935
        // cached in-memory version as well.
UNCOV
936
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
×
937
                return nil, fmt.Errorf("can't set self node: %w", err)
×
938
        }
×
UNCOV
939
        s.currentNodeAnn = nodeAnn
×
UNCOV
940

×
UNCOV
941
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
942
        // can generate unique payment IDs.
×
UNCOV
943
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
944
        if err != nil {
×
945
                return nil, err
×
946
        }
×
947

948
        // Instantiate mission control with config from the sub server.
949
        //
950
        // TODO(joostjager): When we are further in the process of moving to sub
951
        // servers, the mission control instance itself can be moved there too.
UNCOV
952
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
953

×
UNCOV
954
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
955
        var estimator routing.Estimator
×
UNCOV
956
        if cfg.Estimator != nil {
×
957
                estimator = cfg.Estimator
×
UNCOV
958
        } else {
×
UNCOV
959
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
960
                case routing.AprioriEstimatorName:
×
UNCOV
961
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
962
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
963
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
964
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
965
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
966
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
967
                        }
×
UNCOV
968

×
UNCOV
969
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
970
                                aprioriConfig,
×
UNCOV
971
                        )
×
UNCOV
972
                        if err != nil {
×
973
                                return nil, err
×
974
                        }
×
975

976
                case routing.BimodalEstimatorName:
×
977
                        bCfg := routingConfig.BimodalConfig
×
978
                        bimodalConfig := routing.BimodalConfig{
×
979
                                BimodalNodeWeight: bCfg.NodeWeight,
×
980
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
981
                                        bCfg.Scale,
×
982
                                ),
×
983
                                BimodalDecayTime: bCfg.DecayTime,
×
984
                        }
×
985

×
986
                        estimator, err = routing.NewBimodalEstimator(
×
987
                                bimodalConfig,
×
988
                        )
×
989
                        if err != nil {
×
990
                                return nil, err
×
991
                        }
×
992

993
                default:
×
994
                        return nil, fmt.Errorf("unknown estimator type %v",
×
995
                                routingConfig.ProbabilityEstimatorType)
×
996
                }
997
        }
998

UNCOV
999
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
1000
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
1001
                Estimator:               estimator,
×
UNCOV
1002
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
1003
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
1004
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
1005
        }
×
UNCOV
1006

×
UNCOV
1007
        s.missionController, err = routing.NewMissionController(
×
UNCOV
1008
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
1009
        )
×
UNCOV
1010
        if err != nil {
×
1011
                return nil, fmt.Errorf("can't create mission control "+
×
1012
                        "manager: %w", err)
×
1013
        }
×
UNCOV
1014
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
1015
                routing.DefaultMissionControlNamespace,
×
UNCOV
1016
        )
×
UNCOV
1017
        if err != nil {
×
1018
                return nil, fmt.Errorf("can't create mission control in the "+
×
1019
                        "default namespace: %w", err)
×
1020
        }
×
1021

UNCOV
1022
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
1023
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
1024
                int64(routingConfig.AttemptCost),
×
UNCOV
1025
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
1026
                routingConfig.MinRouteProbability)
×
UNCOV
1027

×
UNCOV
1028
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
1029
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
1030
                        routingConfig.AttemptCost,
×
UNCOV
1031
                ),
×
UNCOV
1032
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
1033
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1034
        }
×
UNCOV
1035

×
UNCOV
1036
        sourceNode, err := dbs.GraphDB.SourceNode()
×
UNCOV
1037
        if err != nil {
×
1038
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1039
        }
×
UNCOV
1040
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1041
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
×
UNCOV
1042
                        dbs.GraphDB,
×
UNCOV
1043
                ),
×
UNCOV
1044
                SourceNode:        sourceNode,
×
UNCOV
1045
                MissionControl:    s.defaultMC,
×
UNCOV
1046
                GetLink:           s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1047
                PathFindingConfig: pathFindingConfig,
×
UNCOV
1048
        }
×
UNCOV
1049

×
UNCOV
1050
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1051

×
UNCOV
1052
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1053

×
UNCOV
1054
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1055
                cfg.Routing.StrictZombiePruning
×
UNCOV
1056

×
UNCOV
1057
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1058
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1059
                Graph:               dbs.GraphDB,
×
UNCOV
1060
                Chain:               cc.ChainIO,
×
UNCOV
1061
                ChainView:           cc.ChainView,
×
UNCOV
1062
                Notifier:            cc.ChainNotifier,
×
UNCOV
1063
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1064
                GraphPruneInterval:  time.Hour,
×
UNCOV
1065
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1066
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1067
                StrictZombiePruning: strictPruning,
×
UNCOV
1068
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1069
        })
×
UNCOV
1070
        if err != nil {
×
1071
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1072
        }
×
1073

UNCOV
1074
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1075
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1076
                RoutingGraph:       graphsession.NewRoutingGraph(dbs.GraphDB),
×
UNCOV
1077
                Chain:              cc.ChainIO,
×
UNCOV
1078
                Payer:              s.htlcSwitch,
×
UNCOV
1079
                Control:            s.controlTower,
×
UNCOV
1080
                MissionControl:     s.defaultMC,
×
UNCOV
1081
                SessionSource:      paymentSessionSource,
×
UNCOV
1082
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1083
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1084
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1085
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1086
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1087
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1088
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1089
        })
×
UNCOV
1090
        if err != nil {
×
1091
                return nil, fmt.Errorf("can't create router: %w", err)
×
1092
        }
×
1093

UNCOV
1094
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1095
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1096
        if err != nil {
×
1097
                return nil, err
×
1098
        }
×
UNCOV
1099
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1100
        if err != nil {
×
1101
                return nil, err
×
1102
        }
×
1103

UNCOV
1104
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1105

×
UNCOV
1106
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1107
                Graph:                 s.graphBuilder,
×
UNCOV
1108
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1109
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1110
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1111
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1112
                ChanSeries:            chanSeries,
×
UNCOV
1113
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1114
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1115
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1116
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1117
                        error) {
×
1118

×
1119
                        return s.genNodeAnnouncement(nil)
×
1120
                },
×
1121
                ProofMatureDelta:        0,
1122
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1123
                RetransmitTicker:        ticker.New(time.Minute * 30),
1124
                RebroadcastInterval:     time.Hour * 24,
1125
                WaitingProofStore:       waitingProofStore,
1126
                MessageStore:            gossipMessageStore,
1127
                AnnSigner:               s.nodeSigner,
1128
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1129
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1130
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1131
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1132
                MinimumBatchSize:        10,
1133
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1134
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1135
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1136
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1137
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1138
                IsAlias:                 aliasmgr.IsAlias,
1139
                SignAliasUpdate:         s.signAliasUpdate,
1140
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1141
                GetAlias:                s.aliasMgr.GetPeerAlias,
1142
                FindChannel:             s.findChannel,
1143
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1144
                ScidCloser:              scidCloserMan,
1145
        }, nodeKeyDesc)
1146

UNCOV
1147
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1148
        //nolint:ll
×
UNCOV
1149
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1150
                SelfPub:              nodeKeyDesc.PubKey,
×
UNCOV
1151
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1152
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
×
UNCOV
1153
                        *models.ChannelEdgePolicy) error) error {
×
UNCOV
1154

×
UNCOV
1155
                        return s.graphDB.ForEachNodeChannel(selfVertex,
×
UNCOV
1156
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
×
UNCOV
1157
                                        e *models.ChannelEdgePolicy,
×
UNCOV
1158
                                        _ *models.ChannelEdgePolicy) error {
×
UNCOV
1159

×
UNCOV
1160
                                        // NOTE: The invoked callback here may
×
UNCOV
1161
                                        // receive a nil channel policy.
×
UNCOV
1162
                                        return cb(c, e)
×
UNCOV
1163
                                },
×
1164
                        )
1165
                },
1166
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1167
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1168
                FetchChannel:              s.chanStateDB.FetchChannel,
1169
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1170
                        return s.graphBuilder.AddEdge(edge)
×
1171
                },
×
1172
        }
1173

UNCOV
1174
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1175
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1176
        )
×
UNCOV
1177
        if err != nil {
×
1178
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1179
                return nil, err
×
1180
        }
×
1181

UNCOV
1182
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1183
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1184
        )
×
UNCOV
1185
        if err != nil {
×
1186
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1187
                return nil, err
×
1188
        }
×
1189

UNCOV
1190
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1191
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1192
                s.implCfg.AuxSweeper,
×
UNCOV
1193
        )
×
UNCOV
1194

×
UNCOV
1195
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1196
                Signer:     cc.Wallet.Cfg.Signer,
×
UNCOV
1197
                Wallet:     cc.Wallet,
×
UNCOV
1198
                Estimator:  cc.FeeEstimator,
×
UNCOV
1199
                Notifier:   cc.ChainNotifier,
×
UNCOV
1200
                AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1201
        })
×
UNCOV
1202

×
UNCOV
1203
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1204
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1205
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1206
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1207
                ),
×
UNCOV
1208
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1209
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1210
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1211
                Notifier:             cc.ChainNotifier,
×
UNCOV
1212
                Store:                sweeperStore,
×
UNCOV
1213
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1214
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1215
                Aggregator:           aggregator,
×
UNCOV
1216
                Publisher:            s.txPublisher,
×
UNCOV
1217
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1218
        })
×
UNCOV
1219

×
UNCOV
1220
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1221
                ChainIO:             cc.ChainIO,
×
UNCOV
1222
                ConfDepth:           1,
×
UNCOV
1223
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1224
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1225
                Notifier:            cc.ChainNotifier,
×
UNCOV
1226
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1227
                Store:               utxnStore,
×
UNCOV
1228
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1229
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1230
        })
×
UNCOV
1231

×
UNCOV
1232
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1233
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1234
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1235
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1236
                // returned by CloseLink.
×
UNCOV
1237

×
UNCOV
1238
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1239
                // delivery script or target fee per kw because user input is not
×
UNCOV
1240
                // available when the remote peer closes the channel.
×
UNCOV
1241
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
×
UNCOV
1242
        }
×
1243

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

×
UNCOV
1248
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1249
                &contractcourt.BreachConfig{
×
UNCOV
1250
                        CloseLink: closeLink,
×
UNCOV
1251
                        DB:        s.chanStateDB,
×
UNCOV
1252
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1253
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1254
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1255
                        ),
×
UNCOV
1256
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1257
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1258
                        ContractBreaches:   contractBreaches,
×
UNCOV
1259
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1260
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1261
                                dbs.ChanStateDB,
×
UNCOV
1262
                        ),
×
UNCOV
1263
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1264
                },
×
UNCOV
1265
        )
×
UNCOV
1266

×
UNCOV
1267
        //nolint:ll
×
UNCOV
1268
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1269
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1270
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1271
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1272
                NewSweepAddr: func() ([]byte, error) {
×
1273
                        addr, err := newSweepPkScriptGen(
×
1274
                                cc.Wallet, netParams,
×
1275
                        )().Unpack()
×
1276
                        if err != nil {
×
1277
                                return nil, err
×
1278
                        }
×
1279

1280
                        return addr.DeliveryAddress, nil
×
1281
                },
1282
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1283
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1284
                        for _, msg := range msgs {
×
UNCOV
1285
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1286
                                if err != nil {
×
1287
                                        return err
×
1288
                                }
×
1289
                        }
UNCOV
1290
                        return nil
×
1291
                },
1292
                IncubateOutputs: func(chanPoint wire.OutPoint,
1293
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1294
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1295
                        broadcastHeight uint32,
UNCOV
1296
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1297

×
UNCOV
1298
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1299
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1300
                                broadcastHeight, deadlineHeight,
×
UNCOV
1301
                        )
×
UNCOV
1302
                },
×
1303
                PreimageDB:   s.witnessBeacon,
1304
                Notifier:     cc.ChainNotifier,
1305
                Mempool:      cc.MempoolNotifier,
1306
                Signer:       cc.Wallet.Cfg.Signer,
1307
                FeeEstimator: cc.FeeEstimator,
1308
                ChainIO:      cc.ChainIO,
UNCOV
1309
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1310
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1311
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1312
                        return nil
×
UNCOV
1313
                },
×
1314
                IsOurAddress: cc.Wallet.IsOurAddress,
1315
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1316
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1317

×
UNCOV
1318
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1319
                        // the event.
×
UNCOV
1320
                        finalErr := make(chan error, 1)
×
UNCOV
1321
                        processACK := func(brarErr error) {
×
UNCOV
1322
                                if brarErr != nil {
×
1323
                                        finalErr <- brarErr
×
1324
                                        return
×
1325
                                }
×
1326

1327
                                // If the BreachArbitrator successfully handled
1328
                                // the event, we can signal that the handoff
1329
                                // was successful.
UNCOV
1330
                                finalErr <- nil
×
1331
                        }
1332

UNCOV
1333
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1334
                                ChanPoint:         chanPoint,
×
UNCOV
1335
                                ProcessACK:        processACK,
×
UNCOV
1336
                                BreachRetribution: breachRet,
×
UNCOV
1337
                        }
×
UNCOV
1338

×
UNCOV
1339
                        // Send the contract breach event to the
×
UNCOV
1340
                        // BreachArbitrator.
×
UNCOV
1341
                        select {
×
UNCOV
1342
                        case contractBreaches <- event:
×
1343
                        case <-s.quit:
×
1344
                                return ErrServerShuttingDown
×
1345
                        }
1346

1347
                        // We'll wait for a final error to be available from
1348
                        // the BreachArbitrator.
UNCOV
1349
                        select {
×
UNCOV
1350
                        case err := <-finalErr:
×
UNCOV
1351
                                return err
×
1352
                        case <-s.quit:
×
1353
                                return ErrServerShuttingDown
×
1354
                        }
1355
                },
UNCOV
1356
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1357
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1358
                },
×
1359
                Sweeper:                       s.sweeper,
1360
                Registry:                      s.invoices,
1361
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1362
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1363
                OnionProcessor:                s.sphinx,
1364
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1365
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1366
                Clock:                         clock.NewDefaultClock(),
1367
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1368
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1369
                HtlcNotifier:                  s.htlcNotifier,
1370
                Budget:                        *s.cfg.Sweeper.Budget,
1371

1372
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1373
                QueryIncomingCircuit: func(
UNCOV
1374
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1375

×
UNCOV
1376
                        // Get the circuit map.
×
UNCOV
1377
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1378

×
UNCOV
1379
                        // Lookup the outgoing circuit.
×
UNCOV
1380
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1381
                        if pc == nil {
×
UNCOV
1382
                                return nil
×
1383
                        }
×
1384

1385
                        return &pc.Incoming
×
1386
                },
1387
                AuxLeafStore: implCfg.AuxLeafStore,
1388
                AuxSigner:    implCfg.AuxSigner,
1389
                AuxResolver:  implCfg.AuxContractResolver,
1390
        }, dbs.ChanStateDB)
1391

1392
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1393
        chainCfg := cfg.Bitcoin
×
UNCOV
1394
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1395
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1396

×
UNCOV
1397
        var chanIDSeed [32]byte
×
UNCOV
1398
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1399
                return nil, err
×
1400
        }
×
1401

1402
        // Wrap the `ReAddChannelEdge` method so that the funding manager can
1403
        // use it without depending on several layers of indirection.
NEW
1404
        reAssignSCID := func(aliasScID, newScID lnwire.ShortChannelID) (
×
1405
                *models.ChannelEdgePolicy, error) {
×
1406

×
1407
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
NEW
UNCOV
1408
                        aliasScID.ToUint64(),
×
UNCOV
1409
                )
×
UNCOV
1410
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
×
UNCOV
1411
                        // This is unlikely but there is a slim chance of this
×
UNCOV
1412
                        // being hit if lnd was killed via SIGKILL and the
×
UNCOV
1413
                        // funding manager was stepping through the delete
×
UNCOV
1414
                        // alias edge logic.
×
UNCOV
1415
                        return nil, nil
×
UNCOV
1416
                } else if err != nil {
×
1417
                        return nil, err
×
1418
                }
×
1419

1420
                // We create a new ChannelEdgeInfo with the new SCID.
NEW
1421
                newEdgeInfo := new(models.ChannelEdgeInfo)
×
NEW
1422
                *newEdgeInfo = *info
×
NEW
UNCOV
1423
                newEdgeInfo.ChannelID = newScID.ToUint64()
×
NEW
UNCOV
1424

×
NEW
1425
                // We also readd the channel policy from our side with the new
×
NEW
1426
                // short channel id so we grab our key to find our policy.
×
1427
                var ourKey [33]byte
×
1428
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
1429

×
UNCOV
1430
                var ourPolicy *models.ChannelEdgePolicy
×
1431
                if info != nil && info.NodeKey1Bytes == ourKey {
×
1432
                        ourPolicy = e1
×
1433
                } else {
×
1434
                        ourPolicy = e2
×
1435
                }
×
1436

1437
                if ourPolicy == nil {
×
NEW
1438
                        // We should always have our policy available. If that
×
NEW
1439
                        // is not the case there might be an error in the
×
NEW
1440
                        // ChannelUpdate msg logic so we return early.
×
NEW
1441
                        return nil, fmt.Errorf("edge policy not found")
×
1442
                }
×
1443

1444
                // Update the policy data, this invalidates the signature
1445
                // therefore we need to resign the data.
NEW
1446
                ourPolicy.ChannelID = newEdgeInfo.ChannelID
×
NEW
1447
                chanUpdate := netann.UnsignedChannelUpdateFromEdge(
×
NEW
1448
                        newEdgeInfo, ourPolicy,
×
1449
                )
×
NEW
1450

×
NEW
1451
                data, err := chanUpdate.DataToSign()
×
NEW
1452
                if err != nil {
×
NEW
1453
                        return nil, err
×
NEW
1454
                }
×
1455

NEW
UNCOV
1456
                nodeSig, err := cc.MsgSigner.SignMessage(
×
NEW
UNCOV
1457
                        nodeKeyDesc.KeyLocator, data, true,
×
NEW
UNCOV
1458
                )
×
NEW
UNCOV
1459
                if err != nil {
×
NEW
UNCOV
1460
                        return nil, err
×
NEW
UNCOV
1461
                }
×
1462

NEW
UNCOV
1463
                sig, err := lnwire.NewSigFromSignature(nodeSig)
×
NEW
UNCOV
1464
                if err != nil {
×
NEW
UNCOV
1465
                        return nil, err
×
NEW
UNCOV
1466
                }
×
NEW
UNCOV
1467
                ourPolicy.SetSigBytes(sig.ToSignatureBytes())
×
NEW
1468

×
NEW
1469
                // Delete the old edge information under the alias SCID and add
×
NEW
1470
                // the updated data with the new SCID.
×
NEW
UNCOV
1471
                err = s.graphDB.ReAddChannelEdge(
×
NEW
UNCOV
1472
                        aliasScID.ToUint64(), newEdgeInfo, ourPolicy,
×
NEW
UNCOV
1473
                )
×
NEW
UNCOV
1474

×
UNCOV
1475
                return ourPolicy, err
×
1476
        }
1477

1478
        // For the reservationTimeout and the zombieSweeperInterval different
1479
        // values are set in case we are in a dev environment so enhance test
1480
        // capacilities.
UNCOV
1481
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1482
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1483

×
UNCOV
1484
        // Get the development config for funding manager. If we are not in
×
UNCOV
1485
        // development mode, this would be nil.
×
UNCOV
1486
        var devCfg *funding.DevConfig
×
UNCOV
1487
        if lncfg.IsDevBuild() {
×
UNCOV
1488
                devCfg = &funding.DevConfig{
×
UNCOV
1489
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1490
                }
×
UNCOV
1491

×
UNCOV
1492
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1493
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1494

×
UNCOV
1495
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1496
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1497
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1498
        }
×
1499

1500
        //nolint:ll
UNCOV
1501
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1502
                Dev:                devCfg,
×
UNCOV
1503
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1504
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1505
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1506
                Wallet:             cc.Wallet,
×
UNCOV
1507
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1508
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1509
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1510
                },
×
1511
                Notifier:     cc.ChainNotifier,
1512
                ChannelDB:    s.chanStateDB,
1513
                FeeEstimator: cc.FeeEstimator,
1514
                SignMessage:  cc.MsgSigner.SignMessage,
1515
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1516
                        error) {
×
UNCOV
1517

×
UNCOV
1518
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1519
                },
×
1520
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1521
                NotifyWhenOnline:     s.NotifyWhenOnline,
1522
                TempChanIDSeed:       chanIDSeed,
1523
                FindChannel:          s.findChannel,
1524
                DefaultRoutingPolicy: cc.RoutingPolicy,
1525
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1526
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1527
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1528
                        // For large channels we increase the number
×
UNCOV
1529
                        // of confirmations we require for the
×
UNCOV
1530
                        // channel to be considered open. As it is
×
UNCOV
1531
                        // always the responder that gets to choose
×
UNCOV
1532
                        // value, the pushAmt is value being pushed
×
UNCOV
1533
                        // to us. This means we have more to lose
×
UNCOV
1534
                        // in the case this gets re-orged out, and
×
UNCOV
1535
                        // we will require more confirmations before
×
UNCOV
1536
                        // we consider it open.
×
UNCOV
1537

×
UNCOV
1538
                        // In case the user has explicitly specified
×
UNCOV
1539
                        // a default value for the number of
×
UNCOV
1540
                        // confirmations, we use it.
×
UNCOV
1541
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1542
                        if defaultConf != 0 {
×
UNCOV
1543
                                return defaultConf
×
UNCOV
1544
                        }
×
1545

1546
                        minConf := uint64(3)
×
1547
                        maxConf := uint64(6)
×
1548

×
1549
                        // If this is a wumbo channel, then we'll require the
×
1550
                        // max amount of confirmations.
×
1551
                        if chanAmt > MaxFundingAmount {
×
1552
                                return uint16(maxConf)
×
1553
                        }
×
1554

1555
                        // If not we return a value scaled linearly
1556
                        // between 3 and 6, depending on channel size.
1557
                        // TODO(halseth): Use 1 as minimum?
1558
                        maxChannelSize := uint64(
×
1559
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1560
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1561
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1562
                        if conf < minConf {
×
1563
                                conf = minConf
×
1564
                        }
×
1565
                        if conf > maxConf {
×
1566
                                conf = maxConf
×
1567
                        }
×
1568
                        return uint16(conf)
×
1569
                },
UNCOV
1570
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1571
                        // We scale the remote CSV delay (the time the
×
UNCOV
1572
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1573
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1574
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1575
                        // for channels of size MaxFundingAmount.
×
UNCOV
1576

×
UNCOV
1577
                        // In case the user has explicitly specified
×
UNCOV
1578
                        // a default value for the remote delay, we
×
UNCOV
1579
                        // use it.
×
UNCOV
1580
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1581
                        if defaultDelay > 0 {
×
UNCOV
1582
                                return defaultDelay
×
UNCOV
1583
                        }
×
1584

1585
                        // If this is a wumbo channel, then we'll require the
1586
                        // max value.
1587
                        if chanAmt > MaxFundingAmount {
×
1588
                                return maxRemoteDelay
×
1589
                        }
×
1590

1591
                        // If not we scale according to channel size.
1592
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1593
                                chanAmt / MaxFundingAmount)
×
1594
                        if delay < minRemoteDelay {
×
1595
                                delay = minRemoteDelay
×
1596
                        }
×
1597
                        if delay > maxRemoteDelay {
×
1598
                                delay = maxRemoteDelay
×
1599
                        }
×
1600
                        return delay
×
1601
                },
1602
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1603
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1604

×
UNCOV
1605
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1606
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1607
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1608
                        // we'll set false to prevent the server from continuing
×
UNCOV
1609
                        // to connect to this peer even if the number of
×
UNCOV
1610
                        // channels with this peer is zero.
×
UNCOV
1611
                        s.mu.Lock()
×
UNCOV
1612
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1613
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1614
                                s.persistentPeers[pubStr] = false
×
UNCOV
1615
                        }
×
UNCOV
1616
                        s.mu.Unlock()
×
UNCOV
1617

×
UNCOV
1618
                        // With that taken care of, we'll send this channel to
×
UNCOV
1619
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1620
                        return s.chainArb.WatchNewChannel(channel)
×
1621
                },
UNCOV
1622
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1623
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1624
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1625
                },
×
1626
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1627
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1628

×
UNCOV
1629
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1630
                        // at least 1% of the total channel capacity at all
×
UNCOV
1631
                        // times. If this value ends up dipping below the dust
×
UNCOV
1632
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1633
                        // reserve as required by BOLT #2.
×
UNCOV
1634
                        reserve := chanAmt / 100
×
UNCOV
1635
                        if reserve < dustLimit {
×
UNCOV
1636
                                reserve = dustLimit
×
UNCOV
1637
                        }
×
1638

UNCOV
1639
                        return reserve
×
1640
                },
UNCOV
1641
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1642
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1643
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1644
                        // required reserve.
×
UNCOV
1645
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1646
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1647
                },
×
UNCOV
1648
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1649
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1650
                                return cfg.DefaultRemoteMaxHtlcs
×
1651
                        }
×
1652

1653
                        // By default, we'll permit them to utilize the full
1654
                        // channel bandwidth.
1655
                        return uint16(input.MaxHTLCNumber / 2)
×
1656
                },
1657
                ZombieSweeperInterval:         zombieSweeperInterval,
1658
                ReservationTimeout:            reservationTimeout,
1659
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1660
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1661
                MaxPendingChannels:            cfg.MaxPendingChannels,
1662
                RejectPush:                    cfg.RejectPush,
1663
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1664
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1665
                OpenChannelPredicate:          chanPredicate,
1666
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1667
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1668
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1669
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1670
                ReAssignSCID:         reAssignSCID,
1671
                AliasManager:         s.aliasMgr,
1672
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1673
                AuxFundingController: implCfg.AuxFundingController,
1674
                AuxSigner:            implCfg.AuxSigner,
1675
                AuxResolver:          implCfg.AuxContractResolver,
1676
        })
UNCOV
1677
        if err != nil {
×
1678
                return nil, err
×
1679
        }
×
1680

1681
        // Next, we'll assemble the sub-system that will maintain an on-disk
1682
        // static backup of the latest channel state.
UNCOV
1683
        chanNotifier := &channelNotifier{
×
UNCOV
1684
                chanNotifier: s.channelNotifier,
×
UNCOV
1685
                addrs:        s.addrSource,
×
UNCOV
1686
        }
×
UNCOV
1687
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
×
UNCOV
1688
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1689
                s.chanStateDB, s.addrSource,
×
UNCOV
1690
        )
×
UNCOV
1691
        if err != nil {
×
1692
                return nil, err
×
1693
        }
×
UNCOV
1694
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1695
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1696
        )
×
UNCOV
1697
        if err != nil {
×
1698
                return nil, err
×
1699
        }
×
1700

1701
        // Assemble a peer notifier which will provide clients with subscriptions
1702
        // to peer online and offline events.
UNCOV
1703
        s.peerNotifier = peernotifier.New()
×
UNCOV
1704

×
UNCOV
1705
        // Create a channel event store which monitors all open channels.
×
UNCOV
1706
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1707
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1708
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1709
                },
×
UNCOV
1710
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1711
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1712
                },
×
1713
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1714
                Clock:           clock.NewDefaultClock(),
1715
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1716
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1717
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1718
        })
1719

UNCOV
1720
        if cfg.WtClient.Active {
×
UNCOV
1721
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1722
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1723

×
UNCOV
1724
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1725
                // protocol operations on sat/kw.
×
UNCOV
1726
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1727
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1728
                )
×
UNCOV
1729

×
UNCOV
1730
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1731

×
UNCOV
1732
                if err := policy.Validate(); err != nil {
×
1733
                        return nil, err
×
1734
                }
×
1735

1736
                // authDial is the wrapper around the btrontide.Dial for the
1737
                // watchtower.
UNCOV
1738
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1739
                        netAddr *lnwire.NetAddress,
×
UNCOV
1740
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1741

×
UNCOV
1742
                        return brontide.Dial(
×
UNCOV
1743
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1744
                        )
×
UNCOV
1745
                }
×
1746

1747
                // buildBreachRetribution is a call-back that can be used to
1748
                // query the BreachRetribution info and channel type given a
1749
                // channel ID and commitment height.
UNCOV
1750
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1751
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1752
                        channeldb.ChannelType, error) {
×
UNCOV
1753

×
UNCOV
1754
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1755
                                nil, chanID,
×
UNCOV
1756
                        )
×
UNCOV
1757
                        if err != nil {
×
1758
                                return nil, 0, err
×
1759
                        }
×
1760

UNCOV
1761
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1762
                                channel, commitHeight, 0, nil,
×
UNCOV
1763
                                implCfg.AuxLeafStore,
×
UNCOV
1764
                                implCfg.AuxContractResolver,
×
UNCOV
1765
                        )
×
UNCOV
1766
                        if err != nil {
×
1767
                                return nil, 0, err
×
1768
                        }
×
1769

UNCOV
1770
                        return br, channel.ChanType, nil
×
1771
                }
1772

UNCOV
1773
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1774

×
UNCOV
1775
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1776
                // signalling support for anchor channels.
×
UNCOV
1777
                anchorPolicy := policy
×
UNCOV
1778
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1779

×
UNCOV
1780
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1781
                // signalling support for taproot channels.
×
UNCOV
1782
                taprootPolicy := policy
×
UNCOV
1783
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1784
                        blob.FlagTaprootChannel,
×
UNCOV
1785
                )
×
UNCOV
1786

×
UNCOV
1787
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1788
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1789
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1790
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1791
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1792
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1793
                                error) {
×
UNCOV
1794

×
UNCOV
1795
                                return s.channelNotifier.
×
UNCOV
1796
                                        SubscribeChannelEvents()
×
UNCOV
1797
                        },
×
1798
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1799
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1800
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1801
                                        cc.Wallet, netParams,
×
UNCOV
1802
                                )().Unpack()
×
UNCOV
1803
                                if err != nil {
×
1804
                                        return nil, err
×
1805
                                }
×
1806

UNCOV
1807
                                return addr.DeliveryAddress, nil
×
1808
                        },
1809
                        SecretKeyRing:      s.cc.KeyRing,
1810
                        Dial:               cfg.net.Dial,
1811
                        AuthDial:           authDial,
1812
                        DB:                 dbs.TowerClientDB,
1813
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1814
                        MinBackoff:         10 * time.Second,
1815
                        MaxBackoff:         5 * time.Minute,
1816
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1817
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1818
                if err != nil {
×
1819
                        return nil, err
×
1820
                }
×
1821
        }
1822

UNCOV
1823
        if len(cfg.ExternalHosts) != 0 {
×
1824
                advertisedIPs := make(map[string]struct{})
×
1825
                for _, addr := range s.currentNodeAnn.Addresses {
×
1826
                        advertisedIPs[addr.String()] = struct{}{}
×
1827
                }
×
1828

1829
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1830
                        Hosts:         cfg.ExternalHosts,
×
1831
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1832
                        LookupHost: func(host string) (net.Addr, error) {
×
1833
                                return lncfg.ParseAddressString(
×
1834
                                        host, strconv.Itoa(defaultPeerPort),
×
1835
                                        cfg.net.ResolveTCPAddr,
×
1836
                                )
×
1837
                        },
×
1838
                        AdvertisedIPs: advertisedIPs,
1839
                        AnnounceNewIPs: netann.IPAnnouncer(
1840
                                func(modifier ...netann.NodeAnnModifier) (
1841
                                        lnwire.NodeAnnouncement, error) {
×
1842

×
1843
                                        return s.genNodeAnnouncement(
×
1844
                                                nil, modifier...,
×
1845
                                        )
×
1846
                                }),
×
1847
                })
1848
        }
1849

1850
        // Create liveness monitor.
UNCOV
1851
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1852

×
UNCOV
1853
        // Create the connection manager which will be responsible for
×
UNCOV
1854
        // maintaining persistent outbound connections and also accepting new
×
UNCOV
1855
        // incoming connections
×
UNCOV
1856
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1857
                Listeners:      listeners,
×
UNCOV
1858
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1859
                RetryDuration:  time.Second * 5,
×
UNCOV
1860
                TargetOutbound: 100,
×
UNCOV
1861
                Dial: noiseDial(
×
UNCOV
1862
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1863
                ),
×
UNCOV
1864
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1865
        })
×
UNCOV
1866
        if err != nil {
×
1867
                return nil, err
×
1868
        }
×
UNCOV
1869
        s.connMgr = cmgr
×
UNCOV
1870

×
UNCOV
1871
        // Finally, register the subsystems in blockbeat.
×
UNCOV
1872
        s.registerBlockConsumers()
×
UNCOV
1873

×
UNCOV
1874
        return s, nil
×
1875
}
1876

1877
// UpdateRoutingConfig is a callback function to update the routing config
1878
// values in the main cfg.
UNCOV
1879
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1880
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1881

×
UNCOV
1882
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1883
        case routing.AprioriConfig:
×
UNCOV
1884
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1885
                        routing.AprioriEstimatorName
×
UNCOV
1886

×
UNCOV
1887
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1888
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1889
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1890
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1891
                targetCfg.HopProbability = c.AprioriHopProbability
×
1892

UNCOV
1893
        case routing.BimodalConfig:
×
UNCOV
1894
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1895
                        routing.BimodalEstimatorName
×
UNCOV
1896

×
UNCOV
1897
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1898
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1899
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1900
                targetCfg.DecayTime = c.BimodalDecayTime
×
1901
        }
1902

UNCOV
1903
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1904
}
1905

1906
// registerBlockConsumers registers the subsystems that consume block events.
1907
// By calling `RegisterQueue`, a list of subsystems are registered in the
1908
// blockbeat for block notifications. When a new block arrives, the subsystems
1909
// in the same queue are notified sequentially, and different queues are
1910
// notified concurrently.
1911
//
1912
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1913
// a new `RegisterQueue` call.
UNCOV
1914
func (s *server) registerBlockConsumers() {
×
UNCOV
1915
        // In this queue, when a new block arrives, it will be received and
×
UNCOV
1916
        // processed in this order: chainArb -> sweeper -> txPublisher.
×
UNCOV
1917
        consumers := []chainio.Consumer{
×
UNCOV
1918
                s.chainArb,
×
UNCOV
1919
                s.sweeper,
×
UNCOV
1920
                s.txPublisher,
×
UNCOV
1921
        }
×
UNCOV
1922
        s.blockbeatDispatcher.RegisterQueue(consumers)
×
UNCOV
1923
}
×
1924

1925
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1926
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1927
// may differ from what is on disk.
1928
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1929
        error) {
×
UNCOV
1930

×
UNCOV
1931
        data, err := u.DataToSign()
×
UNCOV
1932
        if err != nil {
×
1933
                return nil, err
×
1934
        }
×
1935

UNCOV
1936
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1937
}
1938

1939
// createLivenessMonitor creates a set of health checks using our configured
1940
// values and uses these checks to create a liveness monitor. Available
1941
// health checks,
1942
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1943
//   - diskCheck
1944
//   - tlsHealthCheck
1945
//   - torController, only created when tor is enabled.
1946
//
1947
// If a health check has been disabled by setting attempts to 0, our monitor
1948
// will not run it.
1949
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
1950
        leaderElector cluster.LeaderElector) {
×
UNCOV
1951

×
UNCOV
1952
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
1953
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1954
                srvrLog.Info("Disabling chain backend checks for " +
×
1955
                        "nochainbackend mode")
×
1956

×
1957
                chainBackendAttempts = 0
×
1958
        }
×
1959

UNCOV
1960
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1961
                "chain backend",
×
UNCOV
1962
                cc.HealthCheck,
×
UNCOV
1963
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1964
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
1965
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1966
                chainBackendAttempts,
×
UNCOV
1967
        )
×
UNCOV
1968

×
UNCOV
1969
        diskCheck := healthcheck.NewObservation(
×
UNCOV
1970
                "disk space",
×
UNCOV
1971
                func() error {
×
1972
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1973
                                cfg.LndDir,
×
1974
                        )
×
1975
                        if err != nil {
×
1976
                                return err
×
1977
                        }
×
1978

1979
                        // If we have more free space than we require,
1980
                        // we return a nil error.
1981
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1982
                                return nil
×
1983
                        }
×
1984

1985
                        return fmt.Errorf("require: %v free space, got: %v",
×
1986
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1987
                                free)
×
1988
                },
1989
                cfg.HealthChecks.DiskCheck.Interval,
1990
                cfg.HealthChecks.DiskCheck.Timeout,
1991
                cfg.HealthChecks.DiskCheck.Backoff,
1992
                cfg.HealthChecks.DiskCheck.Attempts,
1993
        )
1994

UNCOV
1995
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
1996
                "tls",
×
UNCOV
1997
                func() error {
×
1998
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1999
                                s.cc.KeyRing,
×
2000
                        )
×
2001
                        if err != nil {
×
2002
                                return err
×
2003
                        }
×
2004
                        if expired {
×
2005
                                return fmt.Errorf("TLS certificate is "+
×
2006
                                        "expired as of %v", expTime)
×
2007
                        }
×
2008

2009
                        // If the certificate is not outdated, no error needs
2010
                        // to be returned
2011
                        return nil
×
2012
                },
2013
                cfg.HealthChecks.TLSCheck.Interval,
2014
                cfg.HealthChecks.TLSCheck.Timeout,
2015
                cfg.HealthChecks.TLSCheck.Backoff,
2016
                cfg.HealthChecks.TLSCheck.Attempts,
2017
        )
2018

UNCOV
2019
        checks := []*healthcheck.Observation{
×
UNCOV
2020
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
2021
        }
×
UNCOV
2022

×
UNCOV
2023
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
2024
        if s.torController != nil {
×
2025
                torConnectionCheck := healthcheck.NewObservation(
×
2026
                        "tor connection",
×
2027
                        func() error {
×
2028
                                return healthcheck.CheckTorServiceStatus(
×
2029
                                        s.torController,
×
2030
                                        s.createNewHiddenService,
×
2031
                                )
×
2032
                        },
×
2033
                        cfg.HealthChecks.TorConnection.Interval,
2034
                        cfg.HealthChecks.TorConnection.Timeout,
2035
                        cfg.HealthChecks.TorConnection.Backoff,
2036
                        cfg.HealthChecks.TorConnection.Attempts,
2037
                )
2038
                checks = append(checks, torConnectionCheck)
×
2039
        }
2040

2041
        // If remote signing is enabled, add the healthcheck for the remote
2042
        // signing RPC interface.
UNCOV
2043
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
2044
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
2045
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
2046
                // returns exactly on time.
×
UNCOV
2047
                overhead := time.Millisecond * 10
×
UNCOV
2048

×
UNCOV
2049
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
2050
                        "remote signer connection",
×
UNCOV
2051
                        rpcwallet.HealthCheck(
×
UNCOV
2052
                                s.cfg.RemoteSigner,
×
UNCOV
2053

×
UNCOV
2054
                                // For the health check we might to be even
×
UNCOV
2055
                                // stricter than the initial/normal connect, so
×
UNCOV
2056
                                // we use the health check timeout here.
×
UNCOV
2057
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
2058
                        ),
×
UNCOV
2059
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
2060
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
2061
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
2062
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
2063
                )
×
UNCOV
2064
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
2065
        }
×
2066

2067
        // If we have a leader elector, we add a health check to ensure we are
2068
        // still the leader. During normal operation, we should always be the
2069
        // leader, but there are circumstances where this may change, such as
2070
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
2071
        if leaderElector != nil {
×
2072
                leaderCheck := healthcheck.NewObservation(
×
2073
                        "leader status",
×
2074
                        func() error {
×
2075
                                // Check if we are still the leader. Note that
×
2076
                                // we don't need to use a timeout context here
×
2077
                                // as the healthcheck observer will handle the
×
2078
                                // timeout case for us.
×
2079
                                timeoutCtx, cancel := context.WithTimeout(
×
2080
                                        context.Background(),
×
2081
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2082
                                )
×
2083
                                defer cancel()
×
2084

×
2085
                                leader, err := leaderElector.IsLeader(
×
2086
                                        timeoutCtx,
×
2087
                                )
×
2088
                                if err != nil {
×
2089
                                        return fmt.Errorf("unable to check if "+
×
2090
                                                "still leader: %v", err)
×
2091
                                }
×
2092

2093
                                if !leader {
×
2094
                                        srvrLog.Debug("Not the current leader")
×
2095
                                        return fmt.Errorf("not the current " +
×
2096
                                                "leader")
×
2097
                                }
×
2098

2099
                                return nil
×
2100
                        },
2101
                        cfg.HealthChecks.LeaderCheck.Interval,
2102
                        cfg.HealthChecks.LeaderCheck.Timeout,
2103
                        cfg.HealthChecks.LeaderCheck.Backoff,
2104
                        cfg.HealthChecks.LeaderCheck.Attempts,
2105
                )
2106

2107
                checks = append(checks, leaderCheck)
×
2108
        }
2109

2110
        // If we have not disabled all of our health checks, we create a
2111
        // liveness monitor with our configured checks.
UNCOV
2112
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2113
                &healthcheck.Config{
×
UNCOV
2114
                        Checks:   checks,
×
UNCOV
2115
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2116
                },
×
UNCOV
2117
        )
×
2118
}
2119

2120
// Started returns true if the server has been started, and false otherwise.
2121
// NOTE: This function is safe for concurrent access.
UNCOV
2122
func (s *server) Started() bool {
×
UNCOV
2123
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2124
}
×
2125

2126
// cleaner is used to aggregate "cleanup" functions during an operation that
2127
// starts several subsystems. In case one of the subsystem fails to start
2128
// and a proper resource cleanup is required, the "run" method achieves this
2129
// by running all these added "cleanup" functions.
2130
type cleaner []func() error
2131

2132
// add is used to add a cleanup function to be called when
2133
// the run function is executed.
UNCOV
2134
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2135
        return append(c, cleanup)
×
UNCOV
2136
}
×
2137

2138
// run is used to run all the previousely added cleanup functions.
2139
func (c cleaner) run() {
×
2140
        for i := len(c) - 1; i >= 0; i-- {
×
2141
                if err := c[i](); err != nil {
×
2142
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2143
                }
×
2144
        }
2145
}
2146

2147
// startLowLevelServices starts the low-level services of the server. These
2148
// services must be started successfully before running the main server. The
2149
// services are,
2150
// 1. the chain notifier.
2151
//
2152
// TODO(yy): identify and add more low-level services here.
UNCOV
2153
func (s *server) startLowLevelServices() error {
×
UNCOV
2154
        var startErr error
×
UNCOV
2155

×
UNCOV
2156
        cleanup := cleaner{}
×
UNCOV
2157

×
UNCOV
2158
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2159
        if err := s.cc.ChainNotifier.Start(); err != nil {
×
2160
                startErr = err
×
2161
        }
×
2162

UNCOV
2163
        if startErr != nil {
×
2164
                cleanup.run()
×
2165
        }
×
2166

UNCOV
2167
        return startErr
×
2168
}
2169

2170
// Start starts the main daemon server, all requested listeners, and any helper
2171
// goroutines.
2172
// NOTE: This function is safe for concurrent access.
2173
//
2174
//nolint:funlen
UNCOV
2175
func (s *server) Start() error {
×
UNCOV
2176
        // Get the current blockbeat.
×
UNCOV
2177
        beat, err := s.getStartingBeat()
×
UNCOV
2178
        if err != nil {
×
2179
                return err
×
2180
        }
×
2181

UNCOV
2182
        var startErr error
×
UNCOV
2183

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

×
UNCOV
2189
        s.start.Do(func() {
×
UNCOV
2190
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2191
                if err := s.customMessageServer.Start(); err != nil {
×
2192
                        startErr = err
×
2193
                        return
×
2194
                }
×
2195

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

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

2212
                // Start the notification server. This is used so channel
2213
                // management goroutines can be notified when a funding
2214
                // transaction reaches a sufficient number of confirmations, or
2215
                // when the input for the funding transaction is spent in an
2216
                // attempt at an uncooperative close by the counterparty.
UNCOV
2217
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2218
                if err := s.sigPool.Start(); err != nil {
×
2219
                        startErr = err
×
2220
                        return
×
2221
                }
×
2222

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

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

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

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

UNCOV
2247
                cleanup = cleanup.add(func() error {
×
2248
                        return s.peerNotifier.Stop()
×
2249
                })
×
UNCOV
2250
                if err := s.peerNotifier.Start(); err != nil {
×
2251
                        startErr = err
×
2252
                        return
×
2253
                }
×
2254

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

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

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

UNCOV
2275
                cleanup = cleanup.add(s.sweeper.Stop)
×
UNCOV
2276
                if err := s.sweeper.Start(beat); err != nil {
×
2277
                        startErr = err
×
2278
                        return
×
2279
                }
×
2280

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

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

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

2299
                // htlcSwitch must be started before chainArb since the latter
2300
                // relies on htlcSwitch to deliver resolution message upon
2301
                // start.
UNCOV
2302
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2303
                if err := s.htlcSwitch.Start(); err != nil {
×
2304
                        startErr = err
×
2305
                        return
×
2306
                }
×
2307

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

UNCOV
2314
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
×
UNCOV
2315
                if err := s.invoiceHtlcModifier.Start(); err != nil {
×
2316
                        startErr = err
×
2317
                        return
×
2318
                }
×
2319

UNCOV
2320
                cleanup = cleanup.add(s.chainArb.Stop)
×
UNCOV
2321
                if err := s.chainArb.Start(beat); err != nil {
×
2322
                        startErr = err
×
2323
                        return
×
2324
                }
×
2325

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

UNCOV
2332
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2333
                if err := s.chanRouter.Start(); err != nil {
×
2334
                        startErr = err
×
2335
                        return
×
2336
                }
×
2337
                // The authGossiper depends on the chanRouter and therefore
2338
                // should be started after it.
UNCOV
2339
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2340
                if err := s.authGossiper.Start(); err != nil {
×
2341
                        startErr = err
×
2342
                        return
×
2343
                }
×
2344

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

UNCOV
2351
                cleanup = cleanup.add(s.sphinx.Stop)
×
UNCOV
2352
                if err := s.sphinx.Start(); err != nil {
×
2353
                        startErr = err
×
2354
                        return
×
2355
                }
×
2356

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

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

UNCOV
2369
                cleanup.add(func() error {
×
2370
                        s.missionController.StopStoreTickers()
×
2371
                        return nil
×
2372
                })
×
UNCOV
2373
                s.missionController.RunStoreTickers()
×
UNCOV
2374

×
UNCOV
2375
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2376
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2377
                // that have all the information we need to handle channel
×
UNCOV
2378
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2379
                chanRestorer := &chanDBRestorer{
×
UNCOV
2380
                        db:         s.chanStateDB,
×
UNCOV
2381
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2382
                        chainArb:   s.chainArb,
×
UNCOV
2383
                }
×
UNCOV
2384
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2385
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2386
                                s.chansToRestore.PackedSingleChanBackups,
×
2387
                                s.cc.KeyRing, chanRestorer, s,
×
2388
                        )
×
2389
                        if err != nil {
×
2390
                                startErr = fmt.Errorf("unable to unpack single "+
×
2391
                                        "backups: %v", err)
×
2392
                                return
×
2393
                        }
×
2394
                }
UNCOV
2395
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2396
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2397
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2398
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2399
                        )
×
UNCOV
2400
                        if err != nil {
×
2401
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2402
                                        "backup: %v", err)
×
2403
                                return
×
2404
                        }
×
2405
                }
2406

2407
                // chanSubSwapper must be started after the `channelNotifier`
2408
                // because it depends on channel events as a synchronization
2409
                // point.
UNCOV
2410
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2411
                if err := s.chanSubSwapper.Start(); err != nil {
×
2412
                        startErr = err
×
2413
                        return
×
2414
                }
×
2415

UNCOV
2416
                if s.torController != nil {
×
2417
                        cleanup = cleanup.add(s.torController.Stop)
×
2418
                        if err := s.createNewHiddenService(); err != nil {
×
2419
                                startErr = err
×
2420
                                return
×
2421
                        }
×
2422
                }
2423

UNCOV
2424
                if s.natTraversal != nil {
×
2425
                        s.wg.Add(1)
×
2426
                        go s.watchExternalIP()
×
2427
                }
×
2428

2429
                // Start connmgr last to prevent connections before init.
UNCOV
2430
                cleanup = cleanup.add(func() error {
×
2431
                        s.connMgr.Stop()
×
2432
                        return nil
×
2433
                })
×
UNCOV
2434
                s.connMgr.Start()
×
UNCOV
2435

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

UNCOV
2455
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2456
                                IdentityKey: parsedPubkey,
×
UNCOV
2457
                                Address:     addr,
×
UNCOV
2458
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2459
                        }
×
UNCOV
2460

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

2473
                // Subscribe to NodeAnnouncements that advertise new addresses
2474
                // our persistent peers.
UNCOV
2475
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2476
                        startErr = err
×
2477
                        return
×
2478
                }
×
2479

2480
                // With all the relevant sub-systems started, we'll now attempt
2481
                // to establish persistent connections to our direct channel
2482
                // collaborators within the network. Before doing so however,
2483
                // we'll prune our set of link nodes found within the database
2484
                // to ensure we don't reconnect to any nodes we no longer have
2485
                // open channels with.
UNCOV
2486
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2487
                        startErr = err
×
2488
                        return
×
2489
                }
×
UNCOV
2490
                if err := s.establishPersistentConnections(); err != nil {
×
2491
                        startErr = err
×
2492
                        return
×
2493
                }
×
2494

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

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

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

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

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

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

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

2556
                        s.wg.Add(1)
×
2557
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
UNCOV
2558
                } else {
×
UNCOV
2559
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2560
                }
×
2561

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

2573
                // Set the active flag now that we've completed the full
2574
                // startup.
UNCOV
2575
                atomic.StoreInt32(&s.active, 1)
×
2576
        })
2577

UNCOV
2578
        if startErr != nil {
×
2579
                cleanup.run()
×
2580
        }
×
UNCOV
2581
        return startErr
×
2582
}
2583

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

×
UNCOV
2592
                close(s.quit)
×
UNCOV
2593

×
UNCOV
2594
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2595
                s.connMgr.Stop()
×
UNCOV
2596

×
UNCOV
2597
                // Stop dispatching blocks to other systems immediately.
×
UNCOV
2598
                s.blockbeatDispatcher.Stop()
×
UNCOV
2599

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

2659
                // Update channel.backup file. Make sure to do it before
2660
                // stopping chanSubSwapper.
UNCOV
2661
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2662
                        s.chanStateDB, s.addrSource,
×
UNCOV
2663
                )
×
UNCOV
2664
                if err != nil {
×
2665
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2666
                                err)
×
UNCOV
2667
                } else {
×
UNCOV
2668
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2669
                        if err != nil {
×
UNCOV
2670
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2671
                                        "backup failed: %v", err)
×
UNCOV
2672
                        }
×
2673
                }
2674

UNCOV
2675
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2676
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2677
                }
×
UNCOV
2678
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2679
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2680
                }
×
UNCOV
2681
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2682
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2683
                                err)
×
2684
                }
×
UNCOV
2685
                if err := s.chanEventStore.Stop(); err != nil {
×
2686
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2687
                                err)
×
2688
                }
×
UNCOV
2689
                s.missionController.StopStoreTickers()
×
UNCOV
2690

×
UNCOV
2691
                // Disconnect from each active peers to ensure that
×
UNCOV
2692
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2693
                for _, peer := range s.Peers() {
×
UNCOV
2694
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2695
                        if err != nil {
×
2696
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2697
                                        "received error: %v", peer.IdentityKey(),
×
2698
                                        err,
×
2699
                                )
×
2700
                        }
×
2701
                }
2702

2703
                // Now that all connections have been torn down, stop the tower
2704
                // client which will reliably flush all queued states to the
2705
                // tower. If this is halted for any reason, the force quit timer
2706
                // will kick in and abort to allow this method to return.
UNCOV
2707
                if s.towerClientMgr != nil {
×
UNCOV
2708
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2709
                                srvrLog.Warnf("Unable to shut down tower "+
×
2710
                                        "client manager: %v", err)
×
2711
                        }
×
2712
                }
2713

UNCOV
2714
                if s.hostAnn != nil {
×
2715
                        if err := s.hostAnn.Stop(); err != nil {
×
2716
                                srvrLog.Warnf("unable to shut down host "+
×
2717
                                        "annoucner: %v", err)
×
2718
                        }
×
2719
                }
2720

UNCOV
2721
                if s.livenessMonitor != nil {
×
UNCOV
2722
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2723
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2724
                                        "monitor: %v", err)
×
2725
                        }
×
2726
                }
2727

2728
                // Wait for all lingering goroutines to quit.
UNCOV
2729
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2730
                s.wg.Wait()
×
UNCOV
2731

×
UNCOV
2732
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2733
                s.sigPool.Stop()
×
UNCOV
2734
                s.writePool.Stop()
×
UNCOV
2735
                s.readPool.Stop()
×
2736
        })
2737

UNCOV
2738
        return nil
×
2739
}
2740

2741
// Stopped returns true if the server has been instructed to shutdown.
2742
// NOTE: This function is safe for concurrent access.
UNCOV
2743
func (s *server) Stopped() bool {
×
UNCOV
2744
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2745
}
×
2746

2747
// configurePortForwarding attempts to set up port forwarding for the different
2748
// ports that the server will be listening on.
2749
//
2750
// NOTE: This should only be used when using some kind of NAT traversal to
2751
// automatically set up forwarding rules.
2752
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2753
        ip, err := s.natTraversal.ExternalIP()
×
2754
        if err != nil {
×
2755
                return nil, err
×
2756
        }
×
2757
        s.lastDetectedIP = ip
×
2758

×
2759
        externalIPs := make([]string, 0, len(ports))
×
2760
        for _, port := range ports {
×
2761
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2762
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2763
                        continue
×
2764
                }
2765

2766
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2767
                externalIPs = append(externalIPs, hostIP)
×
2768
        }
2769

2770
        return externalIPs, nil
×
2771
}
2772

2773
// removePortForwarding attempts to clear the forwarding rules for the different
2774
// ports the server is currently listening on.
2775
//
2776
// NOTE: This should only be used when using some kind of NAT traversal to
2777
// automatically set up forwarding rules.
2778
func (s *server) removePortForwarding() {
×
2779
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2780
        for _, port := range forwardedPorts {
×
2781
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2782
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2783
                                "port %d: %v", port, err)
×
2784
                }
×
2785
        }
2786
}
2787

2788
// watchExternalIP continuously checks for an updated external IP address every
2789
// 15 minutes. Once a new IP address has been detected, it will automatically
2790
// handle port forwarding rules and send updated node announcements to the
2791
// currently connected peers.
2792
//
2793
// NOTE: This MUST be run as a goroutine.
2794
func (s *server) watchExternalIP() {
×
2795
        defer s.wg.Done()
×
2796

×
2797
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2798
        // up by the server.
×
2799
        defer s.removePortForwarding()
×
2800

×
2801
        // Keep track of the external IPs set by the user to avoid replacing
×
2802
        // them when detecting a new IP.
×
2803
        ipsSetByUser := make(map[string]struct{})
×
2804
        for _, ip := range s.cfg.ExternalIPs {
×
2805
                ipsSetByUser[ip.String()] = struct{}{}
×
2806
        }
×
2807

2808
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2809

×
2810
        ticker := time.NewTicker(15 * time.Minute)
×
2811
        defer ticker.Stop()
×
2812
out:
×
2813
        for {
×
2814
                select {
×
2815
                case <-ticker.C:
×
2816
                        // We'll start off by making sure a new IP address has
×
2817
                        // been detected.
×
2818
                        ip, err := s.natTraversal.ExternalIP()
×
2819
                        if err != nil {
×
2820
                                srvrLog.Debugf("Unable to retrieve the "+
×
2821
                                        "external IP address: %v", err)
×
2822
                                continue
×
2823
                        }
2824

2825
                        // Periodically renew the NAT port forwarding.
2826
                        for _, port := range forwardedPorts {
×
2827
                                err := s.natTraversal.AddPortMapping(port)
×
2828
                                if err != nil {
×
2829
                                        srvrLog.Warnf("Unable to automatically "+
×
2830
                                                "re-create port forwarding using %s: %v",
×
2831
                                                s.natTraversal.Name(), err)
×
2832
                                } else {
×
2833
                                        srvrLog.Debugf("Automatically re-created "+
×
2834
                                                "forwarding for port %d using %s to "+
×
2835
                                                "advertise external IP",
×
2836
                                                port, s.natTraversal.Name())
×
2837
                                }
×
2838
                        }
2839

2840
                        if ip.Equal(s.lastDetectedIP) {
×
2841
                                continue
×
2842
                        }
2843

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

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

2861
                                newAddrs = append(newAddrs, addr)
×
2862
                        }
2863

2864
                        // Skip the update if we weren't able to resolve any of
2865
                        // the new addresses.
2866
                        if len(newAddrs) == 0 {
×
2867
                                srvrLog.Debug("Skipping node announcement " +
×
2868
                                        "update due to not being able to " +
×
2869
                                        "resolve any new addresses")
×
2870
                                continue
×
2871
                        }
2872

2873
                        // Now, we'll need to update the addresses in our node's
2874
                        // announcement in order to propagate the update
2875
                        // throughout the network. We'll only include addresses
2876
                        // that have a different IP from the previous one, as
2877
                        // the previous IP is no longer valid.
2878
                        currentNodeAnn := s.getNodeAnnouncement()
×
2879

×
2880
                        for _, addr := range currentNodeAnn.Addresses {
×
2881
                                host, _, err := net.SplitHostPort(addr.String())
×
2882
                                if err != nil {
×
2883
                                        srvrLog.Debugf("Unable to determine "+
×
2884
                                                "host from address %v: %v",
×
2885
                                                addr, err)
×
2886
                                        continue
×
2887
                                }
2888

2889
                                // We'll also make sure to include external IPs
2890
                                // set manually by the user.
2891
                                _, setByUser := ipsSetByUser[addr.String()]
×
2892
                                if setByUser || host != s.lastDetectedIP.String() {
×
2893
                                        newAddrs = append(newAddrs, addr)
×
2894
                                }
×
2895
                        }
2896

2897
                        // Then, we'll generate a new timestamped node
2898
                        // announcement with the updated addresses and broadcast
2899
                        // it to our peers.
2900
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2901
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2902
                        )
×
2903
                        if err != nil {
×
2904
                                srvrLog.Debugf("Unable to generate new node "+
×
2905
                                        "announcement: %v", err)
×
2906
                                continue
×
2907
                        }
2908

2909
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2910
                        if err != nil {
×
2911
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2912
                                        "announcement to peers: %v", err)
×
2913
                                continue
×
2914
                        }
2915

2916
                        // Finally, update the last IP seen to the current one.
2917
                        s.lastDetectedIP = ip
×
2918
                case <-s.quit:
×
2919
                        break out
×
2920
                }
2921
        }
2922
}
2923

2924
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2925
// based on the server, and currently active bootstrap mechanisms as defined
2926
// within the current configuration.
2927
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2928
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2929

×
2930
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2931

×
2932
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2933
        // this can be used by default if we've already partially seeded the
×
2934
        // network.
×
2935
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2936
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2937
        if err != nil {
×
2938
                return nil, err
×
2939
        }
×
2940
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2941

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

×
2947
                // If we have a set of DNS seeds for this chain, then we'll add
×
2948
                // it as an additional bootstrapping source.
×
2949
                if ok {
×
2950
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2951
                                "seeds: %v", dnsSeeds)
×
2952

×
2953
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2954
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2955
                        )
×
2956
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2957
                }
×
2958
        }
2959

2960
        return bootStrappers, nil
×
2961
}
2962

2963
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2964
// needs to ignore, which is made of three parts,
2965
//   - the node itself needs to be skipped as it doesn't make sense to connect
2966
//     to itself.
2967
//   - the peers that already have connections with, as in s.peersByPub.
2968
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2969
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2970
        s.mu.RLock()
×
2971
        defer s.mu.RUnlock()
×
2972

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

×
2975
        // We should ignore ourselves from bootstrapping.
×
2976
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2977
        ignore[selfKey] = struct{}{}
×
2978

×
2979
        // Ignore all connected peers.
×
2980
        for _, peer := range s.peersByPub {
×
2981
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2982
                ignore[nID] = struct{}{}
×
2983
        }
×
2984

2985
        // Ignore all persistent peers as they have a dedicated reconnecting
2986
        // process.
2987
        for pubKeyStr := range s.persistentPeers {
×
2988
                var nID autopilot.NodeID
×
2989
                copy(nID[:], []byte(pubKeyStr))
×
2990
                ignore[nID] = struct{}{}
×
2991
        }
×
2992

2993
        return ignore
×
2994
}
2995

2996
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2997
// and maintain a target minimum number of outbound connections. With this
2998
// invariant, we ensure that our node is connected to a diverse set of peers
2999
// and that nodes newly joining the network receive an up to date network view
3000
// as soon as possible.
3001
func (s *server) peerBootstrapper(numTargetPeers uint32,
3002
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3003

×
3004
        defer s.wg.Done()
×
3005

×
3006
        // Before we continue, init the ignore peers map.
×
3007
        ignoreList := s.createBootstrapIgnorePeers()
×
3008

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

×
3013
        // Once done, we'll attempt to maintain our target minimum number of
×
3014
        // peers.
×
3015
        //
×
3016
        // We'll use a 15 second backoff, and double the time every time an
×
3017
        // epoch fails up to a ceiling.
×
3018
        backOff := time.Second * 15
×
3019

×
3020
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3021
        // see if we've reached our minimum number of peers.
×
3022
        sampleTicker := time.NewTicker(backOff)
×
3023
        defer sampleTicker.Stop()
×
3024

×
3025
        // We'll use the number of attempts and errors to determine if we need
×
3026
        // to increase the time between discovery epochs.
×
3027
        var epochErrors uint32 // To be used atomically.
×
3028
        var epochAttempts uint32
×
3029

×
3030
        for {
×
3031
                select {
×
3032
                // The ticker has just woken us up, so we'll need to check if
3033
                // we need to attempt to connect our to any more peers.
3034
                case <-sampleTicker.C:
×
3035
                        // Obtain the current number of peers, so we can gauge
×
3036
                        // if we need to sample more peers or not.
×
3037
                        s.mu.RLock()
×
3038
                        numActivePeers := uint32(len(s.peersByPub))
×
3039
                        s.mu.RUnlock()
×
3040

×
3041
                        // If we have enough peers, then we can loop back
×
3042
                        // around to the next round as we're done here.
×
3043
                        if numActivePeers >= numTargetPeers {
×
3044
                                continue
×
3045
                        }
3046

3047
                        // If all of our attempts failed during this last back
3048
                        // off period, then will increase our backoff to 5
3049
                        // minute ceiling to avoid an excessive number of
3050
                        // queries
3051
                        //
3052
                        // TODO(roasbeef): add reverse policy too?
3053

3054
                        if epochAttempts > 0 &&
×
3055
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3056

×
3057
                                sampleTicker.Stop()
×
3058

×
3059
                                backOff *= 2
×
3060
                                if backOff > bootstrapBackOffCeiling {
×
3061
                                        backOff = bootstrapBackOffCeiling
×
3062
                                }
×
3063

3064
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3065
                                        "%v", backOff)
×
3066
                                sampleTicker = time.NewTicker(backOff)
×
3067
                                continue
×
3068
                        }
3069

3070
                        atomic.StoreUint32(&epochErrors, 0)
×
3071
                        epochAttempts = 0
×
3072

×
3073
                        // Since we know need more peers, we'll compute the
×
3074
                        // exact number we need to reach our threshold.
×
3075
                        numNeeded := numTargetPeers - numActivePeers
×
3076

×
3077
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3078
                                "peers", numNeeded)
×
3079

×
3080
                        // With the number of peers we need calculated, we'll
×
3081
                        // query the network bootstrappers to sample a set of
×
3082
                        // random addrs for us.
×
3083
                        //
×
3084
                        // Before we continue, get a copy of the ignore peers
×
3085
                        // map.
×
3086
                        ignoreList = s.createBootstrapIgnorePeers()
×
3087

×
3088
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3089
                                ignoreList, numNeeded*2, bootstrappers...,
×
3090
                        )
×
3091
                        if err != nil {
×
3092
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3093
                                        "peers: %v", err)
×
3094
                                continue
×
3095
                        }
3096

3097
                        // Finally, we'll launch a new goroutine for each
3098
                        // prospective peer candidates.
3099
                        for _, addr := range peerAddrs {
×
3100
                                epochAttempts++
×
3101

×
3102
                                go func(a *lnwire.NetAddress) {
×
3103
                                        // TODO(roasbeef): can do AS, subnet,
×
3104
                                        // country diversity, etc
×
3105
                                        errChan := make(chan error, 1)
×
3106
                                        s.connectToPeer(
×
3107
                                                a, errChan,
×
3108
                                                s.cfg.ConnectionTimeout,
×
3109
                                        )
×
3110
                                        select {
×
3111
                                        case err := <-errChan:
×
3112
                                                if err == nil {
×
3113
                                                        return
×
3114
                                                }
×
3115

3116
                                                srvrLog.Errorf("Unable to "+
×
3117
                                                        "connect to %v: %v",
×
3118
                                                        a, err)
×
3119
                                                atomic.AddUint32(&epochErrors, 1)
×
3120
                                        case <-s.quit:
×
3121
                                        }
3122
                                }(addr)
3123
                        }
3124
                case <-s.quit:
×
3125
                        return
×
3126
                }
3127
        }
3128
}
3129

3130
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3131
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3132
// query back off each time we encounter a failure.
3133
const bootstrapBackOffCeiling = time.Minute * 5
3134

3135
// initialPeerBootstrap attempts to continuously connect to peers on startup
3136
// until the target number of peers has been reached. This ensures that nodes
3137
// receive an up to date network view as soon as possible.
3138
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3139
        numTargetPeers uint32,
3140
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3141

×
3142
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3143
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3144

×
3145
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3146
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3147
        var delaySignal <-chan time.Time
×
3148
        delayTime := time.Second * 2
×
3149

×
3150
        // As want to be more aggressive, we'll use a lower back off celling
×
3151
        // then the main peer bootstrap logic.
×
3152
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3153

×
3154
        for attempts := 0; ; attempts++ {
×
3155
                // Check if the server has been requested to shut down in order
×
3156
                // to prevent blocking.
×
3157
                if s.Stopped() {
×
3158
                        return
×
3159
                }
×
3160

3161
                // We can exit our aggressive initial peer bootstrapping stage
3162
                // if we've reached out target number of peers.
3163
                s.mu.RLock()
×
3164
                numActivePeers := uint32(len(s.peersByPub))
×
3165
                s.mu.RUnlock()
×
3166

×
3167
                if numActivePeers >= numTargetPeers {
×
3168
                        return
×
3169
                }
×
3170

3171
                if attempts > 0 {
×
3172
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3173
                                "bootstrap peers (attempt #%v)", delayTime,
×
3174
                                attempts)
×
3175

×
3176
                        // We've completed at least one iterating and haven't
×
3177
                        // finished, so we'll start to insert a delay period
×
3178
                        // between each attempt.
×
3179
                        delaySignal = time.After(delayTime)
×
3180
                        select {
×
3181
                        case <-delaySignal:
×
3182
                        case <-s.quit:
×
3183
                                return
×
3184
                        }
3185

3186
                        // After our delay, we'll double the time we wait up to
3187
                        // the max back off period.
3188
                        delayTime *= 2
×
3189
                        if delayTime > backOffCeiling {
×
3190
                                delayTime = backOffCeiling
×
3191
                        }
×
3192
                }
3193

3194
                // Otherwise, we'll request for the remaining number of peers
3195
                // in order to reach our target.
3196
                peersNeeded := numTargetPeers - numActivePeers
×
3197
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3198
                        ignore, peersNeeded, bootstrappers...,
×
3199
                )
×
3200
                if err != nil {
×
3201
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3202
                                "peers: %v", err)
×
3203
                        continue
×
3204
                }
3205

3206
                // Then, we'll attempt to establish a connection to the
3207
                // different peer addresses retrieved by our bootstrappers.
3208
                var wg sync.WaitGroup
×
3209
                for _, bootstrapAddr := range bootstrapAddrs {
×
3210
                        wg.Add(1)
×
3211
                        go func(addr *lnwire.NetAddress) {
×
3212
                                defer wg.Done()
×
3213

×
3214
                                errChan := make(chan error, 1)
×
3215
                                go s.connectToPeer(
×
3216
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3217
                                )
×
3218

×
3219
                                // We'll only allow this connection attempt to
×
3220
                                // take up to 3 seconds. This allows us to move
×
3221
                                // quickly by discarding peers that are slowing
×
3222
                                // us down.
×
3223
                                select {
×
3224
                                case err := <-errChan:
×
3225
                                        if err == nil {
×
3226
                                                return
×
3227
                                        }
×
3228
                                        srvrLog.Errorf("Unable to connect to "+
×
3229
                                                "%v: %v", addr, err)
×
3230
                                // TODO: tune timeout? 3 seconds might be *too*
3231
                                // aggressive but works well.
3232
                                case <-time.After(3 * time.Second):
×
3233
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3234
                                                "to not establishing a "+
×
3235
                                                "connection within 3 seconds",
×
3236
                                                addr)
×
3237
                                case <-s.quit:
×
3238
                                }
3239
                        }(bootstrapAddr)
3240
                }
3241

3242
                wg.Wait()
×
3243
        }
3244
}
3245

3246
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3247
// order to listen for inbound connections over Tor.
3248
func (s *server) createNewHiddenService() error {
×
3249
        // Determine the different ports the server is listening on. The onion
×
3250
        // service's virtual port will map to these ports and one will be picked
×
3251
        // at random when the onion service is being accessed.
×
3252
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3253
        for _, listenAddr := range s.listenAddrs {
×
3254
                port := listenAddr.(*net.TCPAddr).Port
×
3255
                listenPorts = append(listenPorts, port)
×
3256
        }
×
3257

3258
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3259
        if err != nil {
×
3260
                return err
×
3261
        }
×
3262

3263
        // Once the port mapping has been set, we can go ahead and automatically
3264
        // create our onion service. The service's private key will be saved to
3265
        // disk in order to regain access to this service when restarting `lnd`.
3266
        onionCfg := tor.AddOnionConfig{
×
3267
                VirtualPort: defaultPeerPort,
×
3268
                TargetPorts: listenPorts,
×
3269
                Store: tor.NewOnionFile(
×
3270
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3271
                        encrypter,
×
3272
                ),
×
3273
        }
×
3274

×
3275
        switch {
×
3276
        case s.cfg.Tor.V2:
×
3277
                onionCfg.Type = tor.V2
×
3278
        case s.cfg.Tor.V3:
×
3279
                onionCfg.Type = tor.V3
×
3280
        }
3281

3282
        addr, err := s.torController.AddOnion(onionCfg)
×
3283
        if err != nil {
×
3284
                return err
×
3285
        }
×
3286

3287
        // Now that the onion service has been created, we'll add the onion
3288
        // address it can be reached at to our list of advertised addresses.
3289
        newNodeAnn, err := s.genNodeAnnouncement(
×
3290
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3291
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3292
                },
×
3293
        )
3294
        if err != nil {
×
3295
                return fmt.Errorf("unable to generate new node "+
×
3296
                        "announcement: %v", err)
×
3297
        }
×
3298

3299
        // Finally, we'll update the on-disk version of our announcement so it
3300
        // will eventually propagate to nodes in the network.
3301
        selfNode := &models.LightningNode{
×
3302
                HaveNodeAnnouncement: true,
×
3303
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3304
                Addresses:            newNodeAnn.Addresses,
×
3305
                Alias:                newNodeAnn.Alias.String(),
×
3306
                Features: lnwire.NewFeatureVector(
×
3307
                        newNodeAnn.Features, lnwire.Features,
×
3308
                ),
×
3309
                Color:        newNodeAnn.RGBColor,
×
3310
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3311
        }
×
3312
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3313
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3314
                return fmt.Errorf("can't set self node: %w", err)
×
3315
        }
×
3316

3317
        return nil
×
3318
}
3319

3320
// findChannel finds a channel given a public key and ChannelID. It is an
3321
// optimization that is quicker than seeking for a channel given only the
3322
// ChannelID.
3323
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3324
        *channeldb.OpenChannel, error) {
×
UNCOV
3325

×
UNCOV
3326
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3327
        if err != nil {
×
3328
                return nil, err
×
3329
        }
×
3330

UNCOV
3331
        for _, channel := range nodeChans {
×
UNCOV
3332
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3333
                        return channel, nil
×
UNCOV
3334
                }
×
3335
        }
3336

UNCOV
3337
        return nil, fmt.Errorf("unable to find channel")
×
3338
}
3339

3340
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3341
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3342
        s.mu.Lock()
×
UNCOV
3343
        defer s.mu.Unlock()
×
UNCOV
3344

×
UNCOV
3345
        return *s.currentNodeAnn
×
UNCOV
3346
}
×
3347

3348
// genNodeAnnouncement generates and returns the current fully signed node
3349
// announcement. The time stamp of the announcement will be updated in order
3350
// to ensure it propagates through the network.
3351
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3352
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3353

×
UNCOV
3354
        s.mu.Lock()
×
UNCOV
3355
        defer s.mu.Unlock()
×
UNCOV
3356

×
UNCOV
3357
        // First, try to update our feature manager with the updated set of
×
UNCOV
3358
        // features.
×
UNCOV
3359
        if features != nil {
×
UNCOV
3360
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3361
                        feature.SetNodeAnn: features,
×
UNCOV
3362
                }
×
UNCOV
3363
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3364
                if err != nil {
×
UNCOV
3365
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3366
                }
×
3367

3368
                // If we could successfully update our feature manager, add
3369
                // an update modifier to include these new features to our
3370
                // set.
UNCOV
3371
                modifiers = append(
×
UNCOV
3372
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3373
                )
×
3374
        }
3375

3376
        // Always update the timestamp when refreshing to ensure the update
3377
        // propagates.
UNCOV
3378
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3379

×
UNCOV
3380
        // Apply the requested changes to the node announcement.
×
UNCOV
3381
        for _, modifier := range modifiers {
×
UNCOV
3382
                modifier(s.currentNodeAnn)
×
UNCOV
3383
        }
×
3384

3385
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3386
        err := netann.SignNodeAnnouncement(
×
UNCOV
3387
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
UNCOV
3388
        )
×
UNCOV
3389
        if err != nil {
×
3390
                return lnwire.NodeAnnouncement{}, err
×
3391
        }
×
3392

UNCOV
3393
        return *s.currentNodeAnn, nil
×
3394
}
3395

3396
// updateAndBroadcastSelfNode generates a new node announcement
3397
// applying the giving modifiers and updating the time stamp
3398
// to ensure it propagates through the network. Then it broadcasts
3399
// it to the network.
3400
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
UNCOV
3401
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3402

×
UNCOV
3403
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3404
        if err != nil {
×
UNCOV
3405
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3406
                        "announcement: %v", err)
×
UNCOV
3407
        }
×
3408

3409
        // Update the on-disk version of our announcement.
3410
        // Load and modify self node istead of creating anew instance so we
3411
        // don't risk overwriting any existing values.
UNCOV
3412
        selfNode, err := s.graphDB.SourceNode()
×
UNCOV
3413
        if err != nil {
×
3414
                return fmt.Errorf("unable to get current source node: %w", err)
×
3415
        }
×
3416

UNCOV
3417
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3418
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3419
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3420
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3421
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3422
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3423
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3424

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

×
UNCOV
3427
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3428
                return fmt.Errorf("can't set self node: %w", err)
×
3429
        }
×
3430

3431
        // Finally, propagate it to the nodes in the network.
UNCOV
3432
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3433
        if err != nil {
×
3434
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3435
                        "announcement to peers: %v", err)
×
3436
                return err
×
3437
        }
×
3438

UNCOV
3439
        return nil
×
3440
}
3441

3442
type nodeAddresses struct {
3443
        pubKey    *btcec.PublicKey
3444
        addresses []net.Addr
3445
}
3446

3447
// establishPersistentConnections attempts to establish persistent connections
3448
// to all our direct channel collaborators. In order to promote liveness of our
3449
// active channels, we instruct the connection manager to attempt to establish
3450
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3451
func (s *server) establishPersistentConnections() error {
×
UNCOV
3452
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3453
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3454
        // since other PubKey forms can't be compared.
×
UNCOV
3455
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3456

×
UNCOV
3457
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3458
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3459
        // the reconnection port to the default peer port.
×
UNCOV
3460
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3461
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3462
                return err
×
3463
        }
×
UNCOV
3464
        for _, node := range linkNodes {
×
UNCOV
3465
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3466
                nodeAddrs := &nodeAddresses{
×
UNCOV
3467
                        pubKey:    node.IdentityPub,
×
UNCOV
3468
                        addresses: node.Addresses,
×
UNCOV
3469
                }
×
UNCOV
3470
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3471
        }
×
3472

3473
        // After checking our previous connections for addresses to connect to,
3474
        // iterate through the nodes in our channel graph to find addresses
3475
        // that have been added via NodeAnnouncement messages.
UNCOV
3476
        sourceNode, err := s.graphDB.SourceNode()
×
UNCOV
3477
        if err != nil {
×
3478
                return err
×
3479
        }
×
3480

3481
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3482
        // each of the nodes.
UNCOV
3483
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
3484
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
×
UNCOV
3485
                tx kvdb.RTx,
×
UNCOV
3486
                chanInfo *models.ChannelEdgeInfo,
×
UNCOV
3487
                policy, _ *models.ChannelEdgePolicy) error {
×
UNCOV
3488

×
UNCOV
3489
                // If the remote party has announced the channel to us, but we
×
UNCOV
3490
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3491
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3492
                if policy == nil {
×
3493
                        srvrLog.Warnf("No channel policy found for "+
×
3494
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3495
                }
×
3496

3497
                // We'll now fetch the peer opposite from us within this
3498
                // channel so we can queue up a direct connection to them.
UNCOV
3499
                channelPeer, err := s.graphDB.FetchOtherNode(
×
UNCOV
3500
                        tx, chanInfo, selfPub,
×
UNCOV
3501
                )
×
UNCOV
3502
                if err != nil {
×
3503
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3504
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3505
                                err)
×
3506
                }
×
3507

UNCOV
3508
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3509

×
UNCOV
3510
                // Add all unique addresses from channel
×
UNCOV
3511
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3512
                // connect to for this peer.
×
UNCOV
3513
                addrSet := make(map[string]net.Addr)
×
UNCOV
3514
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3515
                        switch addr.(type) {
×
UNCOV
3516
                        case *net.TCPAddr:
×
UNCOV
3517
                                addrSet[addr.String()] = addr
×
3518

3519
                        // We'll only attempt to connect to Tor addresses if Tor
3520
                        // outbound support is enabled.
3521
                        case *tor.OnionAddr:
×
3522
                                if s.cfg.Tor.Active {
×
3523
                                        addrSet[addr.String()] = addr
×
3524
                                }
×
3525
                        }
3526
                }
3527

3528
                // If this peer is also recorded as a link node, we'll add any
3529
                // additional addresses that have not already been selected.
UNCOV
3530
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3531
                if ok {
×
UNCOV
3532
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3533
                                switch lnAddress.(type) {
×
UNCOV
3534
                                case *net.TCPAddr:
×
UNCOV
3535
                                        addrSet[lnAddress.String()] = lnAddress
×
3536

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

3547
                // Construct a slice of the deduped addresses.
UNCOV
3548
                var addrs []net.Addr
×
UNCOV
3549
                for _, addr := range addrSet {
×
UNCOV
3550
                        addrs = append(addrs, addr)
×
UNCOV
3551
                }
×
3552

UNCOV
3553
                n := &nodeAddresses{
×
UNCOV
3554
                        addresses: addrs,
×
UNCOV
3555
                }
×
UNCOV
3556
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3557
                if err != nil {
×
3558
                        return err
×
3559
                }
×
3560

UNCOV
3561
                nodeAddrsMap[pubStr] = n
×
UNCOV
3562
                return nil
×
3563
        })
UNCOV
3564
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
×
3565
                return err
×
3566
        }
×
3567

UNCOV
3568
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3569
                len(nodeAddrsMap))
×
UNCOV
3570

×
UNCOV
3571
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3572
        // have been recorded and sent to the connection manager.
×
UNCOV
3573
        s.mu.Lock()
×
UNCOV
3574
        defer s.mu.Unlock()
×
UNCOV
3575

×
UNCOV
3576
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3577
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3578
        var numOutboundConns int
×
UNCOV
3579
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3580
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3581
                // persistent connection with. We set the value to false to
×
UNCOV
3582
                // indicate that we should not continue to reconnect if the
×
UNCOV
3583
                // number of channels returns to zero, since this peer has not
×
UNCOV
3584
                // been requested as perm by the user.
×
UNCOV
3585
                s.persistentPeers[pubStr] = false
×
UNCOV
3586
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3587
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3588
                }
×
3589

UNCOV
3590
                for _, address := range nodeAddr.addresses {
×
UNCOV
3591
                        // Create a wrapper address which couples the IP and
×
UNCOV
3592
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3593
                        // can be established.
×
UNCOV
3594
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3595
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3596
                                Address:     address,
×
UNCOV
3597
                        }
×
UNCOV
3598

×
UNCOV
3599
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3600
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3601
                }
×
3602

3603
                // We'll connect to the first 10 peers immediately, then
3604
                // randomly stagger any remaining connections if the
3605
                // stagger initial reconnect flag is set. This ensures
3606
                // that mobile nodes or nodes with a small number of
3607
                // channels obtain connectivity quickly, but larger
3608
                // nodes are able to disperse the costs of connecting to
3609
                // all peers at once.
UNCOV
3610
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3611
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3612

×
UNCOV
3613
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3614
                } else {
×
3615
                        go s.delayInitialReconnect(pubStr)
×
3616
                }
×
3617

UNCOV
3618
                numOutboundConns++
×
3619
        }
3620

UNCOV
3621
        return nil
×
3622
}
3623

3624
// delayInitialReconnect will attempt a reconnection to the given peer after
3625
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3626
//
3627
// NOTE: This method MUST be run as a goroutine.
3628
func (s *server) delayInitialReconnect(pubStr string) {
×
3629
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3630
        select {
×
3631
        case <-time.After(delay):
×
3632
                s.connectToPersistentPeer(pubStr)
×
3633
        case <-s.quit:
×
3634
        }
3635
}
3636

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

×
UNCOV
3643
        s.mu.Lock()
×
UNCOV
3644
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3645
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3646
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3647
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3648
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3649
                s.mu.Unlock()
×
UNCOV
3650

×
UNCOV
3651
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3652
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3653

×
UNCOV
3654
                return
×
UNCOV
3655
        }
×
UNCOV
3656
        s.mu.Unlock()
×
3657
}
3658

3659
// BroadcastMessage sends a request to the server to broadcast a set of
3660
// messages to all peers other than the one specified by the `skips` parameter.
3661
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3662
// the target peers.
3663
//
3664
// NOTE: This function is safe for concurrent access.
3665
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3666
        msgs ...lnwire.Message) error {
×
UNCOV
3667

×
UNCOV
3668
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3669
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3670
        // exact set of peers present at the time of invocation.
×
UNCOV
3671
        s.mu.RLock()
×
UNCOV
3672
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3673
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3674
                if skips != nil {
×
UNCOV
3675
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3676
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3677
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3678
                                continue
×
3679
                        }
3680
                }
3681

UNCOV
3682
                peers = append(peers, sPeer)
×
3683
        }
UNCOV
3684
        s.mu.RUnlock()
×
UNCOV
3685

×
UNCOV
3686
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3687
        // all messages to each of peers.
×
UNCOV
3688
        var wg sync.WaitGroup
×
UNCOV
3689
        for _, sPeer := range peers {
×
UNCOV
3690
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3691
                        sPeer.PubKey())
×
UNCOV
3692

×
UNCOV
3693
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3694
                wg.Add(1)
×
UNCOV
3695
                s.wg.Add(1)
×
UNCOV
3696
                go func(p lnpeer.Peer) {
×
UNCOV
3697
                        defer s.wg.Done()
×
UNCOV
3698
                        defer wg.Done()
×
UNCOV
3699

×
UNCOV
3700
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3701
                }(sPeer)
×
3702
        }
3703

3704
        // Wait for all messages to have been dispatched before returning to
3705
        // caller.
UNCOV
3706
        wg.Wait()
×
UNCOV
3707

×
UNCOV
3708
        return nil
×
3709
}
3710

3711
// NotifyWhenOnline can be called by other subsystems to get notified when a
3712
// particular peer comes online. The peer itself is sent across the peerChan.
3713
//
3714
// NOTE: This function is safe for concurrent access.
3715
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3716
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3717

×
UNCOV
3718
        s.mu.Lock()
×
UNCOV
3719

×
UNCOV
3720
        // Compute the target peer's identifier.
×
UNCOV
3721
        pubStr := string(peerKey[:])
×
UNCOV
3722

×
UNCOV
3723
        // Check if peer is connected.
×
UNCOV
3724
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3725
        if ok {
×
UNCOV
3726
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3727
                // waiting for the peer to become active.
×
UNCOV
3728
                s.mu.Unlock()
×
UNCOV
3729

×
UNCOV
3730
                // Wait until the peer signals that it is actually active
×
UNCOV
3731
                // rather than only in the server's maps.
×
UNCOV
3732
                select {
×
UNCOV
3733
                case <-peer.ActiveSignal():
×
3734
                case <-peer.QuitSignal():
×
3735
                        // The peer quit, so we'll add the channel to the slice
×
3736
                        // and return.
×
3737
                        s.mu.Lock()
×
3738
                        s.peerConnectedListeners[pubStr] = append(
×
3739
                                s.peerConnectedListeners[pubStr], peerChan,
×
3740
                        )
×
3741
                        s.mu.Unlock()
×
3742
                        return
×
3743
                }
3744

3745
                // Connected, can return early.
UNCOV
3746
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3747

×
UNCOV
3748
                select {
×
UNCOV
3749
                case peerChan <- peer:
×
3750
                case <-s.quit:
×
3751
                }
3752

UNCOV
3753
                return
×
3754
        }
3755

3756
        // Not connected, store this listener such that it can be notified when
3757
        // the peer comes online.
UNCOV
3758
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3759
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3760
        )
×
UNCOV
3761
        s.mu.Unlock()
×
3762
}
3763

3764
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3765
// the given public key has been disconnected. The notification is signaled by
3766
// closing the channel returned.
UNCOV
3767
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3768
        s.mu.Lock()
×
UNCOV
3769
        defer s.mu.Unlock()
×
UNCOV
3770

×
UNCOV
3771
        c := make(chan struct{})
×
UNCOV
3772

×
UNCOV
3773
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3774
        // notification.
×
UNCOV
3775
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3776
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3777
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3778
                close(c)
×
3779
                return c
×
3780
        }
×
3781

3782
        // Otherwise, the peer is online, so we'll keep track of the channel to
3783
        // trigger the notification once the server detects the peer
3784
        // disconnects.
UNCOV
3785
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3786
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3787
        )
×
UNCOV
3788

×
UNCOV
3789
        return c
×
3790
}
3791

3792
// FindPeer will return the peer that corresponds to the passed in public key.
3793
// This function is used by the funding manager, allowing it to update the
3794
// daemon's local representation of the remote peer.
3795
//
3796
// NOTE: This function is safe for concurrent access.
UNCOV
3797
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3798
        s.mu.RLock()
×
UNCOV
3799
        defer s.mu.RUnlock()
×
UNCOV
3800

×
UNCOV
3801
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3802

×
UNCOV
3803
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3804
}
×
3805

3806
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3807
// which should be a string representation of the peer's serialized, compressed
3808
// public key.
3809
//
3810
// NOTE: This function is safe for concurrent access.
UNCOV
3811
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3812
        s.mu.RLock()
×
UNCOV
3813
        defer s.mu.RUnlock()
×
UNCOV
3814

×
UNCOV
3815
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3816
}
×
3817

3818
// findPeerByPubStr is an internal method that retrieves the specified peer from
3819
// the server's internal state using.
UNCOV
3820
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3821
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3822
        if !ok {
×
UNCOV
3823
                return nil, ErrPeerNotConnected
×
UNCOV
3824
        }
×
3825

UNCOV
3826
        return peer, nil
×
3827
}
3828

3829
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3830
// exponential backoff. If no previous backoff was known, the default is
3831
// returned.
3832
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3833
        startTime time.Time) time.Duration {
×
UNCOV
3834

×
UNCOV
3835
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3836
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3837
        if !ok {
×
UNCOV
3838
                // If an existing backoff was unknown, use the default.
×
UNCOV
3839
                return s.cfg.MinBackoff
×
UNCOV
3840
        }
×
3841

3842
        // If the peer failed to start properly, we'll just use the previous
3843
        // backoff to compute the subsequent randomized exponential backoff
3844
        // duration. This will roughly double on average.
UNCOV
3845
        if startTime.IsZero() {
×
3846
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3847
        }
×
3848

3849
        // The peer succeeded in starting. If the connection didn't last long
3850
        // enough to be considered stable, we'll continue to back off retries
3851
        // with this peer.
UNCOV
3852
        connDuration := time.Since(startTime)
×
UNCOV
3853
        if connDuration < defaultStableConnDuration {
×
UNCOV
3854
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3855
        }
×
3856

3857
        // The peer succeed in starting and this was stable peer, so we'll
3858
        // reduce the timeout duration by the length of the connection after
3859
        // applying randomized exponential backoff. We'll only apply this in the
3860
        // case that:
3861
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3862
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3863
        if relaxedBackoff > s.cfg.MinBackoff {
×
3864
                return relaxedBackoff
×
3865
        }
×
3866

3867
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3868
        // the stable connection lasted much longer than our previous backoff.
3869
        // To reward such good behavior, we'll reconnect after the default
3870
        // timeout.
3871
        return s.cfg.MinBackoff
×
3872
}
3873

3874
// shouldDropLocalConnection determines if our local connection to a remote peer
3875
// should be dropped in the case of concurrent connection establishment. In
3876
// order to deterministically decide which connection should be dropped, we'll
3877
// utilize the ordering of the local and remote public key. If we didn't use
3878
// such a tie breaker, then we risk _both_ connections erroneously being
3879
// dropped.
3880
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3881
        localPubBytes := local.SerializeCompressed()
×
3882
        remotePubPbytes := remote.SerializeCompressed()
×
3883

×
3884
        // The connection that comes from the node with a "smaller" pubkey
×
3885
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3886
        // should drop our established connection.
×
3887
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3888
}
×
3889

3890
// InboundPeerConnected initializes a new peer in response to a new inbound
3891
// connection.
3892
//
3893
// NOTE: This function is safe for concurrent access.
UNCOV
3894
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3895
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3896
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3897
        if s.Stopped() {
×
3898
                return
×
3899
        }
×
3900

UNCOV
3901
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3902
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3903
        pubStr := string(pubSer)
×
UNCOV
3904

×
UNCOV
3905
        var pubBytes [33]byte
×
UNCOV
3906
        copy(pubBytes[:], pubSer)
×
UNCOV
3907

×
UNCOV
3908
        s.mu.Lock()
×
UNCOV
3909
        defer s.mu.Unlock()
×
UNCOV
3910

×
UNCOV
3911
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3912
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3913
        if dcErr != nil {
×
3914
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3915
                        "peer: %v", dcErr)
×
3916
                conn.Close()
×
3917

×
3918
                return
×
3919
        }
×
3920

UNCOV
3921
        if shouldDc {
×
3922
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3923
                        "banned.", pubSer)
×
3924

×
3925
                conn.Close()
×
3926

×
3927
                return
×
3928
        }
×
3929

3930
        // If we already have an outbound connection to this peer, then ignore
3931
        // this new connection.
UNCOV
3932
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
3933
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
3934
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
3935
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3936

×
UNCOV
3937
                conn.Close()
×
UNCOV
3938
                return
×
UNCOV
3939
        }
×
3940

3941
        // If we already have a valid connection that is scheduled to take
3942
        // precedence once the prior peer has finished disconnecting, we'll
3943
        // ignore this connection.
UNCOV
3944
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3945
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3946
                        "scheduled", conn.RemoteAddr(), p)
×
3947
                conn.Close()
×
3948
                return
×
3949
        }
×
3950

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

×
UNCOV
3953
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3954
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3955
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3956
        // default case as we expect these to be the only error values returned
×
UNCOV
3957
        // from findPeerByPubStr.
×
UNCOV
3958
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3959
        switch err {
×
UNCOV
3960
        case ErrPeerNotConnected:
×
UNCOV
3961
                // We were unable to locate an existing connection with the
×
UNCOV
3962
                // target peer, proceed to connect.
×
UNCOV
3963
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3964
                s.peerConnected(conn, nil, true)
×
3965

3966
        case nil:
×
3967
                // We already have a connection with the incoming peer. If the
×
3968
                // connection we've already established should be kept and is
×
3969
                // not of the same type of the new connection (inbound), then
×
3970
                // we'll close out the new connection s.t there's only a single
×
3971
                // connection between us.
×
3972
                localPub := s.identityECDH.PubKey()
×
3973
                if !connectedPeer.Inbound() &&
×
3974
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3975

×
3976
                        srvrLog.Warnf("Received inbound connection from "+
×
3977
                                "peer %v, but already have outbound "+
×
3978
                                "connection, dropping conn", connectedPeer)
×
3979
                        conn.Close()
×
3980
                        return
×
3981
                }
×
3982

3983
                // Otherwise, if we should drop the connection, then we'll
3984
                // disconnect our already connected peer.
3985
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3986
                        connectedPeer)
×
3987

×
3988
                s.cancelConnReqs(pubStr, nil)
×
3989

×
3990
                // Remove the current peer from the server's internal state and
×
3991
                // signal that the peer termination watcher does not need to
×
3992
                // execute for this peer.
×
3993
                s.removePeer(connectedPeer)
×
3994
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3995
                s.scheduledPeerConnection[pubStr] = func() {
×
3996
                        s.peerConnected(conn, nil, true)
×
3997
                }
×
3998
        }
3999
}
4000

4001
// OutboundPeerConnected initializes a new peer in response to a new outbound
4002
// connection.
4003
// NOTE: This function is safe for concurrent access.
UNCOV
4004
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
4005
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
4006
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
4007
        if s.Stopped() {
×
4008
                return
×
4009
        }
×
4010

UNCOV
4011
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
4012
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
4013
        pubStr := string(pubSer)
×
UNCOV
4014

×
UNCOV
4015
        var pubBytes [33]byte
×
UNCOV
4016
        copy(pubBytes[:], pubSer)
×
UNCOV
4017

×
UNCOV
4018
        s.mu.Lock()
×
UNCOV
4019
        defer s.mu.Unlock()
×
UNCOV
4020

×
UNCOV
4021
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
4022
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
4023
        if dcErr != nil {
×
4024
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
4025
                        "peer: %v", dcErr)
×
4026
                conn.Close()
×
4027

×
4028
                return
×
4029
        }
×
4030

UNCOV
4031
        if shouldDc {
×
4032
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
4033
                        "banned.", pubSer)
×
4034

×
4035
                if connReq != nil {
×
4036
                        s.connMgr.Remove(connReq.ID())
×
4037
                }
×
4038

4039
                conn.Close()
×
4040

×
4041
                return
×
4042
        }
4043

4044
        // If we already have an inbound connection to this peer, then ignore
4045
        // this new connection.
UNCOV
4046
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
4047
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
4048
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
4049
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4050

×
UNCOV
4051
                if connReq != nil {
×
UNCOV
4052
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
4053
                }
×
UNCOV
4054
                conn.Close()
×
UNCOV
4055
                return
×
4056
        }
UNCOV
4057
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
4058
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4059
                s.connMgr.Remove(connReq.ID())
×
4060
                conn.Close()
×
4061
                return
×
4062
        }
×
4063

4064
        // If we already have a valid connection that is scheduled to take
4065
        // precedence once the prior peer has finished disconnecting, we'll
4066
        // ignore this connection.
UNCOV
4067
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
4068
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
4069

×
4070
                if connReq != nil {
×
4071
                        s.connMgr.Remove(connReq.ID())
×
4072
                }
×
4073

4074
                conn.Close()
×
4075
                return
×
4076
        }
4077

UNCOV
4078
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
UNCOV
4079
                conn.RemoteAddr())
×
UNCOV
4080

×
UNCOV
4081
        if connReq != nil {
×
UNCOV
4082
                // A successful connection was returned by the connmgr.
×
UNCOV
4083
                // Immediately cancel all pending requests, excluding the
×
UNCOV
4084
                // outbound connection we just established.
×
UNCOV
4085
                ignore := connReq.ID()
×
UNCOV
4086
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
4087
        } else {
×
UNCOV
4088
                // This was a successful connection made by some other
×
UNCOV
4089
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
4090
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
4091
        }
×
4092

4093
        // If we already have a connection with this peer, decide whether or not
4094
        // we need to drop the stale connection. We forgo adding a default case
4095
        // as we expect these to be the only error values returned from
4096
        // findPeerByPubStr.
UNCOV
4097
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4098
        switch err {
×
UNCOV
4099
        case ErrPeerNotConnected:
×
UNCOV
4100
                // We were unable to locate an existing connection with the
×
UNCOV
4101
                // target peer, proceed to connect.
×
UNCOV
4102
                s.peerConnected(conn, connReq, false)
×
4103

4104
        case nil:
×
4105
                // We already have a connection with the incoming peer. If the
×
4106
                // connection we've already established should be kept and is
×
4107
                // not of the same type of the new connection (outbound), then
×
4108
                // we'll close out the new connection s.t there's only a single
×
4109
                // connection between us.
×
4110
                localPub := s.identityECDH.PubKey()
×
4111
                if connectedPeer.Inbound() &&
×
4112
                        shouldDropLocalConnection(localPub, nodePub) {
×
4113

×
4114
                        srvrLog.Warnf("Established outbound connection to "+
×
4115
                                "peer %v, but already have inbound "+
×
4116
                                "connection, dropping conn", connectedPeer)
×
4117
                        if connReq != nil {
×
4118
                                s.connMgr.Remove(connReq.ID())
×
4119
                        }
×
4120
                        conn.Close()
×
4121
                        return
×
4122
                }
4123

4124
                // Otherwise, _their_ connection should be dropped. So we'll
4125
                // disconnect the peer and send the now obsolete peer to the
4126
                // server for garbage collection.
4127
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4128
                        connectedPeer)
×
4129

×
4130
                // Remove the current peer from the server's internal state and
×
4131
                // signal that the peer termination watcher does not need to
×
4132
                // execute for this peer.
×
4133
                s.removePeer(connectedPeer)
×
4134
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4135
                s.scheduledPeerConnection[pubStr] = func() {
×
4136
                        s.peerConnected(conn, connReq, false)
×
4137
                }
×
4138
        }
4139
}
4140

4141
// UnassignedConnID is the default connection ID that a request can have before
4142
// it actually is submitted to the connmgr.
4143
// TODO(conner): move into connmgr package, or better, add connmgr method for
4144
// generating atomic IDs
4145
const UnassignedConnID uint64 = 0
4146

4147
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4148
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4149
// Afterwards, each connection request removed from the connmgr. The caller can
4150
// optionally specify a connection ID to ignore, which prevents us from
4151
// canceling a successful request. All persistent connreqs for the provided
4152
// pubkey are discarded after the operationjw.
UNCOV
4153
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4154
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4155
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4156
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4157
                close(cancelChan)
×
UNCOV
4158
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4159
        }
×
4160

4161
        // Next, check to see if we have any outstanding persistent connection
4162
        // requests to this peer. If so, then we'll remove all of these
4163
        // connection requests, and also delete the entry from the map.
UNCOV
4164
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4165
        if !ok {
×
UNCOV
4166
                return
×
UNCOV
4167
        }
×
4168

UNCOV
4169
        for _, connReq := range connReqs {
×
UNCOV
4170
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4171

×
UNCOV
4172
                // Atomically capture the current request identifier.
×
UNCOV
4173
                connID := connReq.ID()
×
UNCOV
4174

×
UNCOV
4175
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4176
                // yet been schedule.
×
UNCOV
4177
                if connID == UnassignedConnID {
×
UNCOV
4178
                        continue
×
4179
                }
4180

4181
                // Skip a particular connection ID if instructed.
UNCOV
4182
                if skip != nil && connID == *skip {
×
UNCOV
4183
                        continue
×
4184
                }
4185

UNCOV
4186
                s.connMgr.Remove(connID)
×
4187
        }
4188

UNCOV
4189
        delete(s.persistentConnReqs, pubStr)
×
4190
}
4191

4192
// handleCustomMessage dispatches an incoming custom peers message to
4193
// subscribers.
UNCOV
4194
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4195
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4196
                peer, msg.Type)
×
UNCOV
4197

×
UNCOV
4198
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4199
                Peer: peer,
×
UNCOV
4200
                Msg:  msg,
×
UNCOV
4201
        })
×
UNCOV
4202
}
×
4203

4204
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4205
// messages.
UNCOV
4206
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4207
        return s.customMessageServer.Subscribe()
×
UNCOV
4208
}
×
4209

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

×
UNCOV
4217
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4218
        addr := conn.RemoteAddr()
×
UNCOV
4219
        pubKey := brontideConn.RemotePub()
×
UNCOV
4220

×
UNCOV
4221
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4222
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4223

×
UNCOV
4224
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4225
                IdentityKey: pubKey,
×
UNCOV
4226
                Address:     addr,
×
UNCOV
4227
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4228
        }
×
UNCOV
4229

×
UNCOV
4230
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4231
        // vectors to advertise to the remote node.
×
UNCOV
4232
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4233
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4234

×
UNCOV
4235
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4236
        // found, create a fresh buffer.
×
UNCOV
4237
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4238
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4239
        if !ok {
×
UNCOV
4240
                var err error
×
UNCOV
4241
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4242
                if err != nil {
×
4243
                        srvrLog.Errorf("unable to create peer %v", err)
×
4244
                        return
×
4245
                }
×
4246
        }
4247

4248
        // If we directly set the peer.Config TowerClient member to the
4249
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4250
        // the peer.Config's TowerClient member will not evaluate to nil even
4251
        // though the underlying value is nil. To avoid this gotcha which can
4252
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4253
        // TowerClient if needed.
UNCOV
4254
        var towerClient wtclient.ClientManager
×
UNCOV
4255
        if s.towerClientMgr != nil {
×
UNCOV
4256
                towerClient = s.towerClientMgr
×
UNCOV
4257
        }
×
4258

UNCOV
4259
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4260
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4261

×
UNCOV
4262
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4263
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4264
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4265
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4266
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4267
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4268
        pCfg := peer.Config{
×
UNCOV
4269
                Conn:                    brontideConn,
×
UNCOV
4270
                ConnReq:                 connReq,
×
UNCOV
4271
                Addr:                    peerAddr,
×
UNCOV
4272
                Inbound:                 inbound,
×
UNCOV
4273
                Features:                initFeatures,
×
UNCOV
4274
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4275
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4276
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4277
                ErrorBuffer:             errBuffer,
×
UNCOV
4278
                WritePool:               s.writePool,
×
UNCOV
4279
                ReadPool:                s.readPool,
×
UNCOV
4280
                Switch:                  s.htlcSwitch,
×
UNCOV
4281
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4282
                ChannelDB:               s.chanStateDB,
×
UNCOV
4283
                ChannelGraph:            s.graphDB,
×
UNCOV
4284
                ChainArb:                s.chainArb,
×
UNCOV
4285
                AuthGossiper:            s.authGossiper,
×
UNCOV
4286
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4287
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4288
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4289
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4290
                SigPool:                 s.sigPool,
×
UNCOV
4291
                Wallet:                  s.cc.Wallet,
×
UNCOV
4292
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4293
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4294
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4295
                Sphinx:                  s.sphinx,
×
UNCOV
4296
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4297
                Invoices:                s.invoices,
×
UNCOV
4298
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4299
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4300
                TowerClient:             towerClient,
×
UNCOV
4301
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4302
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4303
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4304

×
UNCOV
4305
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4306
                },
×
4307

4308
                PongBuf: s.pongBuf,
4309

4310
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4311

4312
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4313

4314
                FundingManager: s.fundingMgr,
4315

4316
                Hodl:                    s.cfg.Hodl,
4317
                UnsafeReplay:            s.cfg.UnsafeReplay,
4318
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4319
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4320
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4321
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4322
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4323
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4324
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4325
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4326
                HandleCustomMessage:    s.handleCustomMessage,
4327
                GetAliases:             s.aliasMgr.GetAliases,
4328
                RequestAlias:           s.aliasMgr.RequestAlias,
4329
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4330
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4331
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4332
                MaxFeeExposure:         thresholdMSats,
4333
                Quit:                   s.quit,
4334
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4335
                AuxSigner:              s.implCfg.AuxSigner,
4336
                MsgRouter:              s.implCfg.MsgRouter,
4337
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4338
                AuxResolver:            s.implCfg.AuxContractResolver,
4339
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
UNCOV
4340
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4341
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4342
                                return false
×
UNCOV
4343
                        }
×
4344

UNCOV
4345
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4346
                                EndorsementExperimentEnd,
×
UNCOV
4347
                        )
×
4348
                },
4349
        }
4350

UNCOV
4351
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4352
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4353

×
UNCOV
4354
        p := peer.NewBrontide(pCfg)
×
UNCOV
4355

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

×
UNCOV
4359
        s.addPeer(p)
×
UNCOV
4360

×
UNCOV
4361
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4362
        // delete the previous error buffer from the server's map of error
×
UNCOV
4363
        // buffers.
×
UNCOV
4364
        delete(s.peerErrors, pkStr)
×
UNCOV
4365

×
UNCOV
4366
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4367
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4368
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4369
        s.wg.Add(1)
×
UNCOV
4370
        go s.peerInitializer(p)
×
4371
}
4372

4373
// addPeer adds the passed peer to the server's global state of all active
4374
// peers.
UNCOV
4375
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4376
        if p == nil {
×
4377
                return
×
4378
        }
×
4379

UNCOV
4380
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4381

×
UNCOV
4382
        // Ignore new peers if we're shutting down.
×
UNCOV
4383
        if s.Stopped() {
×
4384
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4385
                        pubBytes)
×
4386
                p.Disconnect(ErrServerShuttingDown)
×
4387

×
4388
                return
×
4389
        }
×
4390

4391
        // Track the new peer in our indexes so we can quickly look it up either
4392
        // according to its public key, or its peer ID.
4393
        // TODO(roasbeef): pipe all requests through to the
4394
        // queryHandler/peerManager
4395

4396
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4397
        // be human-readable.
UNCOV
4398
        pubStr := string(pubBytes)
×
UNCOV
4399

×
UNCOV
4400
        s.peersByPub[pubStr] = p
×
UNCOV
4401

×
UNCOV
4402
        if p.Inbound() {
×
UNCOV
4403
                s.inboundPeers[pubStr] = p
×
UNCOV
4404
        } else {
×
UNCOV
4405
                s.outboundPeers[pubStr] = p
×
UNCOV
4406
        }
×
4407

4408
        // Inform the peer notifier of a peer online event so that it can be reported
4409
        // to clients listening for peer events.
UNCOV
4410
        var pubKey [33]byte
×
UNCOV
4411
        copy(pubKey[:], pubBytes)
×
UNCOV
4412

×
UNCOV
4413
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4414
}
4415

4416
// peerInitializer asynchronously starts a newly connected peer after it has
4417
// been added to the server's peer map. This method sets up a
4418
// peerTerminationWatcher for the given peer, and ensures that it executes even
4419
// if the peer failed to start. In the event of a successful connection, this
4420
// method reads the negotiated, local feature-bits and spawns the appropriate
4421
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4422
// be signaled of the new peer once the method returns.
4423
//
4424
// NOTE: This MUST be launched as a goroutine.
UNCOV
4425
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4426
        defer s.wg.Done()
×
UNCOV
4427

×
UNCOV
4428
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4429

×
UNCOV
4430
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4431
        if s.Stopped() {
×
4432
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4433
                        pubBytes)
×
4434
                return
×
4435
        }
×
4436

4437
        // Create a channel that will be used to signal a successful start of
4438
        // the link. This prevents the peer termination watcher from beginning
4439
        // its duty too early.
UNCOV
4440
        ready := make(chan struct{})
×
UNCOV
4441

×
UNCOV
4442
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4443
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4444
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4445
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4446
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4447
        // that the server has already handled the removal of this peer.
×
UNCOV
4448
        s.wg.Add(1)
×
UNCOV
4449
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4450

×
UNCOV
4451
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4452
        // will unblock the peerTerminationWatcher.
×
UNCOV
4453
        if err := p.Start(); err != nil {
×
4454
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4455

×
4456
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4457
                return
×
4458
        }
×
4459

4460
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4461
        // was successful, and to begin watching the peer's wait group.
UNCOV
4462
        close(ready)
×
UNCOV
4463

×
UNCOV
4464
        s.mu.Lock()
×
UNCOV
4465
        defer s.mu.Unlock()
×
UNCOV
4466

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

×
UNCOV
4470
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4471
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4472
        pubStr := string(pubBytes)
×
UNCOV
4473
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4474
                select {
×
UNCOV
4475
                case peerChan <- p:
×
4476
                case <-s.quit:
×
4477
                        return
×
4478
                }
4479
        }
UNCOV
4480
        delete(s.peerConnectedListeners, pubStr)
×
4481
}
4482

4483
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4484
// and then cleans up all resources allocated to the peer, notifies relevant
4485
// sub-systems of its demise, and finally handles re-connecting to the peer if
4486
// it's persistent. If the server intentionally disconnects a peer, it should
4487
// have a corresponding entry in the ignorePeerTermination map which will cause
4488
// the cleanup routine to exit early. The passed `ready` chan is used to
4489
// synchronize when WaitForDisconnect should begin watching on the peer's
4490
// waitgroup. The ready chan should only be signaled if the peer starts
4491
// successfully, otherwise the peer should be disconnected instead.
4492
//
4493
// NOTE: This MUST be launched as a goroutine.
UNCOV
4494
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4495
        defer s.wg.Done()
×
UNCOV
4496

×
UNCOV
4497
        p.WaitForDisconnect(ready)
×
UNCOV
4498

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

×
UNCOV
4501
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4502
        // the other sub-systems will already be shutting down.
×
UNCOV
4503
        if s.Stopped() {
×
UNCOV
4504
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4505
                return
×
UNCOV
4506
        }
×
4507

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

×
UNCOV
4514
        pubKey := p.IdentityKey()
×
UNCOV
4515

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

×
UNCOV
4520
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4521
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4522
        // with this interface should be closed.
×
UNCOV
4523
        //
×
UNCOV
4524
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4525
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4526
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4527
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4528
        }
×
4529

UNCOV
4530
        for _, link := range links {
×
UNCOV
4531
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4532
        }
×
4533

UNCOV
4534
        s.mu.Lock()
×
UNCOV
4535
        defer s.mu.Unlock()
×
UNCOV
4536

×
UNCOV
4537
        // If there were any notification requests for when this peer
×
UNCOV
4538
        // disconnected, we can trigger them now.
×
UNCOV
4539
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4540
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4541
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4542
                close(offlineChan)
×
UNCOV
4543
        }
×
UNCOV
4544
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4545

×
UNCOV
4546
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4547
        // peer termination watcher and skip cleanup.
×
UNCOV
4548
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4549
                delete(s.ignorePeerTermination, p)
×
4550

×
4551
                pubKey := p.PubKey()
×
4552
                pubStr := string(pubKey[:])
×
4553

×
4554
                // If a connection callback is present, we'll go ahead and
×
4555
                // execute it now that previous peer has fully disconnected. If
×
4556
                // the callback is not present, this likely implies the peer was
×
4557
                // purposefully disconnected via RPC, and that no reconnect
×
4558
                // should be attempted.
×
4559
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4560
                if ok {
×
4561
                        delete(s.scheduledPeerConnection, pubStr)
×
4562
                        connCallback()
×
4563
                }
×
4564
                return
×
4565
        }
4566

4567
        // First, cleanup any remaining state the server has regarding the peer
4568
        // in question.
UNCOV
4569
        s.removePeer(p)
×
UNCOV
4570

×
UNCOV
4571
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4572
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4573
                return
×
UNCOV
4574
        }
×
4575

4576
        // Get the last address that we used to connect to the peer.
UNCOV
4577
        addrs := []net.Addr{
×
UNCOV
4578
                p.NetAddress().Address,
×
UNCOV
4579
        }
×
UNCOV
4580

×
UNCOV
4581
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4582
        // reconnection purposes.
×
UNCOV
4583
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
UNCOV
4584
        switch {
×
4585
        // We found advertised addresses, so use them.
UNCOV
4586
        case err == nil:
×
UNCOV
4587
                addrs = advertisedAddrs
×
4588

4589
        // The peer doesn't have an advertised address.
UNCOV
4590
        case err == errNoAdvertisedAddr:
×
UNCOV
4591
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4592
                // peer address.
×
UNCOV
4593
                if !p.Inbound() {
×
UNCOV
4594
                        break
×
4595
                }
4596

4597
                // Fall back to the existing peer address if
4598
                // we're not accepting connections over Tor.
UNCOV
4599
                if s.torController == nil {
×
UNCOV
4600
                        break
×
4601
                }
4602

4603
                // If we are, the peer's address won't be known
4604
                // to us (we'll see a private address, which is
4605
                // the address used by our onion service to dial
4606
                // to lnd), so we don't have enough information
4607
                // to attempt a reconnect.
4608
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4609
                        "to inbound peer %v without "+
×
4610
                        "advertised address", p)
×
4611
                return
×
4612

4613
        // We came across an error retrieving an advertised
4614
        // address, log it, and fall back to the existing peer
4615
        // address.
UNCOV
4616
        default:
×
UNCOV
4617
                srvrLog.Errorf("Unable to retrieve advertised "+
×
UNCOV
4618
                        "address for node %x: %v", p.PubKey(),
×
UNCOV
4619
                        err)
×
4620
        }
4621

4622
        // Make an easy lookup map so that we can check if an address
4623
        // is already in the address list that we have stored for this peer.
UNCOV
4624
        existingAddrs := make(map[string]bool)
×
UNCOV
4625
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4626
                existingAddrs[addr.String()] = true
×
UNCOV
4627
        }
×
4628

4629
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4630
        for _, addr := range addrs {
×
UNCOV
4631
                if existingAddrs[addr.String()] {
×
4632
                        continue
×
4633
                }
4634

UNCOV
4635
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4636
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4637
                        &lnwire.NetAddress{
×
UNCOV
4638
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4639
                                Address:     addr,
×
UNCOV
4640
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4641
                        },
×
UNCOV
4642
                )
×
4643
        }
4644

4645
        // Record the computed backoff in the backoff map.
UNCOV
4646
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4647
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4648

×
UNCOV
4649
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4650
        // exist.
×
UNCOV
4651
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4652
        if !ok {
×
UNCOV
4653
                cancelChan = make(chan struct{})
×
UNCOV
4654
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4655
        }
×
4656

4657
        // We choose not to wait group this go routine since the Connect
4658
        // call can stall for arbitrarily long if we shutdown while an
4659
        // outbound connection attempt is being made.
UNCOV
4660
        go func() {
×
UNCOV
4661
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
UNCOV
4662
                        "persistent peer %x in %s",
×
UNCOV
4663
                        p.IdentityKey().SerializeCompressed(), backoff)
×
UNCOV
4664

×
UNCOV
4665
                select {
×
UNCOV
4666
                case <-time.After(backoff):
×
UNCOV
4667
                case <-cancelChan:
×
UNCOV
4668
                        return
×
UNCOV
4669
                case <-s.quit:
×
UNCOV
4670
                        return
×
4671
                }
4672

UNCOV
4673
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4674
                        "connection to peer %x",
×
UNCOV
4675
                        p.IdentityKey().SerializeCompressed())
×
UNCOV
4676

×
UNCOV
4677
                s.connectToPersistentPeer(pubStr)
×
4678
        }()
4679
}
4680

4681
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4682
// to connect to the peer. It creates connection requests if there are
4683
// currently none for a given address and it removes old connection requests
4684
// if the associated address is no longer in the latest address list for the
4685
// peer.
UNCOV
4686
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4687
        s.mu.Lock()
×
UNCOV
4688
        defer s.mu.Unlock()
×
UNCOV
4689

×
UNCOV
4690
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4691
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4692
        // connection requests for the associated address and then any leftover
×
UNCOV
4693
        // entries will indicate which addresses we should create new
×
UNCOV
4694
        // connection requests for.
×
UNCOV
4695
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4696
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4697
                addrMap[addr.String()] = addr
×
UNCOV
4698
        }
×
4699

4700
        // Go through each of the existing connection requests and
4701
        // check if they correspond to the latest set of addresses. If
4702
        // there is a connection requests that does not use one of the latest
4703
        // advertised addresses then remove that connection request.
UNCOV
4704
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4705
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4706
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4707

×
UNCOV
4708
                switch _, ok := addrMap[lnAddr]; ok {
×
4709
                // If the existing connection request is using one of the
4710
                // latest advertised addresses for the peer then we add it to
4711
                // updatedConnReqs and remove the associated address from
4712
                // addrMap so that we don't recreate this connReq later on.
4713
                case true:
×
4714
                        updatedConnReqs = append(
×
4715
                                updatedConnReqs, connReq,
×
4716
                        )
×
4717
                        delete(addrMap, lnAddr)
×
4718

4719
                // If the existing connection request is using an address that
4720
                // is not one of the latest advertised addresses for the peer
4721
                // then we remove the connecting request from the connection
4722
                // manager.
UNCOV
4723
                case false:
×
UNCOV
4724
                        srvrLog.Info(
×
UNCOV
4725
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4726
                        )
×
UNCOV
4727
                        s.connMgr.Remove(connReq.ID())
×
4728
                }
4729
        }
4730

UNCOV
4731
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4732

×
UNCOV
4733
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4734
        if !ok {
×
UNCOV
4735
                cancelChan = make(chan struct{})
×
UNCOV
4736
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4737
        }
×
4738

4739
        // Any addresses left in addrMap are new ones that we have not made
4740
        // connection requests for. So create new connection requests for those.
4741
        // If there is more than one address in the address map, stagger the
4742
        // creation of the connection requests for those.
UNCOV
4743
        go func() {
×
UNCOV
4744
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
4745
                defer ticker.Stop()
×
UNCOV
4746

×
UNCOV
4747
                for _, addr := range addrMap {
×
UNCOV
4748
                        // Send the persistent connection request to the
×
UNCOV
4749
                        // connection manager, saving the request itself so we
×
UNCOV
4750
                        // can cancel/restart the process as needed.
×
UNCOV
4751
                        connReq := &connmgr.ConnReq{
×
UNCOV
4752
                                Addr:      addr,
×
UNCOV
4753
                                Permanent: true,
×
UNCOV
4754
                        }
×
UNCOV
4755

×
UNCOV
4756
                        s.mu.Lock()
×
UNCOV
4757
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4758
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4759
                        )
×
UNCOV
4760
                        s.mu.Unlock()
×
UNCOV
4761

×
UNCOV
4762
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4763
                                "channel peer %v", addr)
×
UNCOV
4764

×
UNCOV
4765
                        go s.connMgr.Connect(connReq)
×
UNCOV
4766

×
UNCOV
4767
                        select {
×
UNCOV
4768
                        case <-s.quit:
×
UNCOV
4769
                                return
×
UNCOV
4770
                        case <-cancelChan:
×
UNCOV
4771
                                return
×
UNCOV
4772
                        case <-ticker.C:
×
4773
                        }
4774
                }
4775
        }()
4776
}
4777

4778
// removePeer removes the passed peer from the server's state of all active
4779
// peers.
UNCOV
4780
func (s *server) removePeer(p *peer.Brontide) {
×
UNCOV
4781
        if p == nil {
×
4782
                return
×
4783
        }
×
4784

UNCOV
4785
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4786

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

×
UNCOV
4791
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4792
        if p.ConnReq() != nil {
×
UNCOV
4793
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4794
        }
×
4795

4796
        // Ignore deleting peers if we're shutting down.
UNCOV
4797
        if s.Stopped() {
×
4798
                return
×
4799
        }
×
4800

UNCOV
4801
        pKey := p.PubKey()
×
UNCOV
4802
        pubSer := pKey[:]
×
UNCOV
4803
        pubStr := string(pubSer)
×
UNCOV
4804

×
UNCOV
4805
        delete(s.peersByPub, pubStr)
×
UNCOV
4806

×
UNCOV
4807
        if p.Inbound() {
×
UNCOV
4808
                delete(s.inboundPeers, pubStr)
×
UNCOV
4809
        } else {
×
UNCOV
4810
                delete(s.outboundPeers, pubStr)
×
UNCOV
4811
        }
×
4812

4813
        // Copy the peer's error buffer across to the server if it has any items
4814
        // in it so that we can restore peer errors across connections.
UNCOV
4815
        if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4816
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4817
        }
×
4818

4819
        // Inform the peer notifier of a peer offline event so that it can be
4820
        // reported to clients listening for peer events.
UNCOV
4821
        var pubKey [33]byte
×
UNCOV
4822
        copy(pubKey[:], pubSer)
×
UNCOV
4823

×
UNCOV
4824
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4825
}
4826

4827
// ConnectToPeer requests that the server connect to a Lightning Network peer
4828
// at the specified address. This function will *block* until either a
4829
// connection is established, or the initial handshake process fails.
4830
//
4831
// NOTE: This function is safe for concurrent access.
4832
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
4833
        perm bool, timeout time.Duration) error {
×
UNCOV
4834

×
UNCOV
4835
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4836

×
UNCOV
4837
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
4838
        // better granularity.  In certain conditions, this method requires
×
UNCOV
4839
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4840
        // lock to be released, and subsequently reacquired.
×
UNCOV
4841
        s.mu.Lock()
×
UNCOV
4842

×
UNCOV
4843
        // Ensure we're not already connected to this peer.
×
UNCOV
4844
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4845
        if err == nil {
×
UNCOV
4846
                s.mu.Unlock()
×
UNCOV
4847
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4848
        }
×
4849

4850
        // Peer was not found, continue to pursue connection with peer.
4851

4852
        // If there's already a pending connection request for this pubkey,
4853
        // then we ignore this request to ensure we don't create a redundant
4854
        // connection.
UNCOV
4855
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
4856
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
4857
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4858
        }
×
4859

4860
        // If there's not already a pending or active connection to this node,
4861
        // then instruct the connection manager to attempt to establish a
4862
        // persistent connection to the peer.
UNCOV
4863
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4864
        if perm {
×
UNCOV
4865
                connReq := &connmgr.ConnReq{
×
UNCOV
4866
                        Addr:      addr,
×
UNCOV
4867
                        Permanent: true,
×
UNCOV
4868
                }
×
UNCOV
4869

×
UNCOV
4870
                // Since the user requested a permanent connection, we'll set
×
UNCOV
4871
                // the entry to true which will tell the server to continue
×
UNCOV
4872
                // reconnecting even if the number of channels with this peer is
×
UNCOV
4873
                // zero.
×
UNCOV
4874
                s.persistentPeers[targetPub] = true
×
UNCOV
4875
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4876
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4877
                }
×
UNCOV
4878
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4879
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4880
                )
×
UNCOV
4881
                s.mu.Unlock()
×
UNCOV
4882

×
UNCOV
4883
                go s.connMgr.Connect(connReq)
×
UNCOV
4884

×
UNCOV
4885
                return nil
×
4886
        }
UNCOV
4887
        s.mu.Unlock()
×
UNCOV
4888

×
UNCOV
4889
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4890
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
4891
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
4892
        // caller.
×
UNCOV
4893
        errChan := make(chan error, 1)
×
UNCOV
4894
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
4895

×
UNCOV
4896
        select {
×
UNCOV
4897
        case err := <-errChan:
×
UNCOV
4898
                return err
×
4899
        case <-s.quit:
×
4900
                return ErrServerShuttingDown
×
4901
        }
4902
}
4903

4904
// connectToPeer establishes a connection to a remote peer. errChan is used to
4905
// notify the caller if the connection attempt has failed. Otherwise, it will be
4906
// closed.
4907
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
4908
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4909

×
UNCOV
4910
        conn, err := brontide.Dial(
×
UNCOV
4911
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4912
        )
×
UNCOV
4913
        if err != nil {
×
UNCOV
4914
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4915
                select {
×
UNCOV
4916
                case errChan <- err:
×
4917
                case <-s.quit:
×
4918
                }
UNCOV
4919
                return
×
4920
        }
4921

UNCOV
4922
        close(errChan)
×
UNCOV
4923

×
UNCOV
4924
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
4925
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4926

×
UNCOV
4927
        s.OutboundPeerConnected(nil, conn)
×
4928
}
4929

4930
// DisconnectPeer sends the request to server to close the connection with peer
4931
// identified by public key.
4932
//
4933
// NOTE: This function is safe for concurrent access.
UNCOV
4934
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
4935
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
4936
        pubStr := string(pubBytes)
×
UNCOV
4937

×
UNCOV
4938
        s.mu.Lock()
×
UNCOV
4939
        defer s.mu.Unlock()
×
UNCOV
4940

×
UNCOV
4941
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
4942
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
4943
        // currently connected to.
×
UNCOV
4944
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4945
        if err == ErrPeerNotConnected {
×
UNCOV
4946
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
4947
        }
×
4948

UNCOV
4949
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
4950

×
UNCOV
4951
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
4952

×
UNCOV
4953
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
4954
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
4955
        // disconnect.
×
UNCOV
4956
        delete(s.persistentPeers, pubStr)
×
UNCOV
4957
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
4958

×
UNCOV
4959
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
4960
        // removePeer, which bypassed the peerTerminationWatcher.
×
UNCOV
4961
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
4962

×
UNCOV
4963
        return nil
×
4964
}
4965

4966
// OpenChannel sends a request to the server to open a channel to the specified
4967
// peer identified by nodeKey with the passed channel funding parameters.
4968
//
4969
// NOTE: This function is safe for concurrent access.
4970
func (s *server) OpenChannel(
UNCOV
4971
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
4972

×
UNCOV
4973
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
4974
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
4975
        // not blocked if the caller is not reading the updates.
×
UNCOV
4976
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
4977
        req.Err = make(chan error, 1)
×
UNCOV
4978

×
UNCOV
4979
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
4980
        // we're unable to locate the peer then this request will fail.
×
UNCOV
4981
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
4982
        s.mu.RLock()
×
UNCOV
4983
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
4984
        if !ok {
×
4985
                s.mu.RUnlock()
×
4986

×
4987
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4988
                return req.Updates, req.Err
×
4989
        }
×
UNCOV
4990
        req.Peer = peer
×
UNCOV
4991
        s.mu.RUnlock()
×
UNCOV
4992

×
UNCOV
4993
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
4994
        // opening process.
×
UNCOV
4995
        select {
×
UNCOV
4996
        case <-peer.ActiveSignal():
×
4997
        case <-peer.QuitSignal():
×
4998
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4999
                return req.Updates, req.Err
×
5000
        case <-s.quit:
×
5001
                req.Err <- ErrServerShuttingDown
×
5002
                return req.Updates, req.Err
×
5003
        }
5004

5005
        // If the fee rate wasn't specified at this point we fail the funding
5006
        // because of the missing fee rate information. The caller of the
5007
        // `OpenChannel` method needs to make sure that default values for the
5008
        // fee rate are set beforehand.
UNCOV
5009
        if req.FundingFeePerKw == 0 {
×
5010
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5011
                        "the channel opening transaction")
×
5012

×
5013
                return req.Updates, req.Err
×
5014
        }
×
5015

5016
        // Spawn a goroutine to send the funding workflow request to the funding
5017
        // manager. This allows the server to continue handling queries instead
5018
        // of blocking on this request which is exported as a synchronous
5019
        // request to the outside world.
UNCOV
5020
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
5021

×
UNCOV
5022
        return req.Updates, req.Err
×
5023
}
5024

5025
// Peers returns a slice of all active peers.
5026
//
5027
// NOTE: This function is safe for concurrent access.
UNCOV
5028
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
5029
        s.mu.RLock()
×
UNCOV
5030
        defer s.mu.RUnlock()
×
UNCOV
5031

×
UNCOV
5032
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
5033
        for _, peer := range s.peersByPub {
×
UNCOV
5034
                peers = append(peers, peer)
×
UNCOV
5035
        }
×
5036

UNCOV
5037
        return peers
×
5038
}
5039

5040
// computeNextBackoff uses a truncated exponential backoff to compute the next
5041
// backoff using the value of the exiting backoff. The returned duration is
5042
// randomized in either direction by 1/20 to prevent tight loops from
5043
// stabilizing.
UNCOV
5044
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
5045
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
5046
        nextBackoff := 2 * currBackoff
×
UNCOV
5047
        if nextBackoff > maxBackoff {
×
UNCOV
5048
                nextBackoff = maxBackoff
×
UNCOV
5049
        }
×
5050

5051
        // Using 1/10 of our duration as a margin, compute a random offset to
5052
        // avoid the nodes entering connection cycles.
UNCOV
5053
        margin := nextBackoff / 10
×
UNCOV
5054

×
UNCOV
5055
        var wiggle big.Int
×
UNCOV
5056
        wiggle.SetUint64(uint64(margin))
×
UNCOV
5057
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
5058
                // Randomizing is not mission critical, so we'll just return the
×
5059
                // current backoff.
×
5060
                return nextBackoff
×
5061
        }
×
5062

5063
        // Otherwise add in our wiggle, but subtract out half of the margin so
5064
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
5065
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
5066
}
5067

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

5072
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
UNCOV
5073
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
5074
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
5075
        if err != nil {
×
5076
                return nil, err
×
5077
        }
×
5078

UNCOV
5079
        node, err := s.graphDB.FetchLightningNode(vertex)
×
UNCOV
5080
        if err != nil {
×
UNCOV
5081
                return nil, err
×
UNCOV
5082
        }
×
5083

UNCOV
5084
        if len(node.Addresses) == 0 {
×
UNCOV
5085
                return nil, errNoAdvertisedAddr
×
UNCOV
5086
        }
×
5087

UNCOV
5088
        return node.Addresses, nil
×
5089
}
5090

5091
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5092
// channel update for a target channel.
5093
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
5094
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
5095

×
UNCOV
5096
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
5097
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
5098
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
5099
                if err != nil {
×
UNCOV
5100
                        return nil, err
×
UNCOV
5101
                }
×
5102

UNCOV
5103
                return netann.ExtractChannelUpdate(
×
UNCOV
5104
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
5105
                )
×
5106
        }
5107
}
5108

5109
// applyChannelUpdate applies the channel update to the different sub-systems of
5110
// the server. The useAlias boolean denotes whether or not to send an alias in
5111
// place of the real SCID.
5112
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
5113
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5114

×
UNCOV
5115
        var (
×
UNCOV
5116
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5117
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5118
        )
×
UNCOV
5119

×
UNCOV
5120
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5121

×
UNCOV
5122
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5123
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5124
        if useAlias {
×
UNCOV
5125
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5126
                if foundAlias != defaultAlias {
×
UNCOV
5127
                        peerAlias = &foundAlias
×
UNCOV
5128
                }
×
5129
        }
5130

UNCOV
5131
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5132
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5133
        )
×
UNCOV
5134
        select {
×
UNCOV
5135
        case err := <-errChan:
×
UNCOV
5136
                return err
×
5137
        case <-s.quit:
×
5138
                return ErrServerShuttingDown
×
5139
        }
5140
}
5141

5142
// SendCustomMessage sends a custom message to the peer with the specified
5143
// pubkey.
5144
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5145
        data []byte) error {
×
UNCOV
5146

×
UNCOV
5147
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5148
        if err != nil {
×
5149
                return err
×
5150
        }
×
5151

5152
        // We'll wait until the peer is active.
UNCOV
5153
        select {
×
UNCOV
5154
        case <-peer.ActiveSignal():
×
5155
        case <-peer.QuitSignal():
×
5156
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5157
        case <-s.quit:
×
5158
                return ErrServerShuttingDown
×
5159
        }
5160

UNCOV
5161
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5162
        if err != nil {
×
UNCOV
5163
                return err
×
UNCOV
5164
        }
×
5165

5166
        // Send the message as low-priority. For now we assume that all
5167
        // application-defined message are low priority.
UNCOV
5168
        return peer.SendMessageLazy(true, msg)
×
5169
}
5170

5171
// newSweepPkScriptGen creates closure that generates a new public key script
5172
// which should be used to sweep any funds into the on-chain wallet.
5173
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5174
// (p2wkh) output.
5175
func newSweepPkScriptGen(
5176
        wallet lnwallet.WalletController,
UNCOV
5177
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5178

×
UNCOV
5179
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5180
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5181
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5182
                        lnwallet.DefaultAccountName,
×
UNCOV
5183
                )
×
UNCOV
5184
                if err != nil {
×
5185
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5186
                }
×
5187

UNCOV
5188
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5189
                if err != nil {
×
5190
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5191
                }
×
5192

UNCOV
5193
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5194
                        wallet, netParams, addr,
×
UNCOV
5195
                )
×
UNCOV
5196
                if err != nil {
×
5197
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5198
                }
×
5199

UNCOV
5200
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5201
                        DeliveryAddress: addr,
×
UNCOV
5202
                        InternalKey:     internalKeyDesc,
×
UNCOV
5203
                })
×
5204
        }
5205
}
5206

5207
// shouldPeerBootstrap returns true if we should attempt to perform peer
5208
// bootstrapping to actively seek our peers using the set of active network
5209
// bootstrappers.
5210
func shouldPeerBootstrap(cfg *Config) bool {
6✔
5211
        isSimnet := cfg.Bitcoin.SimNet
6✔
5212
        isSignet := cfg.Bitcoin.SigNet
6✔
5213
        isRegtest := cfg.Bitcoin.RegTest
6✔
5214
        isDevNetwork := isSimnet || isSignet || isRegtest
6✔
5215

6✔
5216
        // TODO(yy): remove the check on simnet/regtest such that the itest is
6✔
5217
        // covering the bootstrapping process.
6✔
5218
        return !cfg.NoNetBootstrap && !isDevNetwork
6✔
5219
}
6✔
5220

5221
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5222
// finished.
UNCOV
5223
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5224
        // Get a list of closed channels.
×
UNCOV
5225
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5226
        if err != nil {
×
5227
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5228
                return nil
×
5229
        }
×
5230

5231
        // Save the SCIDs in a map.
UNCOV
5232
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5233
        for _, c := range channels {
×
UNCOV
5234
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5235
                if !c.IsPending {
×
UNCOV
5236
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5237
                }
×
5238
        }
5239

5240
        // Double check whether the reported closed channel has indeed finished
5241
        // closing.
5242
        //
5243
        // NOTE: There are misalignments regarding when a channel's FC is
5244
        // marked as finalized. We double check the pending channels to make
5245
        // sure the returned SCIDs are indeed terminated.
5246
        //
5247
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5248
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5249
        if err != nil {
×
5250
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5251
                return nil
×
5252
        }
×
5253

UNCOV
5254
        for _, c := range pendings {
×
UNCOV
5255
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5256
                        continue
×
5257
                }
5258

5259
                // If the channel is still reported as pending, remove it from
5260
                // the map.
5261
                delete(closedSCIDs, c.ShortChannelID)
×
5262

×
5263
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5264
                        c.ShortChannelID)
×
5265
        }
5266

UNCOV
5267
        return closedSCIDs
×
5268
}
5269

5270
// getStartingBeat returns the current beat. This is used during the startup to
5271
// initialize blockbeat consumers.
UNCOV
5272
func (s *server) getStartingBeat() (*chainio.Beat, error) {
×
UNCOV
5273
        // beat is the current blockbeat.
×
UNCOV
5274
        var beat *chainio.Beat
×
UNCOV
5275

×
UNCOV
5276
        // We should get a notification with the current best block immediately
×
UNCOV
5277
        // by passing a nil block.
×
UNCOV
5278
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
×
UNCOV
5279
        if err != nil {
×
5280
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5281
        }
×
UNCOV
5282
        defer blockEpochs.Cancel()
×
UNCOV
5283

×
UNCOV
5284
        // We registered for the block epochs with a nil request. The notifier
×
UNCOV
5285
        // should send us the current best block immediately. So we need to
×
UNCOV
5286
        // wait for it here because we need to know the current best height.
×
UNCOV
5287
        select {
×
UNCOV
5288
        case bestBlock := <-blockEpochs.Epochs:
×
UNCOV
5289
                srvrLog.Infof("Received initial block %v at height %d",
×
UNCOV
5290
                        bestBlock.Hash, bestBlock.Height)
×
UNCOV
5291

×
UNCOV
5292
                // Update the current blockbeat.
×
UNCOV
5293
                beat = chainio.NewBeat(*bestBlock)
×
5294

5295
        case <-s.quit:
×
5296
                srvrLog.Debug("LND shutting down")
×
5297
        }
5298

UNCOV
5299
        return beat, nil
×
5300
}
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