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

lightningnetwork / lnd / 12058234999

27 Nov 2024 09:06PM UTC coverage: 57.847% (-1.1%) from 58.921%
12058234999

Pull #9148

github

ProofOfKeags
lnwire: convert DynPropose and DynCommit to use typed tlv records
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

142 of 177 new or added lines in 4 files covered. (80.23%)

19365 existing lines in 251 files now uncovered.

100876 of 174383 relevant lines covered (57.85%)

25338.28 hits per line

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

0.29
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

165
        start sync.Once
166
        stop  sync.Once
167

168
        cfg *Config
169

170
        implCfg *ImplementationCfg
171

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

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

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

183
        chanStatusMgr *netann.ChanStatusManager
184

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

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

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

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

205
        mu sync.RWMutex
206

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

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

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

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

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

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

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

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

257
        cc *chainreg.ChainControl
258

259
        fundingMgr *funding.Manager
260

261
        graphDB *channeldb.ChannelGraph
262

263
        chanStateDB *channeldb.ChannelStateDB
264

265
        addrSource chanbackup.AddressSource
266

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

271
        invoicesDB invoices.InvoiceDB
272

273
        aliasMgr *aliasmgr.Manager
274

275
        htlcSwitch *htlcswitch.Switch
276

277
        interceptableSwitch *htlcswitch.InterceptableSwitch
278

279
        invoices *invoices.InvoiceRegistry
280

281
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
282

283
        channelNotifier *channelnotifier.ChannelNotifier
284

285
        peerNotifier *peernotifier.PeerNotifier
286

287
        htlcNotifier *htlcswitch.HtlcNotifier
288

289
        witnessBeacon contractcourt.WitnessBeacon
290

291
        breachArbitrator *contractcourt.BreachArbitrator
292

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

296
        graphBuilder *graph.Builder
297

298
        chanRouter *routing.ChannelRouter
299

300
        controlTower routing.ControlTower
301

302
        authGossiper *discovery.AuthenticatedGossiper
303

304
        localChanMgr *localchans.Manager
305

306
        utxoNursery *contractcourt.UtxoNursery
307

308
        sweeper *sweep.UtxoSweeper
309

310
        chainArb *contractcourt.ChainArbitrator
311

312
        sphinx *hop.OnionProcessor
313

314
        towerClientMgr *wtclient.Manager
315

316
        connMgr *connmgr.ConnManager
317

318
        sigPool *lnwallet.SigPool
319

320
        writePool *pool.Write
321

322
        readPool *pool.Read
323

324
        tlsManager *TLSManager
325

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

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

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

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

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

348
        hostAnn *netann.HostAnnouncer
349

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

353
        customMessageServer *subscribe.Server
354

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

358
        quit chan struct{}
359

360
        wg sync.WaitGroup
361
}
362

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
442
        return nil
×
443
}
444

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
623
                channelNotifier: channelnotifier.New(
×
UNCOV
624
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
625
                ),
×
UNCOV
626

×
UNCOV
627
                identityECDH:   nodeKeyECDH,
×
UNCOV
628
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
629
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
630

×
UNCOV
631
                listenAddrs: listenAddrs,
×
UNCOV
632

×
UNCOV
633
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
634
                // schedule
×
UNCOV
635
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
636

×
UNCOV
637
                torController: torController,
×
UNCOV
638

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

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

×
UNCOV
655
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
656

×
UNCOV
657
                customMessageServer: subscribe.NewServer(),
×
UNCOV
658

×
UNCOV
659
                tlsManager: tlsManager,
×
UNCOV
660

×
UNCOV
661
                featureMgr: featureMgr,
×
UNCOV
662
                quit:       make(chan struct{}),
×
UNCOV
663
        }
×
UNCOV
664

×
UNCOV
665
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
666
        if err != nil {
×
667
                return nil, err
×
668
        }
×
669

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

×
UNCOV
678
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
679

×
UNCOV
680
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
681
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
682

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

UNCOV
689
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
690

×
UNCOV
691
                return nil
×
692
        }
693

UNCOV
694
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
695
        if err != nil {
×
696
                return nil, err
×
697
        }
×
698

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

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

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

UNCOV
751
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
752
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
753
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
754
        )
×
UNCOV
755

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

×
UNCOV
769
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
770
        if err != nil {
×
771
                return nil, err
×
772
        }
×
UNCOV
773
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
774

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

×
780
                discoveryTimeout := time.Duration(10 * time.Second)
×
781

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

×
796
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
797
                                "enabled device")
×
798

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

808
                        s.natTraversal = pmp
×
809
                }
810
        }
811

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

×
827
                        listenPorts = append(listenPorts, uint16(port))
×
828
                }
×
829

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

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

UNCOV
853
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
UNCOV
854
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
855

×
UNCOV
856
        // As the graph can be obtained at anytime from the network, we won't
×
UNCOV
857
        // replicate it, and instead it'll only be stored locally.
×
UNCOV
858
        chanGraph := dbs.GraphDB.ChannelGraph()
×
UNCOV
859

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
1438
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1439
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1440

×
UNCOV
1441
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1442
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1443
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1444
        }
×
1445

1446
        //nolint:lll
UNCOV
1447
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1448
                Dev:                devCfg,
×
UNCOV
1449
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1450
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1451
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1452
                Wallet:             cc.Wallet,
×
UNCOV
1453
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1454
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1455
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1456
                },
×
1457
                Notifier:     cc.ChainNotifier,
1458
                ChannelDB:    s.chanStateDB,
1459
                FeeEstimator: cc.FeeEstimator,
1460
                SignMessage:  cc.MsgSigner.SignMessage,
1461
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1462
                        error) {
×
UNCOV
1463

×
UNCOV
1464
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1465
                },
×
1466
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1467
                NotifyWhenOnline:     s.NotifyWhenOnline,
1468
                TempChanIDSeed:       chanIDSeed,
1469
                FindChannel:          s.findChannel,
1470
                DefaultRoutingPolicy: cc.RoutingPolicy,
1471
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1472
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1473
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1474
                        // For large channels we increase the number
×
UNCOV
1475
                        // of confirmations we require for the
×
UNCOV
1476
                        // channel to be considered open. As it is
×
UNCOV
1477
                        // always the responder that gets to choose
×
UNCOV
1478
                        // value, the pushAmt is value being pushed
×
UNCOV
1479
                        // to us. This means we have more to lose
×
UNCOV
1480
                        // in the case this gets re-orged out, and
×
UNCOV
1481
                        // we will require more confirmations before
×
UNCOV
1482
                        // we consider it open.
×
UNCOV
1483

×
UNCOV
1484
                        // In case the user has explicitly specified
×
UNCOV
1485
                        // a default value for the number of
×
UNCOV
1486
                        // confirmations, we use it.
×
UNCOV
1487
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1488
                        if defaultConf != 0 {
×
UNCOV
1489
                                return defaultConf
×
UNCOV
1490
                        }
×
1491

1492
                        minConf := uint64(3)
×
1493
                        maxConf := uint64(6)
×
1494

×
1495
                        // If this is a wumbo channel, then we'll require the
×
1496
                        // max amount of confirmations.
×
1497
                        if chanAmt > MaxFundingAmount {
×
1498
                                return uint16(maxConf)
×
1499
                        }
×
1500

1501
                        // If not we return a value scaled linearly
1502
                        // between 3 and 6, depending on channel size.
1503
                        // TODO(halseth): Use 1 as minimum?
1504
                        maxChannelSize := uint64(
×
1505
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1506
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1507
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1508
                        if conf < minConf {
×
1509
                                conf = minConf
×
1510
                        }
×
1511
                        if conf > maxConf {
×
1512
                                conf = maxConf
×
1513
                        }
×
1514
                        return uint16(conf)
×
1515
                },
UNCOV
1516
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1517
                        // We scale the remote CSV delay (the time the
×
UNCOV
1518
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1519
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1520
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1521
                        // for channels of size MaxFundingAmount.
×
UNCOV
1522

×
UNCOV
1523
                        // In case the user has explicitly specified
×
UNCOV
1524
                        // a default value for the remote delay, we
×
UNCOV
1525
                        // use it.
×
UNCOV
1526
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1527
                        if defaultDelay > 0 {
×
UNCOV
1528
                                return defaultDelay
×
UNCOV
1529
                        }
×
1530

1531
                        // If this is a wumbo channel, then we'll require the
1532
                        // max value.
1533
                        if chanAmt > MaxFundingAmount {
×
1534
                                return maxRemoteDelay
×
1535
                        }
×
1536

1537
                        // If not we scale according to channel size.
1538
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1539
                                chanAmt / MaxFundingAmount)
×
1540
                        if delay < minRemoteDelay {
×
1541
                                delay = minRemoteDelay
×
1542
                        }
×
1543
                        if delay > maxRemoteDelay {
×
1544
                                delay = maxRemoteDelay
×
1545
                        }
×
1546
                        return delay
×
1547
                },
1548
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1549
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1550

×
UNCOV
1551
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1552
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1553
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1554
                        // we'll set false to prevent the server from continuing
×
UNCOV
1555
                        // to connect to this peer even if the number of
×
UNCOV
1556
                        // channels with this peer is zero.
×
UNCOV
1557
                        s.mu.Lock()
×
UNCOV
1558
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1559
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1560
                                s.persistentPeers[pubStr] = false
×
UNCOV
1561
                        }
×
UNCOV
1562
                        s.mu.Unlock()
×
UNCOV
1563

×
UNCOV
1564
                        // With that taken care of, we'll send this channel to
×
UNCOV
1565
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1566
                        return s.chainArb.WatchNewChannel(channel)
×
1567
                },
UNCOV
1568
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1569
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1570
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1571
                },
×
1572
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1573
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1574

×
UNCOV
1575
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1576
                        // at least 1% of the total channel capacity at all
×
UNCOV
1577
                        // times. If this value ends up dipping below the dust
×
UNCOV
1578
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1579
                        // reserve as required by BOLT #2.
×
UNCOV
1580
                        reserve := chanAmt / 100
×
UNCOV
1581
                        if reserve < dustLimit {
×
UNCOV
1582
                                reserve = dustLimit
×
UNCOV
1583
                        }
×
1584

UNCOV
1585
                        return reserve
×
1586
                },
UNCOV
1587
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1588
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1589
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1590
                        // required reserve.
×
UNCOV
1591
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1592
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1593
                },
×
UNCOV
1594
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1595
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1596
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1597
                        }
×
1598

1599
                        // By default, we'll permit them to utilize the full
1600
                        // channel bandwidth.
1601
                        return uint16(input.MaxHTLCNumber / 2)
×
1602
                },
1603
                ZombieSweeperInterval:         zombieSweeperInterval,
1604
                ReservationTimeout:            reservationTimeout,
1605
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1606
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1607
                MaxPendingChannels:            cfg.MaxPendingChannels,
1608
                RejectPush:                    cfg.RejectPush,
1609
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1610
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1611
                OpenChannelPredicate:          chanPredicate,
1612
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1613
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1614
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1615
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1616
                DeleteAliasEdge:      deleteAliasEdge,
1617
                AliasManager:         s.aliasMgr,
1618
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1619
                AuxFundingController: implCfg.AuxFundingController,
1620
                AuxSigner:            implCfg.AuxSigner,
1621
                AuxResolver:          implCfg.AuxContractResolver,
1622
        })
UNCOV
1623
        if err != nil {
×
1624
                return nil, err
×
1625
        }
×
1626

1627
        // Next, we'll assemble the sub-system that will maintain an on-disk
1628
        // static backup of the latest channel state.
UNCOV
1629
        chanNotifier := &channelNotifier{
×
UNCOV
1630
                chanNotifier: s.channelNotifier,
×
UNCOV
1631
                addrs:        dbs.ChanStateDB,
×
UNCOV
1632
        }
×
UNCOV
1633
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
×
UNCOV
1634
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1635
                s.chanStateDB, s.addrSource,
×
UNCOV
1636
        )
×
UNCOV
1637
        if err != nil {
×
1638
                return nil, err
×
1639
        }
×
UNCOV
1640
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1641
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1642
        )
×
UNCOV
1643
        if err != nil {
×
1644
                return nil, err
×
1645
        }
×
1646

1647
        // Assemble a peer notifier which will provide clients with subscriptions
1648
        // to peer online and offline events.
UNCOV
1649
        s.peerNotifier = peernotifier.New()
×
UNCOV
1650

×
UNCOV
1651
        // Create a channel event store which monitors all open channels.
×
UNCOV
1652
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1653
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1654
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1655
                },
×
UNCOV
1656
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1657
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1658
                },
×
1659
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1660
                Clock:           clock.NewDefaultClock(),
1661
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1662
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1663
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1664
        })
1665

UNCOV
1666
        if cfg.WtClient.Active {
×
UNCOV
1667
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1668
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1669

×
UNCOV
1670
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1671
                // protocol operations on sat/kw.
×
UNCOV
1672
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1673
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1674
                )
×
UNCOV
1675

×
UNCOV
1676
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1677

×
UNCOV
1678
                if err := policy.Validate(); err != nil {
×
1679
                        return nil, err
×
1680
                }
×
1681

1682
                // authDial is the wrapper around the btrontide.Dial for the
1683
                // watchtower.
UNCOV
1684
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1685
                        netAddr *lnwire.NetAddress,
×
UNCOV
1686
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1687

×
UNCOV
1688
                        return brontide.Dial(
×
UNCOV
1689
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1690
                        )
×
UNCOV
1691
                }
×
1692

1693
                // buildBreachRetribution is a call-back that can be used to
1694
                // query the BreachRetribution info and channel type given a
1695
                // channel ID and commitment height.
UNCOV
1696
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1697
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1698
                        channeldb.ChannelType, error) {
×
UNCOV
1699

×
UNCOV
1700
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1701
                                nil, chanID,
×
UNCOV
1702
                        )
×
UNCOV
1703
                        if err != nil {
×
1704
                                return nil, 0, err
×
1705
                        }
×
1706

UNCOV
1707
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1708
                                channel, commitHeight, 0, nil,
×
UNCOV
1709
                                implCfg.AuxLeafStore,
×
UNCOV
1710
                                implCfg.AuxContractResolver,
×
UNCOV
1711
                        )
×
UNCOV
1712
                        if err != nil {
×
1713
                                return nil, 0, err
×
1714
                        }
×
1715

UNCOV
1716
                        return br, channel.ChanType, nil
×
1717
                }
1718

UNCOV
1719
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1720

×
UNCOV
1721
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1722
                // signalling support for anchor channels.
×
UNCOV
1723
                anchorPolicy := policy
×
UNCOV
1724
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1725

×
UNCOV
1726
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1727
                // signalling support for taproot channels.
×
UNCOV
1728
                taprootPolicy := policy
×
UNCOV
1729
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1730
                        blob.FlagTaprootChannel,
×
UNCOV
1731
                )
×
UNCOV
1732

×
UNCOV
1733
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1734
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1735
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1736
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1737
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1738
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1739
                                error) {
×
UNCOV
1740

×
UNCOV
1741
                                return s.channelNotifier.
×
UNCOV
1742
                                        SubscribeChannelEvents()
×
UNCOV
1743
                        },
×
1744
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1745
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1746
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1747
                                        cc.Wallet, netParams,
×
UNCOV
1748
                                )().Unpack()
×
UNCOV
1749
                                if err != nil {
×
1750
                                        return nil, err
×
1751
                                }
×
1752

UNCOV
1753
                                return addr.DeliveryAddress, nil
×
1754
                        },
1755
                        SecretKeyRing:      s.cc.KeyRing,
1756
                        Dial:               cfg.net.Dial,
1757
                        AuthDial:           authDial,
1758
                        DB:                 dbs.TowerClientDB,
1759
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1760
                        MinBackoff:         10 * time.Second,
1761
                        MaxBackoff:         5 * time.Minute,
1762
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1763
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1764
                if err != nil {
×
1765
                        return nil, err
×
1766
                }
×
1767
        }
1768

UNCOV
1769
        if len(cfg.ExternalHosts) != 0 {
×
1770
                advertisedIPs := make(map[string]struct{})
×
1771
                for _, addr := range s.currentNodeAnn.Addresses {
×
1772
                        advertisedIPs[addr.String()] = struct{}{}
×
1773
                }
×
1774

1775
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1776
                        Hosts:         cfg.ExternalHosts,
×
1777
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1778
                        LookupHost: func(host string) (net.Addr, error) {
×
1779
                                return lncfg.ParseAddressString(
×
1780
                                        host, strconv.Itoa(defaultPeerPort),
×
1781
                                        cfg.net.ResolveTCPAddr,
×
1782
                                )
×
1783
                        },
×
1784
                        AdvertisedIPs: advertisedIPs,
1785
                        AnnounceNewIPs: netann.IPAnnouncer(
1786
                                func(modifier ...netann.NodeAnnModifier) (
1787
                                        lnwire.NodeAnnouncement, error) {
×
1788

×
1789
                                        return s.genNodeAnnouncement(
×
1790
                                                nil, modifier...,
×
1791
                                        )
×
1792
                                }),
×
1793
                })
1794
        }
1795

1796
        // Create liveness monitor.
UNCOV
1797
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1798

×
UNCOV
1799
        // Create the connection manager which will be responsible for
×
UNCOV
1800
        // maintaining persistent outbound connections and also accepting new
×
UNCOV
1801
        // incoming connections
×
UNCOV
1802
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1803
                Listeners:      listeners,
×
UNCOV
1804
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1805
                RetryDuration:  time.Second * 5,
×
UNCOV
1806
                TargetOutbound: 100,
×
UNCOV
1807
                Dial: noiseDial(
×
UNCOV
1808
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1809
                ),
×
UNCOV
1810
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1811
        })
×
UNCOV
1812
        if err != nil {
×
1813
                return nil, err
×
1814
        }
×
UNCOV
1815
        s.connMgr = cmgr
×
UNCOV
1816

×
UNCOV
1817
        return s, nil
×
1818
}
1819

1820
// UpdateRoutingConfig is a callback function to update the routing config
1821
// values in the main cfg.
UNCOV
1822
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1823
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1824

×
UNCOV
1825
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1826
        case routing.AprioriConfig:
×
UNCOV
1827
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1828
                        routing.AprioriEstimatorName
×
UNCOV
1829

×
UNCOV
1830
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1831
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1832
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1833
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1834
                targetCfg.HopProbability = c.AprioriHopProbability
×
1835

UNCOV
1836
        case routing.BimodalConfig:
×
UNCOV
1837
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1838
                        routing.BimodalEstimatorName
×
UNCOV
1839

×
UNCOV
1840
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1841
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1842
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1843
                targetCfg.DecayTime = c.BimodalDecayTime
×
1844
        }
1845

UNCOV
1846
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1847
}
1848

1849
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1850
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1851
// may differ from what is on disk.
1852
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1853
        error) {
×
UNCOV
1854

×
UNCOV
1855
        data, err := u.DataToSign()
×
UNCOV
1856
        if err != nil {
×
1857
                return nil, err
×
1858
        }
×
1859

UNCOV
1860
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1861
}
1862

1863
// createLivenessMonitor creates a set of health checks using our configured
1864
// values and uses these checks to create a liveness monitor. Available
1865
// health checks,
1866
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1867
//   - diskCheck
1868
//   - tlsHealthCheck
1869
//   - torController, only created when tor is enabled.
1870
//
1871
// If a health check has been disabled by setting attempts to 0, our monitor
1872
// will not run it.
1873
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
1874
        leaderElector cluster.LeaderElector) {
×
UNCOV
1875

×
UNCOV
1876
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
1877
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1878
                srvrLog.Info("Disabling chain backend checks for " +
×
1879
                        "nochainbackend mode")
×
1880

×
1881
                chainBackendAttempts = 0
×
1882
        }
×
1883

UNCOV
1884
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1885
                "chain backend",
×
UNCOV
1886
                cc.HealthCheck,
×
UNCOV
1887
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1888
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
1889
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1890
                chainBackendAttempts,
×
UNCOV
1891
        )
×
UNCOV
1892

×
UNCOV
1893
        diskCheck := healthcheck.NewObservation(
×
UNCOV
1894
                "disk space",
×
UNCOV
1895
                func() error {
×
1896
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1897
                                cfg.LndDir,
×
1898
                        )
×
1899
                        if err != nil {
×
1900
                                return err
×
1901
                        }
×
1902

1903
                        // If we have more free space than we require,
1904
                        // we return a nil error.
1905
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1906
                                return nil
×
1907
                        }
×
1908

1909
                        return fmt.Errorf("require: %v free space, got: %v",
×
1910
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1911
                                free)
×
1912
                },
1913
                cfg.HealthChecks.DiskCheck.Interval,
1914
                cfg.HealthChecks.DiskCheck.Timeout,
1915
                cfg.HealthChecks.DiskCheck.Backoff,
1916
                cfg.HealthChecks.DiskCheck.Attempts,
1917
        )
1918

UNCOV
1919
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
1920
                "tls",
×
UNCOV
1921
                func() error {
×
1922
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1923
                                s.cc.KeyRing,
×
1924
                        )
×
1925
                        if err != nil {
×
1926
                                return err
×
1927
                        }
×
1928
                        if expired {
×
1929
                                return fmt.Errorf("TLS certificate is "+
×
1930
                                        "expired as of %v", expTime)
×
1931
                        }
×
1932

1933
                        // If the certificate is not outdated, no error needs
1934
                        // to be returned
1935
                        return nil
×
1936
                },
1937
                cfg.HealthChecks.TLSCheck.Interval,
1938
                cfg.HealthChecks.TLSCheck.Timeout,
1939
                cfg.HealthChecks.TLSCheck.Backoff,
1940
                cfg.HealthChecks.TLSCheck.Attempts,
1941
        )
1942

UNCOV
1943
        checks := []*healthcheck.Observation{
×
UNCOV
1944
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
1945
        }
×
UNCOV
1946

×
UNCOV
1947
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
1948
        if s.torController != nil {
×
1949
                torConnectionCheck := healthcheck.NewObservation(
×
1950
                        "tor connection",
×
1951
                        func() error {
×
1952
                                return healthcheck.CheckTorServiceStatus(
×
1953
                                        s.torController,
×
1954
                                        s.createNewHiddenService,
×
1955
                                )
×
1956
                        },
×
1957
                        cfg.HealthChecks.TorConnection.Interval,
1958
                        cfg.HealthChecks.TorConnection.Timeout,
1959
                        cfg.HealthChecks.TorConnection.Backoff,
1960
                        cfg.HealthChecks.TorConnection.Attempts,
1961
                )
1962
                checks = append(checks, torConnectionCheck)
×
1963
        }
1964

1965
        // If remote signing is enabled, add the healthcheck for the remote
1966
        // signing RPC interface.
UNCOV
1967
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
1968
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
1969
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
1970
                // returns exactly on time.
×
UNCOV
1971
                overhead := time.Millisecond * 10
×
UNCOV
1972

×
UNCOV
1973
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
1974
                        "remote signer connection",
×
UNCOV
1975
                        rpcwallet.HealthCheck(
×
UNCOV
1976
                                s.cfg.RemoteSigner,
×
UNCOV
1977

×
UNCOV
1978
                                // For the health check we might to be even
×
UNCOV
1979
                                // stricter than the initial/normal connect, so
×
UNCOV
1980
                                // we use the health check timeout here.
×
UNCOV
1981
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
1982
                        ),
×
UNCOV
1983
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
1984
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
1985
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
1986
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
1987
                )
×
UNCOV
1988
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
1989
        }
×
1990

1991
        // If we have a leader elector, we add a health check to ensure we are
1992
        // still the leader. During normal operation, we should always be the
1993
        // leader, but there are circumstances where this may change, such as
1994
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
1995
        if leaderElector != nil {
×
1996
                leaderCheck := healthcheck.NewObservation(
×
1997
                        "leader status",
×
1998
                        func() error {
×
1999
                                // Check if we are still the leader. Note that
×
2000
                                // we don't need to use a timeout context here
×
2001
                                // as the healthcheck observer will handle the
×
2002
                                // timeout case for us.
×
2003
                                timeoutCtx, cancel := context.WithTimeout(
×
2004
                                        context.Background(),
×
2005
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2006
                                )
×
2007
                                defer cancel()
×
2008

×
2009
                                leader, err := leaderElector.IsLeader(
×
2010
                                        timeoutCtx,
×
2011
                                )
×
2012
                                if err != nil {
×
2013
                                        return fmt.Errorf("unable to check if "+
×
2014
                                                "still leader: %v", err)
×
2015
                                }
×
2016

2017
                                if !leader {
×
2018
                                        srvrLog.Debug("Not the current leader")
×
2019
                                        return fmt.Errorf("not the current " +
×
2020
                                                "leader")
×
2021
                                }
×
2022

2023
                                return nil
×
2024
                        },
2025
                        cfg.HealthChecks.LeaderCheck.Interval,
2026
                        cfg.HealthChecks.LeaderCheck.Timeout,
2027
                        cfg.HealthChecks.LeaderCheck.Backoff,
2028
                        cfg.HealthChecks.LeaderCheck.Attempts,
2029
                )
2030

2031
                checks = append(checks, leaderCheck)
×
2032
        }
2033

2034
        // If we have not disabled all of our health checks, we create a
2035
        // liveness monitor with our configured checks.
UNCOV
2036
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2037
                &healthcheck.Config{
×
UNCOV
2038
                        Checks:   checks,
×
UNCOV
2039
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2040
                },
×
UNCOV
2041
        )
×
2042
}
2043

2044
// Started returns true if the server has been started, and false otherwise.
2045
// NOTE: This function is safe for concurrent access.
UNCOV
2046
func (s *server) Started() bool {
×
UNCOV
2047
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2048
}
×
2049

2050
// cleaner is used to aggregate "cleanup" functions during an operation that
2051
// starts several subsystems. In case one of the subsystem fails to start
2052
// and a proper resource cleanup is required, the "run" method achieves this
2053
// by running all these added "cleanup" functions.
2054
type cleaner []func() error
2055

2056
// add is used to add a cleanup function to be called when
2057
// the run function is executed.
UNCOV
2058
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2059
        return append(c, cleanup)
×
UNCOV
2060
}
×
2061

2062
// run is used to run all the previousely added cleanup functions.
2063
func (c cleaner) run() {
×
2064
        for i := len(c) - 1; i >= 0; i-- {
×
2065
                if err := c[i](); err != nil {
×
2066
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2067
                }
×
2068
        }
2069
}
2070

2071
// Start starts the main daemon server, all requested listeners, and any helper
2072
// goroutines.
2073
// NOTE: This function is safe for concurrent access.
2074
//
2075
//nolint:funlen
UNCOV
2076
func (s *server) Start() error {
×
UNCOV
2077
        var startErr error
×
UNCOV
2078

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

×
UNCOV
2084
        s.start.Do(func() {
×
UNCOV
2085
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2086
                if err := s.customMessageServer.Start(); err != nil {
×
2087
                        startErr = err
×
2088
                        return
×
2089
                }
×
2090

UNCOV
2091
                if s.hostAnn != nil {
×
2092
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2093
                        if err := s.hostAnn.Start(); err != nil {
×
2094
                                startErr = err
×
2095
                                return
×
2096
                        }
×
2097
                }
2098

UNCOV
2099
                if s.livenessMonitor != nil {
×
UNCOV
2100
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
UNCOV
2101
                        if err := s.livenessMonitor.Start(); err != nil {
×
2102
                                startErr = err
×
2103
                                return
×
2104
                        }
×
2105
                }
2106

2107
                // Start the notification server. This is used so channel
2108
                // management goroutines can be notified when a funding
2109
                // transaction reaches a sufficient number of confirmations, or
2110
                // when the input for the funding transaction is spent in an
2111
                // attempt at an uncooperative close by the counterparty.
UNCOV
2112
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2113
                if err := s.sigPool.Start(); err != nil {
×
2114
                        startErr = err
×
2115
                        return
×
2116
                }
×
2117

UNCOV
2118
                cleanup = cleanup.add(s.writePool.Stop)
×
UNCOV
2119
                if err := s.writePool.Start(); err != nil {
×
2120
                        startErr = err
×
2121
                        return
×
2122
                }
×
2123

UNCOV
2124
                cleanup = cleanup.add(s.readPool.Stop)
×
UNCOV
2125
                if err := s.readPool.Start(); err != nil {
×
2126
                        startErr = err
×
2127
                        return
×
2128
                }
×
2129

UNCOV
2130
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2131
                if err := s.cc.ChainNotifier.Start(); err != nil {
×
2132
                        startErr = err
×
2133
                        return
×
2134
                }
×
2135

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

UNCOV
2142
                cleanup = cleanup.add(s.channelNotifier.Stop)
×
UNCOV
2143
                if err := s.channelNotifier.Start(); err != nil {
×
2144
                        startErr = err
×
2145
                        return
×
2146
                }
×
2147

UNCOV
2148
                cleanup = cleanup.add(func() error {
×
2149
                        return s.peerNotifier.Stop()
×
2150
                })
×
UNCOV
2151
                if err := s.peerNotifier.Start(); err != nil {
×
2152
                        startErr = err
×
2153
                        return
×
2154
                }
×
2155

UNCOV
2156
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2157
                if err := s.htlcNotifier.Start(); err != nil {
×
2158
                        startErr = err
×
2159
                        return
×
2160
                }
×
2161

UNCOV
2162
                if s.towerClientMgr != nil {
×
UNCOV
2163
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
UNCOV
2164
                        if err := s.towerClientMgr.Start(); err != nil {
×
2165
                                startErr = err
×
2166
                                return
×
2167
                        }
×
2168
                }
2169

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

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

UNCOV
2182
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2183
                if err := s.utxoNursery.Start(); err != nil {
×
2184
                        startErr = err
×
2185
                        return
×
2186
                }
×
2187

UNCOV
2188
                cleanup = cleanup.add(s.breachArbitrator.Stop)
×
UNCOV
2189
                if err := s.breachArbitrator.Start(); err != nil {
×
2190
                        startErr = err
×
2191
                        return
×
2192
                }
×
2193

UNCOV
2194
                cleanup = cleanup.add(s.fundingMgr.Stop)
×
UNCOV
2195
                if err := s.fundingMgr.Start(); err != nil {
×
2196
                        startErr = err
×
2197
                        return
×
2198
                }
×
2199

2200
                // htlcSwitch must be started before chainArb since the latter
2201
                // relies on htlcSwitch to deliver resolution message upon
2202
                // start.
UNCOV
2203
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2204
                if err := s.htlcSwitch.Start(); err != nil {
×
2205
                        startErr = err
×
2206
                        return
×
2207
                }
×
2208

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

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

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

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

UNCOV
2233
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2234
                if err := s.chanRouter.Start(); err != nil {
×
2235
                        startErr = err
×
2236
                        return
×
2237
                }
×
2238
                // The authGossiper depends on the chanRouter and therefore
2239
                // should be started after it.
UNCOV
2240
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2241
                if err := s.authGossiper.Start(); err != nil {
×
2242
                        startErr = err
×
2243
                        return
×
2244
                }
×
2245

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

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

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

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

UNCOV
2270
                cleanup.add(func() error {
×
2271
                        s.missionController.StopStoreTickers()
×
2272
                        return nil
×
2273
                })
×
UNCOV
2274
                s.missionController.RunStoreTickers()
×
UNCOV
2275

×
UNCOV
2276
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2277
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2278
                // that have all the information we need to handle channel
×
UNCOV
2279
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2280
                chanRestorer := &chanDBRestorer{
×
UNCOV
2281
                        db:         s.chanStateDB,
×
UNCOV
2282
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2283
                        chainArb:   s.chainArb,
×
UNCOV
2284
                }
×
UNCOV
2285
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2286
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2287
                                s.chansToRestore.PackedSingleChanBackups,
×
2288
                                s.cc.KeyRing, chanRestorer, s,
×
2289
                        )
×
2290
                        if err != nil {
×
2291
                                startErr = fmt.Errorf("unable to unpack single "+
×
2292
                                        "backups: %v", err)
×
2293
                                return
×
2294
                        }
×
2295
                }
UNCOV
2296
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2297
                        _, err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2298
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2299
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2300
                        )
×
UNCOV
2301
                        if err != nil {
×
2302
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2303
                                        "backup: %v", err)
×
2304
                                return
×
2305
                        }
×
2306
                }
2307

2308
                // chanSubSwapper must be started after the `channelNotifier`
2309
                // because it depends on channel events as a synchronization
2310
                // point.
UNCOV
2311
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2312
                if err := s.chanSubSwapper.Start(); err != nil {
×
2313
                        startErr = err
×
2314
                        return
×
2315
                }
×
2316

UNCOV
2317
                if s.torController != nil {
×
2318
                        cleanup = cleanup.add(s.torController.Stop)
×
2319
                        if err := s.createNewHiddenService(); err != nil {
×
2320
                                startErr = err
×
2321
                                return
×
2322
                        }
×
2323
                }
2324

UNCOV
2325
                if s.natTraversal != nil {
×
2326
                        s.wg.Add(1)
×
2327
                        go s.watchExternalIP()
×
2328
                }
×
2329

2330
                // Start connmgr last to prevent connections before init.
UNCOV
2331
                cleanup = cleanup.add(func() error {
×
2332
                        s.connMgr.Stop()
×
2333
                        return nil
×
2334
                })
×
UNCOV
2335
                s.connMgr.Start()
×
UNCOV
2336

×
UNCOV
2337
                // If peers are specified as a config option, we'll add those
×
UNCOV
2338
                // peers first.
×
UNCOV
2339
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2340
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2341
                                peerAddrCfg,
×
UNCOV
2342
                        )
×
UNCOV
2343
                        if err != nil {
×
2344
                                startErr = fmt.Errorf("unable to parse peer "+
×
2345
                                        "pubkey from config: %v", err)
×
2346
                                return
×
2347
                        }
×
UNCOV
2348
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2349
                        if err != nil {
×
2350
                                startErr = fmt.Errorf("unable to parse peer "+
×
2351
                                        "address provided as a config option: "+
×
2352
                                        "%v", err)
×
2353
                                return
×
2354
                        }
×
2355

UNCOV
2356
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2357
                                IdentityKey: parsedPubkey,
×
UNCOV
2358
                                Address:     addr,
×
UNCOV
2359
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2360
                        }
×
UNCOV
2361

×
UNCOV
2362
                        err = s.ConnectToPeer(
×
UNCOV
2363
                                peerAddr, true,
×
UNCOV
2364
                                s.cfg.ConnectionTimeout,
×
UNCOV
2365
                        )
×
UNCOV
2366
                        if err != nil {
×
2367
                                startErr = fmt.Errorf("unable to connect to "+
×
2368
                                        "peer address provided as a config "+
×
2369
                                        "option: %v", err)
×
2370
                                return
×
2371
                        }
×
2372
                }
2373

2374
                // Subscribe to NodeAnnouncements that advertise new addresses
2375
                // our persistent peers.
UNCOV
2376
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2377
                        startErr = err
×
2378
                        return
×
2379
                }
×
2380

2381
                // With all the relevant sub-systems started, we'll now attempt
2382
                // to establish persistent connections to our direct channel
2383
                // collaborators within the network. Before doing so however,
2384
                // we'll prune our set of link nodes found within the database
2385
                // to ensure we don't reconnect to any nodes we no longer have
2386
                // open channels with.
UNCOV
2387
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2388
                        startErr = err
×
2389
                        return
×
2390
                }
×
UNCOV
2391
                if err := s.establishPersistentConnections(); err != nil {
×
2392
                        startErr = err
×
2393
                        return
×
2394
                }
×
2395

2396
                // setSeedList is a helper function that turns multiple DNS seed
2397
                // server tuples from the command line or config file into the
2398
                // data structure we need and does a basic formal sanity check
2399
                // in the process.
UNCOV
2400
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2401
                        if len(tuples) == 0 {
×
2402
                                return
×
2403
                        }
×
2404

2405
                        result := make([][2]string, len(tuples))
×
2406
                        for idx, tuple := range tuples {
×
2407
                                tuple = strings.TrimSpace(tuple)
×
2408
                                if len(tuple) == 0 {
×
2409
                                        return
×
2410
                                }
×
2411

2412
                                servers := strings.Split(tuple, ",")
×
2413
                                if len(servers) > 2 || len(servers) == 0 {
×
2414
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2415
                                                "seed tuple: %v", servers)
×
2416
                                        return
×
2417
                                }
×
2418

2419
                                copy(result[idx][:], servers)
×
2420
                        }
2421

2422
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2423
                }
2424

2425
                // Let users overwrite the DNS seed nodes. We only allow them
2426
                // for bitcoin mainnet/testnet/signet.
UNCOV
2427
                if s.cfg.Bitcoin.MainNet {
×
2428
                        setSeedList(
×
2429
                                s.cfg.Bitcoin.DNSSeeds,
×
2430
                                chainreg.BitcoinMainnetGenesis,
×
2431
                        )
×
2432
                }
×
UNCOV
2433
                if s.cfg.Bitcoin.TestNet3 {
×
2434
                        setSeedList(
×
2435
                                s.cfg.Bitcoin.DNSSeeds,
×
2436
                                chainreg.BitcoinTestnetGenesis,
×
2437
                        )
×
2438
                }
×
UNCOV
2439
                if s.cfg.Bitcoin.SigNet {
×
2440
                        setSeedList(
×
2441
                                s.cfg.Bitcoin.DNSSeeds,
×
2442
                                chainreg.BitcoinSignetGenesis,
×
2443
                        )
×
2444
                }
×
2445

2446
                // If network bootstrapping hasn't been disabled, then we'll
2447
                // configure the set of active bootstrappers, and launch a
2448
                // dedicated goroutine to maintain a set of persistent
2449
                // connections.
UNCOV
2450
                if shouldPeerBootstrap(s.cfg) {
×
2451
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2452
                        if err != nil {
×
2453
                                startErr = err
×
2454
                                return
×
2455
                        }
×
2456

2457
                        s.wg.Add(1)
×
2458
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
UNCOV
2459
                } else {
×
UNCOV
2460
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2461
                }
×
2462

2463
                // Set the active flag now that we've completed the full
2464
                // startup.
UNCOV
2465
                atomic.StoreInt32(&s.active, 1)
×
2466
        })
2467

UNCOV
2468
        if startErr != nil {
×
2469
                cleanup.run()
×
2470
        }
×
UNCOV
2471
        return startErr
×
2472
}
2473

2474
// Stop gracefully shutsdown the main daemon server. This function will signal
2475
// any active goroutines, or helper objects to exit, then blocks until they've
2476
// all successfully exited. Additionally, any/all listeners are closed.
2477
// NOTE: This function is safe for concurrent access.
UNCOV
2478
func (s *server) Stop() error {
×
UNCOV
2479
        s.stop.Do(func() {
×
UNCOV
2480
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2481

×
UNCOV
2482
                close(s.quit)
×
UNCOV
2483

×
UNCOV
2484
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2485
                s.connMgr.Stop()
×
UNCOV
2486

×
UNCOV
2487
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2488
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2489
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2490
                }
×
UNCOV
2491
                if err := s.htlcSwitch.Stop(); err != nil {
×
2492
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2493
                }
×
UNCOV
2494
                if err := s.sphinx.Stop(); err != nil {
×
2495
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2496
                }
×
UNCOV
2497
                if err := s.invoices.Stop(); err != nil {
×
2498
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2499
                }
×
UNCOV
2500
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2501
                        srvrLog.Warnf("failed to stop interceptable "+
×
2502
                                "switch: %v", err)
×
2503
                }
×
UNCOV
2504
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2505
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2506
                                "modifier: %v", err)
×
2507
                }
×
UNCOV
2508
                if err := s.chanRouter.Stop(); err != nil {
×
2509
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2510
                }
×
UNCOV
2511
                if err := s.graphBuilder.Stop(); err != nil {
×
2512
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2513
                }
×
UNCOV
2514
                if err := s.chainArb.Stop(); err != nil {
×
2515
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2516
                }
×
UNCOV
2517
                if err := s.fundingMgr.Stop(); err != nil {
×
2518
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2519
                }
×
UNCOV
2520
                if err := s.breachArbitrator.Stop(); err != nil {
×
2521
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2522
                                err)
×
2523
                }
×
UNCOV
2524
                if err := s.utxoNursery.Stop(); err != nil {
×
2525
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2526
                }
×
UNCOV
2527
                if err := s.authGossiper.Stop(); err != nil {
×
2528
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2529
                }
×
UNCOV
2530
                if err := s.sweeper.Stop(); err != nil {
×
2531
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2532
                }
×
UNCOV
2533
                if err := s.txPublisher.Stop(); err != nil {
×
2534
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2535
                }
×
UNCOV
2536
                if err := s.channelNotifier.Stop(); err != nil {
×
2537
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2538
                }
×
UNCOV
2539
                if err := s.peerNotifier.Stop(); err != nil {
×
2540
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2541
                }
×
UNCOV
2542
                if err := s.htlcNotifier.Stop(); err != nil {
×
2543
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2544
                }
×
2545

2546
                // Update channel.backup file. Make sure to do it before
2547
                // stopping chanSubSwapper.
UNCOV
2548
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2549
                        s.chanStateDB, s.addrSource,
×
UNCOV
2550
                )
×
UNCOV
2551
                if err != nil {
×
2552
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2553
                                err)
×
UNCOV
2554
                } else {
×
UNCOV
2555
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2556
                        if err != nil {
×
UNCOV
2557
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2558
                                        "backup failed: %v", err)
×
UNCOV
2559
                        }
×
2560
                }
2561

UNCOV
2562
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2563
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2564
                }
×
UNCOV
2565
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2566
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2567
                }
×
UNCOV
2568
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2569
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2570
                                err)
×
2571
                }
×
UNCOV
2572
                if err := s.chanEventStore.Stop(); err != nil {
×
2573
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2574
                                err)
×
2575
                }
×
UNCOV
2576
                s.missionController.StopStoreTickers()
×
UNCOV
2577

×
UNCOV
2578
                // Disconnect from each active peers to ensure that
×
UNCOV
2579
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2580
                for _, peer := range s.Peers() {
×
UNCOV
2581
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2582
                        if err != nil {
×
2583
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2584
                                        "received error: %v", peer.IdentityKey(),
×
2585
                                        err,
×
2586
                                )
×
2587
                        }
×
2588
                }
2589

2590
                // Now that all connections have been torn down, stop the tower
2591
                // client which will reliably flush all queued states to the
2592
                // tower. If this is halted for any reason, the force quit timer
2593
                // will kick in and abort to allow this method to return.
UNCOV
2594
                if s.towerClientMgr != nil {
×
UNCOV
2595
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2596
                                srvrLog.Warnf("Unable to shut down tower "+
×
2597
                                        "client manager: %v", err)
×
2598
                        }
×
2599
                }
2600

UNCOV
2601
                if s.hostAnn != nil {
×
2602
                        if err := s.hostAnn.Stop(); err != nil {
×
2603
                                srvrLog.Warnf("unable to shut down host "+
×
2604
                                        "annoucner: %v", err)
×
2605
                        }
×
2606
                }
2607

UNCOV
2608
                if s.livenessMonitor != nil {
×
UNCOV
2609
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2610
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2611
                                        "monitor: %v", err)
×
2612
                        }
×
2613
                }
2614

2615
                // Wait for all lingering goroutines to quit.
UNCOV
2616
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2617
                s.wg.Wait()
×
UNCOV
2618

×
UNCOV
2619
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2620
                s.sigPool.Stop()
×
UNCOV
2621
                s.writePool.Stop()
×
UNCOV
2622
                s.readPool.Stop()
×
2623
        })
2624

UNCOV
2625
        return nil
×
2626
}
2627

2628
// Stopped returns true if the server has been instructed to shutdown.
2629
// NOTE: This function is safe for concurrent access.
UNCOV
2630
func (s *server) Stopped() bool {
×
UNCOV
2631
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2632
}
×
2633

2634
// configurePortForwarding attempts to set up port forwarding for the different
2635
// ports that the server will be listening on.
2636
//
2637
// NOTE: This should only be used when using some kind of NAT traversal to
2638
// automatically set up forwarding rules.
2639
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2640
        ip, err := s.natTraversal.ExternalIP()
×
2641
        if err != nil {
×
2642
                return nil, err
×
2643
        }
×
2644
        s.lastDetectedIP = ip
×
2645

×
2646
        externalIPs := make([]string, 0, len(ports))
×
2647
        for _, port := range ports {
×
2648
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2649
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2650
                        continue
×
2651
                }
2652

2653
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2654
                externalIPs = append(externalIPs, hostIP)
×
2655
        }
2656

2657
        return externalIPs, nil
×
2658
}
2659

2660
// removePortForwarding attempts to clear the forwarding rules for the different
2661
// ports the server is currently listening on.
2662
//
2663
// NOTE: This should only be used when using some kind of NAT traversal to
2664
// automatically set up forwarding rules.
2665
func (s *server) removePortForwarding() {
×
2666
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2667
        for _, port := range forwardedPorts {
×
2668
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2669
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2670
                                "port %d: %v", port, err)
×
2671
                }
×
2672
        }
2673
}
2674

2675
// watchExternalIP continuously checks for an updated external IP address every
2676
// 15 minutes. Once a new IP address has been detected, it will automatically
2677
// handle port forwarding rules and send updated node announcements to the
2678
// currently connected peers.
2679
//
2680
// NOTE: This MUST be run as a goroutine.
2681
func (s *server) watchExternalIP() {
×
2682
        defer s.wg.Done()
×
2683

×
2684
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2685
        // up by the server.
×
2686
        defer s.removePortForwarding()
×
2687

×
2688
        // Keep track of the external IPs set by the user to avoid replacing
×
2689
        // them when detecting a new IP.
×
2690
        ipsSetByUser := make(map[string]struct{})
×
2691
        for _, ip := range s.cfg.ExternalIPs {
×
2692
                ipsSetByUser[ip.String()] = struct{}{}
×
2693
        }
×
2694

2695
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2696

×
2697
        ticker := time.NewTicker(15 * time.Minute)
×
2698
        defer ticker.Stop()
×
2699
out:
×
2700
        for {
×
2701
                select {
×
2702
                case <-ticker.C:
×
2703
                        // We'll start off by making sure a new IP address has
×
2704
                        // been detected.
×
2705
                        ip, err := s.natTraversal.ExternalIP()
×
2706
                        if err != nil {
×
2707
                                srvrLog.Debugf("Unable to retrieve the "+
×
2708
                                        "external IP address: %v", err)
×
2709
                                continue
×
2710
                        }
2711

2712
                        // Periodically renew the NAT port forwarding.
2713
                        for _, port := range forwardedPorts {
×
2714
                                err := s.natTraversal.AddPortMapping(port)
×
2715
                                if err != nil {
×
2716
                                        srvrLog.Warnf("Unable to automatically "+
×
2717
                                                "re-create port forwarding using %s: %v",
×
2718
                                                s.natTraversal.Name(), err)
×
2719
                                } else {
×
2720
                                        srvrLog.Debugf("Automatically re-created "+
×
2721
                                                "forwarding for port %d using %s to "+
×
2722
                                                "advertise external IP",
×
2723
                                                port, s.natTraversal.Name())
×
2724
                                }
×
2725
                        }
2726

2727
                        if ip.Equal(s.lastDetectedIP) {
×
2728
                                continue
×
2729
                        }
2730

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

×
2733
                        // Next, we'll craft the new addresses that will be
×
2734
                        // included in the new node announcement and advertised
×
2735
                        // to the network. Each address will consist of the new
×
2736
                        // IP detected and one of the currently advertised
×
2737
                        // ports.
×
2738
                        var newAddrs []net.Addr
×
2739
                        for _, port := range forwardedPorts {
×
2740
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2741
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2742
                                if err != nil {
×
2743
                                        srvrLog.Debugf("Unable to resolve "+
×
2744
                                                "host %v: %v", addr, err)
×
2745
                                        continue
×
2746
                                }
2747

2748
                                newAddrs = append(newAddrs, addr)
×
2749
                        }
2750

2751
                        // Skip the update if we weren't able to resolve any of
2752
                        // the new addresses.
2753
                        if len(newAddrs) == 0 {
×
2754
                                srvrLog.Debug("Skipping node announcement " +
×
2755
                                        "update due to not being able to " +
×
2756
                                        "resolve any new addresses")
×
2757
                                continue
×
2758
                        }
2759

2760
                        // Now, we'll need to update the addresses in our node's
2761
                        // announcement in order to propagate the update
2762
                        // throughout the network. We'll only include addresses
2763
                        // that have a different IP from the previous one, as
2764
                        // the previous IP is no longer valid.
2765
                        currentNodeAnn := s.getNodeAnnouncement()
×
2766

×
2767
                        for _, addr := range currentNodeAnn.Addresses {
×
2768
                                host, _, err := net.SplitHostPort(addr.String())
×
2769
                                if err != nil {
×
2770
                                        srvrLog.Debugf("Unable to determine "+
×
2771
                                                "host from address %v: %v",
×
2772
                                                addr, err)
×
2773
                                        continue
×
2774
                                }
2775

2776
                                // We'll also make sure to include external IPs
2777
                                // set manually by the user.
2778
                                _, setByUser := ipsSetByUser[addr.String()]
×
2779
                                if setByUser || host != s.lastDetectedIP.String() {
×
2780
                                        newAddrs = append(newAddrs, addr)
×
2781
                                }
×
2782
                        }
2783

2784
                        // Then, we'll generate a new timestamped node
2785
                        // announcement with the updated addresses and broadcast
2786
                        // it to our peers.
2787
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2788
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2789
                        )
×
2790
                        if err != nil {
×
2791
                                srvrLog.Debugf("Unable to generate new node "+
×
2792
                                        "announcement: %v", err)
×
2793
                                continue
×
2794
                        }
2795

2796
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2797
                        if err != nil {
×
2798
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2799
                                        "announcement to peers: %v", err)
×
2800
                                continue
×
2801
                        }
2802

2803
                        // Finally, update the last IP seen to the current one.
2804
                        s.lastDetectedIP = ip
×
2805
                case <-s.quit:
×
2806
                        break out
×
2807
                }
2808
        }
2809
}
2810

2811
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2812
// based on the server, and currently active bootstrap mechanisms as defined
2813
// within the current configuration.
2814
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2815
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2816

×
2817
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2818

×
2819
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2820
        // this can be used by default if we've already partially seeded the
×
2821
        // network.
×
2822
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2823
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2824
        if err != nil {
×
2825
                return nil, err
×
2826
        }
×
2827
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2828

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

×
2834
                // If we have a set of DNS seeds for this chain, then we'll add
×
2835
                // it as an additional bootstrapping source.
×
2836
                if ok {
×
2837
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2838
                                "seeds: %v", dnsSeeds)
×
2839

×
2840
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2841
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2842
                        )
×
2843
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2844
                }
×
2845
        }
2846

2847
        return bootStrappers, nil
×
2848
}
2849

2850
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2851
// needs to ignore, which is made of three parts,
2852
//   - the node itself needs to be skipped as it doesn't make sense to connect
2853
//     to itself.
2854
//   - the peers that already have connections with, as in s.peersByPub.
2855
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2856
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2857
        s.mu.RLock()
×
2858
        defer s.mu.RUnlock()
×
2859

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

×
2862
        // We should ignore ourselves from bootstrapping.
×
2863
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2864
        ignore[selfKey] = struct{}{}
×
2865

×
2866
        // Ignore all connected peers.
×
2867
        for _, peer := range s.peersByPub {
×
2868
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2869
                ignore[nID] = struct{}{}
×
2870
        }
×
2871

2872
        // Ignore all persistent peers as they have a dedicated reconnecting
2873
        // process.
2874
        for pubKeyStr := range s.persistentPeers {
×
2875
                var nID autopilot.NodeID
×
2876
                copy(nID[:], []byte(pubKeyStr))
×
2877
                ignore[nID] = struct{}{}
×
2878
        }
×
2879

2880
        return ignore
×
2881
}
2882

2883
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2884
// and maintain a target minimum number of outbound connections. With this
2885
// invariant, we ensure that our node is connected to a diverse set of peers
2886
// and that nodes newly joining the network receive an up to date network view
2887
// as soon as possible.
2888
func (s *server) peerBootstrapper(numTargetPeers uint32,
2889
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2890

×
2891
        defer s.wg.Done()
×
2892

×
2893
        // Before we continue, init the ignore peers map.
×
2894
        ignoreList := s.createBootstrapIgnorePeers()
×
2895

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

×
2900
        // Once done, we'll attempt to maintain our target minimum number of
×
2901
        // peers.
×
2902
        //
×
2903
        // We'll use a 15 second backoff, and double the time every time an
×
2904
        // epoch fails up to a ceiling.
×
2905
        backOff := time.Second * 15
×
2906

×
2907
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2908
        // see if we've reached our minimum number of peers.
×
2909
        sampleTicker := time.NewTicker(backOff)
×
2910
        defer sampleTicker.Stop()
×
2911

×
2912
        // We'll use the number of attempts and errors to determine if we need
×
2913
        // to increase the time between discovery epochs.
×
2914
        var epochErrors uint32 // To be used atomically.
×
2915
        var epochAttempts uint32
×
2916

×
2917
        for {
×
2918
                select {
×
2919
                // The ticker has just woken us up, so we'll need to check if
2920
                // we need to attempt to connect our to any more peers.
2921
                case <-sampleTicker.C:
×
2922
                        // Obtain the current number of peers, so we can gauge
×
2923
                        // if we need to sample more peers or not.
×
2924
                        s.mu.RLock()
×
2925
                        numActivePeers := uint32(len(s.peersByPub))
×
2926
                        s.mu.RUnlock()
×
2927

×
2928
                        // If we have enough peers, then we can loop back
×
2929
                        // around to the next round as we're done here.
×
2930
                        if numActivePeers >= numTargetPeers {
×
2931
                                continue
×
2932
                        }
2933

2934
                        // If all of our attempts failed during this last back
2935
                        // off period, then will increase our backoff to 5
2936
                        // minute ceiling to avoid an excessive number of
2937
                        // queries
2938
                        //
2939
                        // TODO(roasbeef): add reverse policy too?
2940

2941
                        if epochAttempts > 0 &&
×
2942
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2943

×
2944
                                sampleTicker.Stop()
×
2945

×
2946
                                backOff *= 2
×
2947
                                if backOff > bootstrapBackOffCeiling {
×
2948
                                        backOff = bootstrapBackOffCeiling
×
2949
                                }
×
2950

2951
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2952
                                        "%v", backOff)
×
2953
                                sampleTicker = time.NewTicker(backOff)
×
2954
                                continue
×
2955
                        }
2956

2957
                        atomic.StoreUint32(&epochErrors, 0)
×
2958
                        epochAttempts = 0
×
2959

×
2960
                        // Since we know need more peers, we'll compute the
×
2961
                        // exact number we need to reach our threshold.
×
2962
                        numNeeded := numTargetPeers - numActivePeers
×
2963

×
2964
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2965
                                "peers", numNeeded)
×
2966

×
2967
                        // With the number of peers we need calculated, we'll
×
2968
                        // query the network bootstrappers to sample a set of
×
2969
                        // random addrs for us.
×
2970
                        //
×
2971
                        // Before we continue, get a copy of the ignore peers
×
2972
                        // map.
×
2973
                        ignoreList = s.createBootstrapIgnorePeers()
×
2974

×
2975
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2976
                                ignoreList, numNeeded*2, bootstrappers...,
×
2977
                        )
×
2978
                        if err != nil {
×
2979
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2980
                                        "peers: %v", err)
×
2981
                                continue
×
2982
                        }
2983

2984
                        // Finally, we'll launch a new goroutine for each
2985
                        // prospective peer candidates.
2986
                        for _, addr := range peerAddrs {
×
2987
                                epochAttempts++
×
2988

×
2989
                                go func(a *lnwire.NetAddress) {
×
2990
                                        // TODO(roasbeef): can do AS, subnet,
×
2991
                                        // country diversity, etc
×
2992
                                        errChan := make(chan error, 1)
×
2993
                                        s.connectToPeer(
×
2994
                                                a, errChan,
×
2995
                                                s.cfg.ConnectionTimeout,
×
2996
                                        )
×
2997
                                        select {
×
2998
                                        case err := <-errChan:
×
2999
                                                if err == nil {
×
3000
                                                        return
×
3001
                                                }
×
3002

3003
                                                srvrLog.Errorf("Unable to "+
×
3004
                                                        "connect to %v: %v",
×
3005
                                                        a, err)
×
3006
                                                atomic.AddUint32(&epochErrors, 1)
×
3007
                                        case <-s.quit:
×
3008
                                        }
3009
                                }(addr)
3010
                        }
3011
                case <-s.quit:
×
3012
                        return
×
3013
                }
3014
        }
3015
}
3016

3017
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3018
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3019
// query back off each time we encounter a failure.
3020
const bootstrapBackOffCeiling = time.Minute * 5
3021

3022
// initialPeerBootstrap attempts to continuously connect to peers on startup
3023
// until the target number of peers has been reached. This ensures that nodes
3024
// receive an up to date network view as soon as possible.
3025
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3026
        numTargetPeers uint32,
3027
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3028

×
3029
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3030
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3031

×
3032
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3033
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3034
        var delaySignal <-chan time.Time
×
3035
        delayTime := time.Second * 2
×
3036

×
3037
        // As want to be more aggressive, we'll use a lower back off celling
×
3038
        // then the main peer bootstrap logic.
×
3039
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3040

×
3041
        for attempts := 0; ; attempts++ {
×
3042
                // Check if the server has been requested to shut down in order
×
3043
                // to prevent blocking.
×
3044
                if s.Stopped() {
×
3045
                        return
×
3046
                }
×
3047

3048
                // We can exit our aggressive initial peer bootstrapping stage
3049
                // if we've reached out target number of peers.
3050
                s.mu.RLock()
×
3051
                numActivePeers := uint32(len(s.peersByPub))
×
3052
                s.mu.RUnlock()
×
3053

×
3054
                if numActivePeers >= numTargetPeers {
×
3055
                        return
×
3056
                }
×
3057

3058
                if attempts > 0 {
×
3059
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3060
                                "bootstrap peers (attempt #%v)", delayTime,
×
3061
                                attempts)
×
3062

×
3063
                        // We've completed at least one iterating and haven't
×
3064
                        // finished, so we'll start to insert a delay period
×
3065
                        // between each attempt.
×
3066
                        delaySignal = time.After(delayTime)
×
3067
                        select {
×
3068
                        case <-delaySignal:
×
3069
                        case <-s.quit:
×
3070
                                return
×
3071
                        }
3072

3073
                        // After our delay, we'll double the time we wait up to
3074
                        // the max back off period.
3075
                        delayTime *= 2
×
3076
                        if delayTime > backOffCeiling {
×
3077
                                delayTime = backOffCeiling
×
3078
                        }
×
3079
                }
3080

3081
                // Otherwise, we'll request for the remaining number of peers
3082
                // in order to reach our target.
3083
                peersNeeded := numTargetPeers - numActivePeers
×
3084
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3085
                        ignore, peersNeeded, bootstrappers...,
×
3086
                )
×
3087
                if err != nil {
×
3088
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3089
                                "peers: %v", err)
×
3090
                        continue
×
3091
                }
3092

3093
                // Then, we'll attempt to establish a connection to the
3094
                // different peer addresses retrieved by our bootstrappers.
3095
                var wg sync.WaitGroup
×
3096
                for _, bootstrapAddr := range bootstrapAddrs {
×
3097
                        wg.Add(1)
×
3098
                        go func(addr *lnwire.NetAddress) {
×
3099
                                defer wg.Done()
×
3100

×
3101
                                errChan := make(chan error, 1)
×
3102
                                go s.connectToPeer(
×
3103
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3104
                                )
×
3105

×
3106
                                // We'll only allow this connection attempt to
×
3107
                                // take up to 3 seconds. This allows us to move
×
3108
                                // quickly by discarding peers that are slowing
×
3109
                                // us down.
×
3110
                                select {
×
3111
                                case err := <-errChan:
×
3112
                                        if err == nil {
×
3113
                                                return
×
3114
                                        }
×
3115
                                        srvrLog.Errorf("Unable to connect to "+
×
3116
                                                "%v: %v", addr, err)
×
3117
                                // TODO: tune timeout? 3 seconds might be *too*
3118
                                // aggressive but works well.
3119
                                case <-time.After(3 * time.Second):
×
3120
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3121
                                                "to not establishing a "+
×
3122
                                                "connection within 3 seconds",
×
3123
                                                addr)
×
3124
                                case <-s.quit:
×
3125
                                }
3126
                        }(bootstrapAddr)
3127
                }
3128

3129
                wg.Wait()
×
3130
        }
3131
}
3132

3133
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3134
// order to listen for inbound connections over Tor.
3135
func (s *server) createNewHiddenService() error {
×
3136
        // Determine the different ports the server is listening on. The onion
×
3137
        // service's virtual port will map to these ports and one will be picked
×
3138
        // at random when the onion service is being accessed.
×
3139
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3140
        for _, listenAddr := range s.listenAddrs {
×
3141
                port := listenAddr.(*net.TCPAddr).Port
×
3142
                listenPorts = append(listenPorts, port)
×
3143
        }
×
3144

3145
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3146
        if err != nil {
×
3147
                return err
×
3148
        }
×
3149

3150
        // Once the port mapping has been set, we can go ahead and automatically
3151
        // create our onion service. The service's private key will be saved to
3152
        // disk in order to regain access to this service when restarting `lnd`.
3153
        onionCfg := tor.AddOnionConfig{
×
3154
                VirtualPort: defaultPeerPort,
×
3155
                TargetPorts: listenPorts,
×
3156
                Store: tor.NewOnionFile(
×
3157
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3158
                        encrypter,
×
3159
                ),
×
3160
        }
×
3161

×
3162
        switch {
×
3163
        case s.cfg.Tor.V2:
×
3164
                onionCfg.Type = tor.V2
×
3165
        case s.cfg.Tor.V3:
×
3166
                onionCfg.Type = tor.V3
×
3167
        }
3168

3169
        addr, err := s.torController.AddOnion(onionCfg)
×
3170
        if err != nil {
×
3171
                return err
×
3172
        }
×
3173

3174
        // Now that the onion service has been created, we'll add the onion
3175
        // address it can be reached at to our list of advertised addresses.
3176
        newNodeAnn, err := s.genNodeAnnouncement(
×
3177
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3178
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3179
                },
×
3180
        )
3181
        if err != nil {
×
3182
                return fmt.Errorf("unable to generate new node "+
×
3183
                        "announcement: %v", err)
×
3184
        }
×
3185

3186
        // Finally, we'll update the on-disk version of our announcement so it
3187
        // will eventually propagate to nodes in the network.
3188
        selfNode := &channeldb.LightningNode{
×
3189
                HaveNodeAnnouncement: true,
×
3190
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3191
                Addresses:            newNodeAnn.Addresses,
×
3192
                Alias:                newNodeAnn.Alias.String(),
×
3193
                Features: lnwire.NewFeatureVector(
×
3194
                        newNodeAnn.Features, lnwire.Features,
×
3195
                ),
×
3196
                Color:        newNodeAnn.RGBColor,
×
3197
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3198
        }
×
3199
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3200
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3201
                return fmt.Errorf("can't set self node: %w", err)
×
3202
        }
×
3203

3204
        return nil
×
3205
}
3206

3207
// findChannel finds a channel given a public key and ChannelID. It is an
3208
// optimization that is quicker than seeking for a channel given only the
3209
// ChannelID.
3210
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3211
        *channeldb.OpenChannel, error) {
×
UNCOV
3212

×
UNCOV
3213
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3214
        if err != nil {
×
3215
                return nil, err
×
3216
        }
×
3217

UNCOV
3218
        for _, channel := range nodeChans {
×
UNCOV
3219
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3220
                        return channel, nil
×
UNCOV
3221
                }
×
3222
        }
3223

UNCOV
3224
        return nil, fmt.Errorf("unable to find channel")
×
3225
}
3226

3227
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3228
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3229
        s.mu.Lock()
×
UNCOV
3230
        defer s.mu.Unlock()
×
UNCOV
3231

×
UNCOV
3232
        return *s.currentNodeAnn
×
UNCOV
3233
}
×
3234

3235
// genNodeAnnouncement generates and returns the current fully signed node
3236
// announcement. The time stamp of the announcement will be updated in order
3237
// to ensure it propagates through the network.
3238
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3239
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3240

×
UNCOV
3241
        s.mu.Lock()
×
UNCOV
3242
        defer s.mu.Unlock()
×
UNCOV
3243

×
UNCOV
3244
        // First, try to update our feature manager with the updated set of
×
UNCOV
3245
        // features.
×
UNCOV
3246
        if features != nil {
×
UNCOV
3247
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3248
                        feature.SetNodeAnn: features,
×
UNCOV
3249
                }
×
UNCOV
3250
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3251
                if err != nil {
×
UNCOV
3252
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3253
                }
×
3254

3255
                // If we could successfully update our feature manager, add
3256
                // an update modifier to include these new features to our
3257
                // set.
UNCOV
3258
                modifiers = append(
×
UNCOV
3259
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3260
                )
×
3261
        }
3262

3263
        // Always update the timestamp when refreshing to ensure the update
3264
        // propagates.
UNCOV
3265
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3266

×
UNCOV
3267
        // Apply the requested changes to the node announcement.
×
UNCOV
3268
        for _, modifier := range modifiers {
×
UNCOV
3269
                modifier(s.currentNodeAnn)
×
UNCOV
3270
        }
×
3271

3272
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3273
        err := netann.SignNodeAnnouncement(
×
UNCOV
3274
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
UNCOV
3275
        )
×
UNCOV
3276
        if err != nil {
×
3277
                return lnwire.NodeAnnouncement{}, err
×
3278
        }
×
3279

UNCOV
3280
        return *s.currentNodeAnn, nil
×
3281
}
3282

3283
// updateAndBroadcastSelfNode generates a new node announcement
3284
// applying the giving modifiers and updating the time stamp
3285
// to ensure it propagates through the network. Then it broadcasts
3286
// it to the network.
3287
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
UNCOV
3288
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3289

×
UNCOV
3290
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3291
        if err != nil {
×
UNCOV
3292
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3293
                        "announcement: %v", err)
×
UNCOV
3294
        }
×
3295

3296
        // Update the on-disk version of our announcement.
3297
        // Load and modify self node istead of creating anew instance so we
3298
        // don't risk overwriting any existing values.
UNCOV
3299
        selfNode, err := s.graphDB.SourceNode()
×
UNCOV
3300
        if err != nil {
×
3301
                return fmt.Errorf("unable to get current source node: %w", err)
×
3302
        }
×
3303

UNCOV
3304
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3305
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3306
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3307
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3308
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3309
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3310
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3311

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

×
UNCOV
3314
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3315
                return fmt.Errorf("can't set self node: %w", err)
×
3316
        }
×
3317

3318
        // Finally, propagate it to the nodes in the network.
UNCOV
3319
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3320
        if err != nil {
×
3321
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3322
                        "announcement to peers: %v", err)
×
3323
                return err
×
3324
        }
×
3325

UNCOV
3326
        return nil
×
3327
}
3328

3329
type nodeAddresses struct {
3330
        pubKey    *btcec.PublicKey
3331
        addresses []net.Addr
3332
}
3333

3334
// establishPersistentConnections attempts to establish persistent connections
3335
// to all our direct channel collaborators. In order to promote liveness of our
3336
// active channels, we instruct the connection manager to attempt to establish
3337
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3338
func (s *server) establishPersistentConnections() error {
×
UNCOV
3339
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3340
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3341
        // since other PubKey forms can't be compared.
×
UNCOV
3342
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3343

×
UNCOV
3344
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3345
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3346
        // the reconnection port to the default peer port.
×
UNCOV
3347
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3348
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3349
                return err
×
3350
        }
×
UNCOV
3351
        for _, node := range linkNodes {
×
UNCOV
3352
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3353
                nodeAddrs := &nodeAddresses{
×
UNCOV
3354
                        pubKey:    node.IdentityPub,
×
UNCOV
3355
                        addresses: node.Addresses,
×
UNCOV
3356
                }
×
UNCOV
3357
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3358
        }
×
3359

3360
        // After checking our previous connections for addresses to connect to,
3361
        // iterate through the nodes in our channel graph to find addresses
3362
        // that have been added via NodeAnnouncement messages.
UNCOV
3363
        sourceNode, err := s.graphDB.SourceNode()
×
UNCOV
3364
        if err != nil {
×
3365
                return err
×
3366
        }
×
3367

3368
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3369
        // each of the nodes.
UNCOV
3370
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
3371
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
×
UNCOV
3372
                tx kvdb.RTx,
×
UNCOV
3373
                chanInfo *models.ChannelEdgeInfo,
×
UNCOV
3374
                policy, _ *models.ChannelEdgePolicy) error {
×
UNCOV
3375

×
UNCOV
3376
                // If the remote party has announced the channel to us, but we
×
UNCOV
3377
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3378
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3379
                if policy == nil {
×
3380
                        srvrLog.Warnf("No channel policy found for "+
×
3381
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3382
                }
×
3383

3384
                // We'll now fetch the peer opposite from us within this
3385
                // channel so we can queue up a direct connection to them.
UNCOV
3386
                channelPeer, err := s.graphDB.FetchOtherNode(
×
UNCOV
3387
                        tx, chanInfo, selfPub,
×
UNCOV
3388
                )
×
UNCOV
3389
                if err != nil {
×
3390
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3391
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3392
                                err)
×
3393
                }
×
3394

UNCOV
3395
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3396

×
UNCOV
3397
                // Add all unique addresses from channel
×
UNCOV
3398
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3399
                // connect to for this peer.
×
UNCOV
3400
                addrSet := make(map[string]net.Addr)
×
UNCOV
3401
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3402
                        switch addr.(type) {
×
UNCOV
3403
                        case *net.TCPAddr:
×
UNCOV
3404
                                addrSet[addr.String()] = addr
×
3405

3406
                        // We'll only attempt to connect to Tor addresses if Tor
3407
                        // outbound support is enabled.
3408
                        case *tor.OnionAddr:
×
3409
                                if s.cfg.Tor.Active {
×
3410
                                        addrSet[addr.String()] = addr
×
3411
                                }
×
3412
                        }
3413
                }
3414

3415
                // If this peer is also recorded as a link node, we'll add any
3416
                // additional addresses that have not already been selected.
UNCOV
3417
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3418
                if ok {
×
UNCOV
3419
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3420
                                switch lnAddress.(type) {
×
UNCOV
3421
                                case *net.TCPAddr:
×
UNCOV
3422
                                        addrSet[lnAddress.String()] = lnAddress
×
3423

3424
                                // We'll only attempt to connect to Tor
3425
                                // addresses if Tor outbound support is enabled.
3426
                                case *tor.OnionAddr:
×
3427
                                        if s.cfg.Tor.Active {
×
3428
                                                addrSet[lnAddress.String()] = lnAddress
×
3429
                                        }
×
3430
                                }
3431
                        }
3432
                }
3433

3434
                // Construct a slice of the deduped addresses.
UNCOV
3435
                var addrs []net.Addr
×
UNCOV
3436
                for _, addr := range addrSet {
×
UNCOV
3437
                        addrs = append(addrs, addr)
×
UNCOV
3438
                }
×
3439

UNCOV
3440
                n := &nodeAddresses{
×
UNCOV
3441
                        addresses: addrs,
×
UNCOV
3442
                }
×
UNCOV
3443
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3444
                if err != nil {
×
3445
                        return err
×
3446
                }
×
3447

UNCOV
3448
                nodeAddrsMap[pubStr] = n
×
UNCOV
3449
                return nil
×
3450
        })
UNCOV
3451
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
×
3452
                return err
×
3453
        }
×
3454

UNCOV
3455
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3456
                len(nodeAddrsMap))
×
UNCOV
3457

×
UNCOV
3458
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3459
        // have been recorded and sent to the connection manager.
×
UNCOV
3460
        s.mu.Lock()
×
UNCOV
3461
        defer s.mu.Unlock()
×
UNCOV
3462

×
UNCOV
3463
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3464
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3465
        var numOutboundConns int
×
UNCOV
3466
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3467
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3468
                // persistent connection with. We set the value to false to
×
UNCOV
3469
                // indicate that we should not continue to reconnect if the
×
UNCOV
3470
                // number of channels returns to zero, since this peer has not
×
UNCOV
3471
                // been requested as perm by the user.
×
UNCOV
3472
                s.persistentPeers[pubStr] = false
×
UNCOV
3473
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3474
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3475
                }
×
3476

UNCOV
3477
                for _, address := range nodeAddr.addresses {
×
UNCOV
3478
                        // Create a wrapper address which couples the IP and
×
UNCOV
3479
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3480
                        // can be established.
×
UNCOV
3481
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3482
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3483
                                Address:     address,
×
UNCOV
3484
                        }
×
UNCOV
3485

×
UNCOV
3486
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3487
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3488
                }
×
3489

3490
                // We'll connect to the first 10 peers immediately, then
3491
                // randomly stagger any remaining connections if the
3492
                // stagger initial reconnect flag is set. This ensures
3493
                // that mobile nodes or nodes with a small number of
3494
                // channels obtain connectivity quickly, but larger
3495
                // nodes are able to disperse the costs of connecting to
3496
                // all peers at once.
UNCOV
3497
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3498
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3499

×
UNCOV
3500
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3501
                } else {
×
3502
                        go s.delayInitialReconnect(pubStr)
×
3503
                }
×
3504

UNCOV
3505
                numOutboundConns++
×
3506
        }
3507

UNCOV
3508
        return nil
×
3509
}
3510

3511
// delayInitialReconnect will attempt a reconnection to the given peer after
3512
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3513
//
3514
// NOTE: This method MUST be run as a goroutine.
3515
func (s *server) delayInitialReconnect(pubStr string) {
×
3516
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3517
        select {
×
3518
        case <-time.After(delay):
×
3519
                s.connectToPersistentPeer(pubStr)
×
3520
        case <-s.quit:
×
3521
        }
3522
}
3523

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

×
UNCOV
3530
        s.mu.Lock()
×
UNCOV
3531
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3532
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3533
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3534
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3535
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3536
                s.mu.Unlock()
×
UNCOV
3537

×
UNCOV
3538
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3539
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3540

×
UNCOV
3541
                return
×
UNCOV
3542
        }
×
UNCOV
3543
        s.mu.Unlock()
×
3544
}
3545

3546
// BroadcastMessage sends a request to the server to broadcast a set of
3547
// messages to all peers other than the one specified by the `skips` parameter.
3548
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3549
// the target peers.
3550
//
3551
// NOTE: This function is safe for concurrent access.
3552
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3553
        msgs ...lnwire.Message) error {
×
UNCOV
3554

×
UNCOV
3555
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3556
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3557
        // exact set of peers present at the time of invocation.
×
UNCOV
3558
        s.mu.RLock()
×
UNCOV
3559
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3560
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3561
                if skips != nil {
×
UNCOV
3562
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3563
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3564
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3565
                                continue
×
3566
                        }
3567
                }
3568

UNCOV
3569
                peers = append(peers, sPeer)
×
3570
        }
UNCOV
3571
        s.mu.RUnlock()
×
UNCOV
3572

×
UNCOV
3573
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3574
        // all messages to each of peers.
×
UNCOV
3575
        var wg sync.WaitGroup
×
UNCOV
3576
        for _, sPeer := range peers {
×
UNCOV
3577
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3578
                        sPeer.PubKey())
×
UNCOV
3579

×
UNCOV
3580
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3581
                wg.Add(1)
×
UNCOV
3582
                s.wg.Add(1)
×
UNCOV
3583
                go func(p lnpeer.Peer) {
×
UNCOV
3584
                        defer s.wg.Done()
×
UNCOV
3585
                        defer wg.Done()
×
UNCOV
3586

×
UNCOV
3587
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3588
                }(sPeer)
×
3589
        }
3590

3591
        // Wait for all messages to have been dispatched before returning to
3592
        // caller.
UNCOV
3593
        wg.Wait()
×
UNCOV
3594

×
UNCOV
3595
        return nil
×
3596
}
3597

3598
// NotifyWhenOnline can be called by other subsystems to get notified when a
3599
// particular peer comes online. The peer itself is sent across the peerChan.
3600
//
3601
// NOTE: This function is safe for concurrent access.
3602
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3603
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3604

×
UNCOV
3605
        s.mu.Lock()
×
UNCOV
3606

×
UNCOV
3607
        // Compute the target peer's identifier.
×
UNCOV
3608
        pubStr := string(peerKey[:])
×
UNCOV
3609

×
UNCOV
3610
        // Check if peer is connected.
×
UNCOV
3611
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3612
        if ok {
×
UNCOV
3613
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3614
                // waiting for the peer to become active.
×
UNCOV
3615
                s.mu.Unlock()
×
UNCOV
3616

×
UNCOV
3617
                // Wait until the peer signals that it is actually active
×
UNCOV
3618
                // rather than only in the server's maps.
×
UNCOV
3619
                select {
×
UNCOV
3620
                case <-peer.ActiveSignal():
×
3621
                case <-peer.QuitSignal():
×
3622
                        // The peer quit, so we'll add the channel to the slice
×
3623
                        // and return.
×
3624
                        s.mu.Lock()
×
3625
                        s.peerConnectedListeners[pubStr] = append(
×
3626
                                s.peerConnectedListeners[pubStr], peerChan,
×
3627
                        )
×
3628
                        s.mu.Unlock()
×
3629
                        return
×
3630
                }
3631

3632
                // Connected, can return early.
UNCOV
3633
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3634

×
UNCOV
3635
                select {
×
UNCOV
3636
                case peerChan <- peer:
×
3637
                case <-s.quit:
×
3638
                }
3639

UNCOV
3640
                return
×
3641
        }
3642

3643
        // Not connected, store this listener such that it can be notified when
3644
        // the peer comes online.
UNCOV
3645
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3646
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3647
        )
×
UNCOV
3648
        s.mu.Unlock()
×
3649
}
3650

3651
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3652
// the given public key has been disconnected. The notification is signaled by
3653
// closing the channel returned.
UNCOV
3654
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3655
        s.mu.Lock()
×
UNCOV
3656
        defer s.mu.Unlock()
×
UNCOV
3657

×
UNCOV
3658
        c := make(chan struct{})
×
UNCOV
3659

×
UNCOV
3660
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3661
        // notification.
×
UNCOV
3662
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3663
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3664
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3665
                close(c)
×
3666
                return c
×
3667
        }
×
3668

3669
        // Otherwise, the peer is online, so we'll keep track of the channel to
3670
        // trigger the notification once the server detects the peer
3671
        // disconnects.
UNCOV
3672
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3673
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3674
        )
×
UNCOV
3675

×
UNCOV
3676
        return c
×
3677
}
3678

3679
// FindPeer will return the peer that corresponds to the passed in public key.
3680
// This function is used by the funding manager, allowing it to update the
3681
// daemon's local representation of the remote peer.
3682
//
3683
// NOTE: This function is safe for concurrent access.
UNCOV
3684
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3685
        s.mu.RLock()
×
UNCOV
3686
        defer s.mu.RUnlock()
×
UNCOV
3687

×
UNCOV
3688
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3689

×
UNCOV
3690
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3691
}
×
3692

3693
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3694
// which should be a string representation of the peer's serialized, compressed
3695
// public key.
3696
//
3697
// NOTE: This function is safe for concurrent access.
UNCOV
3698
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3699
        s.mu.RLock()
×
UNCOV
3700
        defer s.mu.RUnlock()
×
UNCOV
3701

×
UNCOV
3702
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3703
}
×
3704

3705
// findPeerByPubStr is an internal method that retrieves the specified peer from
3706
// the server's internal state using.
UNCOV
3707
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3708
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3709
        if !ok {
×
UNCOV
3710
                return nil, ErrPeerNotConnected
×
UNCOV
3711
        }
×
3712

UNCOV
3713
        return peer, nil
×
3714
}
3715

3716
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3717
// exponential backoff. If no previous backoff was known, the default is
3718
// returned.
3719
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3720
        startTime time.Time) time.Duration {
×
UNCOV
3721

×
UNCOV
3722
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3723
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3724
        if !ok {
×
UNCOV
3725
                // If an existing backoff was unknown, use the default.
×
UNCOV
3726
                return s.cfg.MinBackoff
×
UNCOV
3727
        }
×
3728

3729
        // If the peer failed to start properly, we'll just use the previous
3730
        // backoff to compute the subsequent randomized exponential backoff
3731
        // duration. This will roughly double on average.
UNCOV
3732
        if startTime.IsZero() {
×
3733
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3734
        }
×
3735

3736
        // The peer succeeded in starting. If the connection didn't last long
3737
        // enough to be considered stable, we'll continue to back off retries
3738
        // with this peer.
UNCOV
3739
        connDuration := time.Since(startTime)
×
UNCOV
3740
        if connDuration < defaultStableConnDuration {
×
UNCOV
3741
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3742
        }
×
3743

3744
        // The peer succeed in starting and this was stable peer, so we'll
3745
        // reduce the timeout duration by the length of the connection after
3746
        // applying randomized exponential backoff. We'll only apply this in the
3747
        // case that:
3748
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3749
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3750
        if relaxedBackoff > s.cfg.MinBackoff {
×
3751
                return relaxedBackoff
×
3752
        }
×
3753

3754
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3755
        // the stable connection lasted much longer than our previous backoff.
3756
        // To reward such good behavior, we'll reconnect after the default
3757
        // timeout.
3758
        return s.cfg.MinBackoff
×
3759
}
3760

3761
// shouldDropLocalConnection determines if our local connection to a remote peer
3762
// should be dropped in the case of concurrent connection establishment. In
3763
// order to deterministically decide which connection should be dropped, we'll
3764
// utilize the ordering of the local and remote public key. If we didn't use
3765
// such a tie breaker, then we risk _both_ connections erroneously being
3766
// dropped.
3767
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3768
        localPubBytes := local.SerializeCompressed()
×
3769
        remotePubPbytes := remote.SerializeCompressed()
×
3770

×
3771
        // The connection that comes from the node with a "smaller" pubkey
×
3772
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3773
        // should drop our established connection.
×
3774
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3775
}
×
3776

3777
// InboundPeerConnected initializes a new peer in response to a new inbound
3778
// connection.
3779
//
3780
// NOTE: This function is safe for concurrent access.
UNCOV
3781
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3782
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3783
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3784
        if s.Stopped() {
×
3785
                return
×
3786
        }
×
3787

UNCOV
3788
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3789
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3790
        pubStr := string(pubSer)
×
UNCOV
3791

×
UNCOV
3792
        var pubBytes [33]byte
×
UNCOV
3793
        copy(pubBytes[:], pubSer)
×
UNCOV
3794

×
UNCOV
3795
        s.mu.Lock()
×
UNCOV
3796
        defer s.mu.Unlock()
×
UNCOV
3797

×
UNCOV
3798
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3799
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3800
        if dcErr != nil {
×
3801
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3802
                        "peer: %v", dcErr)
×
3803
                conn.Close()
×
3804

×
3805
                return
×
3806
        }
×
3807

UNCOV
3808
        if shouldDc {
×
3809
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3810
                        "banned.", pubSer)
×
3811

×
3812
                conn.Close()
×
3813

×
3814
                return
×
3815
        }
×
3816

3817
        // If we already have an outbound connection to this peer, then ignore
3818
        // this new connection.
UNCOV
3819
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
3820
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
3821
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
3822
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3823

×
UNCOV
3824
                conn.Close()
×
UNCOV
3825
                return
×
UNCOV
3826
        }
×
3827

3828
        // If we already have a valid connection that is scheduled to take
3829
        // precedence once the prior peer has finished disconnecting, we'll
3830
        // ignore this connection.
UNCOV
3831
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3832
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3833
                        "scheduled", conn.RemoteAddr(), p)
×
3834
                conn.Close()
×
3835
                return
×
3836
        }
×
3837

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

×
UNCOV
3840
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3841
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3842
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3843
        // default case as we expect these to be the only error values returned
×
UNCOV
3844
        // from findPeerByPubStr.
×
UNCOV
3845
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3846
        switch err {
×
UNCOV
3847
        case ErrPeerNotConnected:
×
UNCOV
3848
                // We were unable to locate an existing connection with the
×
UNCOV
3849
                // target peer, proceed to connect.
×
UNCOV
3850
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3851
                s.peerConnected(conn, nil, true)
×
3852

3853
        case nil:
×
3854
                // We already have a connection with the incoming peer. If the
×
3855
                // connection we've already established should be kept and is
×
3856
                // not of the same type of the new connection (inbound), then
×
3857
                // we'll close out the new connection s.t there's only a single
×
3858
                // connection between us.
×
3859
                localPub := s.identityECDH.PubKey()
×
3860
                if !connectedPeer.Inbound() &&
×
3861
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3862

×
3863
                        srvrLog.Warnf("Received inbound connection from "+
×
3864
                                "peer %v, but already have outbound "+
×
3865
                                "connection, dropping conn", connectedPeer)
×
3866
                        conn.Close()
×
3867
                        return
×
3868
                }
×
3869

3870
                // Otherwise, if we should drop the connection, then we'll
3871
                // disconnect our already connected peer.
3872
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3873
                        connectedPeer)
×
3874

×
3875
                s.cancelConnReqs(pubStr, nil)
×
3876

×
3877
                // Remove the current peer from the server's internal state and
×
3878
                // signal that the peer termination watcher does not need to
×
3879
                // execute for this peer.
×
3880
                s.removePeer(connectedPeer)
×
3881
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3882
                s.scheduledPeerConnection[pubStr] = func() {
×
3883
                        s.peerConnected(conn, nil, true)
×
3884
                }
×
3885
        }
3886
}
3887

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

UNCOV
3898
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3899
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3900
        pubStr := string(pubSer)
×
UNCOV
3901

×
UNCOV
3902
        var pubBytes [33]byte
×
UNCOV
3903
        copy(pubBytes[:], pubSer)
×
UNCOV
3904

×
UNCOV
3905
        s.mu.Lock()
×
UNCOV
3906
        defer s.mu.Unlock()
×
UNCOV
3907

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

×
3915
                return
×
3916
        }
×
3917

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

×
3922
                if connReq != nil {
×
3923
                        s.connMgr.Remove(connReq.ID())
×
3924
                }
×
3925

3926
                conn.Close()
×
3927

×
3928
                return
×
3929
        }
3930

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

×
UNCOV
3938
                if connReq != nil {
×
UNCOV
3939
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
3940
                }
×
UNCOV
3941
                conn.Close()
×
UNCOV
3942
                return
×
3943
        }
UNCOV
3944
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
3945
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3946
                s.connMgr.Remove(connReq.ID())
×
3947
                conn.Close()
×
3948
                return
×
3949
        }
×
3950

3951
        // If we already have a valid connection that is scheduled to take
3952
        // precedence once the prior peer has finished disconnecting, we'll
3953
        // ignore this connection.
UNCOV
3954
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3955
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3956

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

3961
                conn.Close()
×
3962
                return
×
3963
        }
3964

UNCOV
3965
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
UNCOV
3966
                conn.RemoteAddr())
×
UNCOV
3967

×
UNCOV
3968
        if connReq != nil {
×
UNCOV
3969
                // A successful connection was returned by the connmgr.
×
UNCOV
3970
                // Immediately cancel all pending requests, excluding the
×
UNCOV
3971
                // outbound connection we just established.
×
UNCOV
3972
                ignore := connReq.ID()
×
UNCOV
3973
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
3974
        } else {
×
UNCOV
3975
                // This was a successful connection made by some other
×
UNCOV
3976
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
3977
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3978
        }
×
3979

3980
        // If we already have a connection with this peer, decide whether or not
3981
        // we need to drop the stale connection. We forgo adding a default case
3982
        // as we expect these to be the only error values returned from
3983
        // findPeerByPubStr.
UNCOV
3984
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3985
        switch err {
×
UNCOV
3986
        case ErrPeerNotConnected:
×
UNCOV
3987
                // We were unable to locate an existing connection with the
×
UNCOV
3988
                // target peer, proceed to connect.
×
UNCOV
3989
                s.peerConnected(conn, connReq, false)
×
3990

3991
        case nil:
×
3992
                // We already have a connection with the incoming peer. If the
×
3993
                // connection we've already established should be kept and is
×
3994
                // not of the same type of the new connection (outbound), then
×
3995
                // we'll close out the new connection s.t there's only a single
×
3996
                // connection between us.
×
3997
                localPub := s.identityECDH.PubKey()
×
3998
                if connectedPeer.Inbound() &&
×
3999
                        shouldDropLocalConnection(localPub, nodePub) {
×
4000

×
4001
                        srvrLog.Warnf("Established outbound connection to "+
×
4002
                                "peer %v, but already have inbound "+
×
4003
                                "connection, dropping conn", connectedPeer)
×
4004
                        if connReq != nil {
×
4005
                                s.connMgr.Remove(connReq.ID())
×
4006
                        }
×
4007
                        conn.Close()
×
4008
                        return
×
4009
                }
4010

4011
                // Otherwise, _their_ connection should be dropped. So we'll
4012
                // disconnect the peer and send the now obsolete peer to the
4013
                // server for garbage collection.
4014
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4015
                        connectedPeer)
×
4016

×
4017
                // Remove the current peer from the server's internal state and
×
4018
                // signal that the peer termination watcher does not need to
×
4019
                // execute for this peer.
×
4020
                s.removePeer(connectedPeer)
×
4021
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4022
                s.scheduledPeerConnection[pubStr] = func() {
×
4023
                        s.peerConnected(conn, connReq, false)
×
4024
                }
×
4025
        }
4026
}
4027

4028
// UnassignedConnID is the default connection ID that a request can have before
4029
// it actually is submitted to the connmgr.
4030
// TODO(conner): move into connmgr package, or better, add connmgr method for
4031
// generating atomic IDs
4032
const UnassignedConnID uint64 = 0
4033

4034
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4035
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4036
// Afterwards, each connection request removed from the connmgr. The caller can
4037
// optionally specify a connection ID to ignore, which prevents us from
4038
// canceling a successful request. All persistent connreqs for the provided
4039
// pubkey are discarded after the operationjw.
UNCOV
4040
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4041
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4042
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4043
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4044
                close(cancelChan)
×
UNCOV
4045
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4046
        }
×
4047

4048
        // Next, check to see if we have any outstanding persistent connection
4049
        // requests to this peer. If so, then we'll remove all of these
4050
        // connection requests, and also delete the entry from the map.
UNCOV
4051
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4052
        if !ok {
×
UNCOV
4053
                return
×
UNCOV
4054
        }
×
4055

UNCOV
4056
        for _, connReq := range connReqs {
×
UNCOV
4057
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4058

×
UNCOV
4059
                // Atomically capture the current request identifier.
×
UNCOV
4060
                connID := connReq.ID()
×
UNCOV
4061

×
UNCOV
4062
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4063
                // yet been schedule.
×
UNCOV
4064
                if connID == UnassignedConnID {
×
4065
                        continue
×
4066
                }
4067

4068
                // Skip a particular connection ID if instructed.
UNCOV
4069
                if skip != nil && connID == *skip {
×
UNCOV
4070
                        continue
×
4071
                }
4072

UNCOV
4073
                s.connMgr.Remove(connID)
×
4074
        }
4075

UNCOV
4076
        delete(s.persistentConnReqs, pubStr)
×
4077
}
4078

4079
// handleCustomMessage dispatches an incoming custom peers message to
4080
// subscribers.
UNCOV
4081
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4082
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4083
                peer, msg.Type)
×
UNCOV
4084

×
UNCOV
4085
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4086
                Peer: peer,
×
UNCOV
4087
                Msg:  msg,
×
UNCOV
4088
        })
×
UNCOV
4089
}
×
4090

4091
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4092
// messages.
UNCOV
4093
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4094
        return s.customMessageServer.Subscribe()
×
UNCOV
4095
}
×
4096

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

×
UNCOV
4104
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4105
        addr := conn.RemoteAddr()
×
UNCOV
4106
        pubKey := brontideConn.RemotePub()
×
UNCOV
4107

×
UNCOV
4108
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4109
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4110

×
UNCOV
4111
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4112
                IdentityKey: pubKey,
×
UNCOV
4113
                Address:     addr,
×
UNCOV
4114
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4115
        }
×
UNCOV
4116

×
UNCOV
4117
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4118
        // vectors to advertise to the remote node.
×
UNCOV
4119
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4120
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4121

×
UNCOV
4122
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4123
        // found, create a fresh buffer.
×
UNCOV
4124
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4125
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4126
        if !ok {
×
UNCOV
4127
                var err error
×
UNCOV
4128
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4129
                if err != nil {
×
4130
                        srvrLog.Errorf("unable to create peer %v", err)
×
4131
                        return
×
4132
                }
×
4133
        }
4134

4135
        // If we directly set the peer.Config TowerClient member to the
4136
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4137
        // the peer.Config's TowerClient member will not evaluate to nil even
4138
        // though the underlying value is nil. To avoid this gotcha which can
4139
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4140
        // TowerClient if needed.
UNCOV
4141
        var towerClient wtclient.ClientManager
×
UNCOV
4142
        if s.towerClientMgr != nil {
×
UNCOV
4143
                towerClient = s.towerClientMgr
×
UNCOV
4144
        }
×
4145

UNCOV
4146
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4147
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4148

×
UNCOV
4149
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4150
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4151
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4152
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4153
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4154
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4155
        pCfg := peer.Config{
×
UNCOV
4156
                Conn:                    brontideConn,
×
UNCOV
4157
                ConnReq:                 connReq,
×
UNCOV
4158
                Addr:                    peerAddr,
×
UNCOV
4159
                Inbound:                 inbound,
×
UNCOV
4160
                Features:                initFeatures,
×
UNCOV
4161
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4162
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4163
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4164
                ErrorBuffer:             errBuffer,
×
UNCOV
4165
                WritePool:               s.writePool,
×
UNCOV
4166
                ReadPool:                s.readPool,
×
UNCOV
4167
                Switch:                  s.htlcSwitch,
×
UNCOV
4168
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4169
                ChannelDB:               s.chanStateDB,
×
UNCOV
4170
                ChannelGraph:            s.graphDB,
×
UNCOV
4171
                ChainArb:                s.chainArb,
×
UNCOV
4172
                AuthGossiper:            s.authGossiper,
×
UNCOV
4173
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4174
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4175
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4176
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4177
                SigPool:                 s.sigPool,
×
UNCOV
4178
                Wallet:                  s.cc.Wallet,
×
UNCOV
4179
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4180
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4181
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4182
                Sphinx:                  s.sphinx,
×
UNCOV
4183
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4184
                Invoices:                s.invoices,
×
UNCOV
4185
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4186
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4187
                TowerClient:             towerClient,
×
UNCOV
4188
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4189
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4190
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4191

×
UNCOV
4192
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4193
                },
×
4194

4195
                PongBuf: s.pongBuf,
4196

4197
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4198

4199
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4200

4201
                FundingManager: s.fundingMgr,
4202

4203
                Hodl:                    s.cfg.Hodl,
4204
                UnsafeReplay:            s.cfg.UnsafeReplay,
4205
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4206
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4207
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4208
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4209
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4210
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4211
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4212
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4213
                HandleCustomMessage:    s.handleCustomMessage,
4214
                GetAliases:             s.aliasMgr.GetAliases,
4215
                RequestAlias:           s.aliasMgr.RequestAlias,
4216
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4217
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4218
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4219
                MaxFeeExposure:         thresholdMSats,
4220
                Quit:                   s.quit,
4221
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4222
                AuxSigner:              s.implCfg.AuxSigner,
4223
                MsgRouter:              s.implCfg.MsgRouter,
4224
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4225
                AuxResolver:            s.implCfg.AuxContractResolver,
UNCOV
4226
                ShouldFwdExpEndorsement: func() bool {
×
UNCOV
4227
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
×
UNCOV
4228
                                return false
×
UNCOV
4229
                        }
×
4230

UNCOV
4231
                        return clock.NewDefaultClock().Now().Before(
×
UNCOV
4232
                                EndorsementExperimentEnd,
×
UNCOV
4233
                        )
×
4234
                },
4235
        }
4236

UNCOV
4237
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4238
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4239

×
UNCOV
4240
        p := peer.NewBrontide(pCfg)
×
UNCOV
4241

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

×
UNCOV
4245
        s.addPeer(p)
×
UNCOV
4246

×
UNCOV
4247
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4248
        // delete the previous error buffer from the server's map of error
×
UNCOV
4249
        // buffers.
×
UNCOV
4250
        delete(s.peerErrors, pkStr)
×
UNCOV
4251

×
UNCOV
4252
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4253
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4254
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4255
        s.wg.Add(1)
×
UNCOV
4256
        go s.peerInitializer(p)
×
4257
}
4258

4259
// addPeer adds the passed peer to the server's global state of all active
4260
// peers.
UNCOV
4261
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4262
        if p == nil {
×
4263
                return
×
4264
        }
×
4265

UNCOV
4266
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4267

×
UNCOV
4268
        // Ignore new peers if we're shutting down.
×
UNCOV
4269
        if s.Stopped() {
×
4270
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4271
                        pubBytes)
×
4272
                p.Disconnect(ErrServerShuttingDown)
×
4273

×
4274
                return
×
4275
        }
×
4276

4277
        // Track the new peer in our indexes so we can quickly look it up either
4278
        // according to its public key, or its peer ID.
4279
        // TODO(roasbeef): pipe all requests through to the
4280
        // queryHandler/peerManager
4281

4282
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4283
        // be human-readable.
UNCOV
4284
        pubStr := string(pubBytes)
×
UNCOV
4285

×
UNCOV
4286
        s.peersByPub[pubStr] = p
×
UNCOV
4287

×
UNCOV
4288
        if p.Inbound() {
×
UNCOV
4289
                s.inboundPeers[pubStr] = p
×
UNCOV
4290
        } else {
×
UNCOV
4291
                s.outboundPeers[pubStr] = p
×
UNCOV
4292
        }
×
4293

4294
        // Inform the peer notifier of a peer online event so that it can be reported
4295
        // to clients listening for peer events.
UNCOV
4296
        var pubKey [33]byte
×
UNCOV
4297
        copy(pubKey[:], pubBytes)
×
UNCOV
4298

×
UNCOV
4299
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4300
}
4301

4302
// peerInitializer asynchronously starts a newly connected peer after it has
4303
// been added to the server's peer map. This method sets up a
4304
// peerTerminationWatcher for the given peer, and ensures that it executes even
4305
// if the peer failed to start. In the event of a successful connection, this
4306
// method reads the negotiated, local feature-bits and spawns the appropriate
4307
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4308
// be signaled of the new peer once the method returns.
4309
//
4310
// NOTE: This MUST be launched as a goroutine.
UNCOV
4311
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4312
        defer s.wg.Done()
×
UNCOV
4313

×
UNCOV
4314
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4315

×
UNCOV
4316
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4317
        if s.Stopped() {
×
4318
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4319
                        pubBytes)
×
4320
                return
×
4321
        }
×
4322

4323
        // Create a channel that will be used to signal a successful start of
4324
        // the link. This prevents the peer termination watcher from beginning
4325
        // its duty too early.
UNCOV
4326
        ready := make(chan struct{})
×
UNCOV
4327

×
UNCOV
4328
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4329
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4330
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4331
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4332
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4333
        // that the server has already handled the removal of this peer.
×
UNCOV
4334
        s.wg.Add(1)
×
UNCOV
4335
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4336

×
UNCOV
4337
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4338
        // will unblock the peerTerminationWatcher.
×
UNCOV
4339
        if err := p.Start(); err != nil {
×
4340
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
4341

×
4342
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4343
                return
×
4344
        }
×
4345

4346
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4347
        // was successful, and to begin watching the peer's wait group.
UNCOV
4348
        close(ready)
×
UNCOV
4349

×
UNCOV
4350
        s.mu.Lock()
×
UNCOV
4351
        defer s.mu.Unlock()
×
UNCOV
4352

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

×
UNCOV
4356
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4357
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4358
        pubStr := string(pubBytes)
×
UNCOV
4359
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4360
                select {
×
UNCOV
4361
                case peerChan <- p:
×
UNCOV
4362
                case <-s.quit:
×
UNCOV
4363
                        return
×
4364
                }
4365
        }
UNCOV
4366
        delete(s.peerConnectedListeners, pubStr)
×
4367
}
4368

4369
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4370
// and then cleans up all resources allocated to the peer, notifies relevant
4371
// sub-systems of its demise, and finally handles re-connecting to the peer if
4372
// it's persistent. If the server intentionally disconnects a peer, it should
4373
// have a corresponding entry in the ignorePeerTermination map which will cause
4374
// the cleanup routine to exit early. The passed `ready` chan is used to
4375
// synchronize when WaitForDisconnect should begin watching on the peer's
4376
// waitgroup. The ready chan should only be signaled if the peer starts
4377
// successfully, otherwise the peer should be disconnected instead.
4378
//
4379
// NOTE: This MUST be launched as a goroutine.
UNCOV
4380
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4381
        defer s.wg.Done()
×
UNCOV
4382

×
UNCOV
4383
        p.WaitForDisconnect(ready)
×
UNCOV
4384

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

×
UNCOV
4387
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4388
        // the other sub-systems will already be shutting down.
×
UNCOV
4389
        if s.Stopped() {
×
UNCOV
4390
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4391
                return
×
UNCOV
4392
        }
×
4393

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

×
UNCOV
4400
        pubKey := p.IdentityKey()
×
UNCOV
4401

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

×
UNCOV
4406
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4407
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4408
        // with this interface should be closed.
×
UNCOV
4409
        //
×
UNCOV
4410
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4411
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4412
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4413
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4414
        }
×
4415

UNCOV
4416
        for _, link := range links {
×
UNCOV
4417
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4418
        }
×
4419

UNCOV
4420
        s.mu.Lock()
×
UNCOV
4421
        defer s.mu.Unlock()
×
UNCOV
4422

×
UNCOV
4423
        // If there were any notification requests for when this peer
×
UNCOV
4424
        // disconnected, we can trigger them now.
×
UNCOV
4425
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4426
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4427
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4428
                close(offlineChan)
×
UNCOV
4429
        }
×
UNCOV
4430
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4431

×
UNCOV
4432
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4433
        // peer termination watcher and skip cleanup.
×
UNCOV
4434
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4435
                delete(s.ignorePeerTermination, p)
×
4436

×
4437
                pubKey := p.PubKey()
×
4438
                pubStr := string(pubKey[:])
×
4439

×
4440
                // If a connection callback is present, we'll go ahead and
×
4441
                // execute it now that previous peer has fully disconnected. If
×
4442
                // the callback is not present, this likely implies the peer was
×
4443
                // purposefully disconnected via RPC, and that no reconnect
×
4444
                // should be attempted.
×
4445
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4446
                if ok {
×
4447
                        delete(s.scheduledPeerConnection, pubStr)
×
4448
                        connCallback()
×
4449
                }
×
4450
                return
×
4451
        }
4452

4453
        // First, cleanup any remaining state the server has regarding the peer
4454
        // in question.
UNCOV
4455
        s.removePeer(p)
×
UNCOV
4456

×
UNCOV
4457
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4458
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4459
                return
×
UNCOV
4460
        }
×
4461

4462
        // Get the last address that we used to connect to the peer.
UNCOV
4463
        addrs := []net.Addr{
×
UNCOV
4464
                p.NetAddress().Address,
×
UNCOV
4465
        }
×
UNCOV
4466

×
UNCOV
4467
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4468
        // reconnection purposes.
×
UNCOV
4469
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
UNCOV
4470
        switch {
×
4471
        // We found advertised addresses, so use them.
UNCOV
4472
        case err == nil:
×
UNCOV
4473
                addrs = advertisedAddrs
×
4474

4475
        // The peer doesn't have an advertised address.
UNCOV
4476
        case err == errNoAdvertisedAddr:
×
UNCOV
4477
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4478
                // peer address.
×
UNCOV
4479
                if !p.Inbound() {
×
UNCOV
4480
                        break
×
4481
                }
4482

4483
                // Fall back to the existing peer address if
4484
                // we're not accepting connections over Tor.
UNCOV
4485
                if s.torController == nil {
×
UNCOV
4486
                        break
×
4487
                }
4488

4489
                // If we are, the peer's address won't be known
4490
                // to us (we'll see a private address, which is
4491
                // the address used by our onion service to dial
4492
                // to lnd), so we don't have enough information
4493
                // to attempt a reconnect.
4494
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4495
                        "to inbound peer %v without "+
×
4496
                        "advertised address", p)
×
4497
                return
×
4498

4499
        // We came across an error retrieving an advertised
4500
        // address, log it, and fall back to the existing peer
4501
        // address.
UNCOV
4502
        default:
×
UNCOV
4503
                srvrLog.Errorf("Unable to retrieve advertised "+
×
UNCOV
4504
                        "address for node %x: %v", p.PubKey(),
×
UNCOV
4505
                        err)
×
4506
        }
4507

4508
        // Make an easy lookup map so that we can check if an address
4509
        // is already in the address list that we have stored for this peer.
UNCOV
4510
        existingAddrs := make(map[string]bool)
×
UNCOV
4511
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4512
                existingAddrs[addr.String()] = true
×
UNCOV
4513
        }
×
4514

4515
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4516
        for _, addr := range addrs {
×
UNCOV
4517
                if existingAddrs[addr.String()] {
×
4518
                        continue
×
4519
                }
4520

UNCOV
4521
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4522
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4523
                        &lnwire.NetAddress{
×
UNCOV
4524
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4525
                                Address:     addr,
×
UNCOV
4526
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4527
                        },
×
UNCOV
4528
                )
×
4529
        }
4530

4531
        // Record the computed backoff in the backoff map.
UNCOV
4532
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4533
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4534

×
UNCOV
4535
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4536
        // exist.
×
UNCOV
4537
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4538
        if !ok {
×
UNCOV
4539
                cancelChan = make(chan struct{})
×
UNCOV
4540
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4541
        }
×
4542

4543
        // We choose not to wait group this go routine since the Connect
4544
        // call can stall for arbitrarily long if we shutdown while an
4545
        // outbound connection attempt is being made.
UNCOV
4546
        go func() {
×
UNCOV
4547
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
UNCOV
4548
                        "persistent peer %x in %s",
×
UNCOV
4549
                        p.IdentityKey().SerializeCompressed(), backoff)
×
UNCOV
4550

×
UNCOV
4551
                select {
×
UNCOV
4552
                case <-time.After(backoff):
×
UNCOV
4553
                case <-cancelChan:
×
UNCOV
4554
                        return
×
UNCOV
4555
                case <-s.quit:
×
UNCOV
4556
                        return
×
4557
                }
4558

UNCOV
4559
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4560
                        "connection to peer %x",
×
UNCOV
4561
                        p.IdentityKey().SerializeCompressed())
×
UNCOV
4562

×
UNCOV
4563
                s.connectToPersistentPeer(pubStr)
×
4564
        }()
4565
}
4566

4567
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4568
// to connect to the peer. It creates connection requests if there are
4569
// currently none for a given address and it removes old connection requests
4570
// if the associated address is no longer in the latest address list for the
4571
// peer.
UNCOV
4572
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4573
        s.mu.Lock()
×
UNCOV
4574
        defer s.mu.Unlock()
×
UNCOV
4575

×
UNCOV
4576
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4577
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4578
        // connection requests for the associated address and then any leftover
×
UNCOV
4579
        // entries will indicate which addresses we should create new
×
UNCOV
4580
        // connection requests for.
×
UNCOV
4581
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4582
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4583
                addrMap[addr.String()] = addr
×
UNCOV
4584
        }
×
4585

4586
        // Go through each of the existing connection requests and
4587
        // check if they correspond to the latest set of addresses. If
4588
        // there is a connection requests that does not use one of the latest
4589
        // advertised addresses then remove that connection request.
UNCOV
4590
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4591
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4592
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4593

×
UNCOV
4594
                switch _, ok := addrMap[lnAddr]; ok {
×
4595
                // If the existing connection request is using one of the
4596
                // latest advertised addresses for the peer then we add it to
4597
                // updatedConnReqs and remove the associated address from
4598
                // addrMap so that we don't recreate this connReq later on.
4599
                case true:
×
4600
                        updatedConnReqs = append(
×
4601
                                updatedConnReqs, connReq,
×
4602
                        )
×
4603
                        delete(addrMap, lnAddr)
×
4604

4605
                // If the existing connection request is using an address that
4606
                // is not one of the latest advertised addresses for the peer
4607
                // then we remove the connecting request from the connection
4608
                // manager.
UNCOV
4609
                case false:
×
UNCOV
4610
                        srvrLog.Info(
×
UNCOV
4611
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4612
                        )
×
UNCOV
4613
                        s.connMgr.Remove(connReq.ID())
×
4614
                }
4615
        }
4616

UNCOV
4617
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4618

×
UNCOV
4619
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4620
        if !ok {
×
UNCOV
4621
                cancelChan = make(chan struct{})
×
UNCOV
4622
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4623
        }
×
4624

4625
        // Any addresses left in addrMap are new ones that we have not made
4626
        // connection requests for. So create new connection requests for those.
4627
        // If there is more than one address in the address map, stagger the
4628
        // creation of the connection requests for those.
UNCOV
4629
        go func() {
×
UNCOV
4630
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
4631
                defer ticker.Stop()
×
UNCOV
4632

×
UNCOV
4633
                for _, addr := range addrMap {
×
UNCOV
4634
                        // Send the persistent connection request to the
×
UNCOV
4635
                        // connection manager, saving the request itself so we
×
UNCOV
4636
                        // can cancel/restart the process as needed.
×
UNCOV
4637
                        connReq := &connmgr.ConnReq{
×
UNCOV
4638
                                Addr:      addr,
×
UNCOV
4639
                                Permanent: true,
×
UNCOV
4640
                        }
×
UNCOV
4641

×
UNCOV
4642
                        s.mu.Lock()
×
UNCOV
4643
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4644
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4645
                        )
×
UNCOV
4646
                        s.mu.Unlock()
×
UNCOV
4647

×
UNCOV
4648
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4649
                                "channel peer %v", addr)
×
UNCOV
4650

×
UNCOV
4651
                        go s.connMgr.Connect(connReq)
×
UNCOV
4652

×
UNCOV
4653
                        select {
×
UNCOV
4654
                        case <-s.quit:
×
UNCOV
4655
                                return
×
UNCOV
4656
                        case <-cancelChan:
×
UNCOV
4657
                                return
×
UNCOV
4658
                        case <-ticker.C:
×
4659
                        }
4660
                }
4661
        }()
4662
}
4663

4664
// removePeer removes the passed peer from the server's state of all active
4665
// peers.
UNCOV
4666
func (s *server) removePeer(p *peer.Brontide) {
×
UNCOV
4667
        if p == nil {
×
4668
                return
×
4669
        }
×
4670

UNCOV
4671
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4672

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

×
UNCOV
4677
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4678
        if p.ConnReq() != nil {
×
UNCOV
4679
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4680
        }
×
4681

4682
        // Ignore deleting peers if we're shutting down.
UNCOV
4683
        if s.Stopped() {
×
4684
                return
×
4685
        }
×
4686

UNCOV
4687
        pKey := p.PubKey()
×
UNCOV
4688
        pubSer := pKey[:]
×
UNCOV
4689
        pubStr := string(pubSer)
×
UNCOV
4690

×
UNCOV
4691
        delete(s.peersByPub, pubStr)
×
UNCOV
4692

×
UNCOV
4693
        if p.Inbound() {
×
UNCOV
4694
                delete(s.inboundPeers, pubStr)
×
UNCOV
4695
        } else {
×
UNCOV
4696
                delete(s.outboundPeers, pubStr)
×
UNCOV
4697
        }
×
4698

4699
        // Copy the peer's error buffer across to the server if it has any items
4700
        // in it so that we can restore peer errors across connections.
UNCOV
4701
        if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4702
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4703
        }
×
4704

4705
        // Inform the peer notifier of a peer offline event so that it can be
4706
        // reported to clients listening for peer events.
UNCOV
4707
        var pubKey [33]byte
×
UNCOV
4708
        copy(pubKey[:], pubSer)
×
UNCOV
4709

×
UNCOV
4710
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4711
}
4712

4713
// ConnectToPeer requests that the server connect to a Lightning Network peer
4714
// at the specified address. This function will *block* until either a
4715
// connection is established, or the initial handshake process fails.
4716
//
4717
// NOTE: This function is safe for concurrent access.
4718
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
4719
        perm bool, timeout time.Duration) error {
×
UNCOV
4720

×
UNCOV
4721
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4722

×
UNCOV
4723
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
4724
        // better granularity.  In certain conditions, this method requires
×
UNCOV
4725
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4726
        // lock to be released, and subsequently reacquired.
×
UNCOV
4727
        s.mu.Lock()
×
UNCOV
4728

×
UNCOV
4729
        // Ensure we're not already connected to this peer.
×
UNCOV
4730
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4731
        if err == nil {
×
UNCOV
4732
                s.mu.Unlock()
×
UNCOV
4733
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4734
        }
×
4735

4736
        // Peer was not found, continue to pursue connection with peer.
4737

4738
        // If there's already a pending connection request for this pubkey,
4739
        // then we ignore this request to ensure we don't create a redundant
4740
        // connection.
UNCOV
4741
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
4742
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
4743
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4744
        }
×
4745

4746
        // If there's not already a pending or active connection to this node,
4747
        // then instruct the connection manager to attempt to establish a
4748
        // persistent connection to the peer.
UNCOV
4749
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4750
        if perm {
×
UNCOV
4751
                connReq := &connmgr.ConnReq{
×
UNCOV
4752
                        Addr:      addr,
×
UNCOV
4753
                        Permanent: true,
×
UNCOV
4754
                }
×
UNCOV
4755

×
UNCOV
4756
                // Since the user requested a permanent connection, we'll set
×
UNCOV
4757
                // the entry to true which will tell the server to continue
×
UNCOV
4758
                // reconnecting even if the number of channels with this peer is
×
UNCOV
4759
                // zero.
×
UNCOV
4760
                s.persistentPeers[targetPub] = true
×
UNCOV
4761
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4762
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4763
                }
×
UNCOV
4764
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4765
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4766
                )
×
UNCOV
4767
                s.mu.Unlock()
×
UNCOV
4768

×
UNCOV
4769
                go s.connMgr.Connect(connReq)
×
UNCOV
4770

×
UNCOV
4771
                return nil
×
4772
        }
UNCOV
4773
        s.mu.Unlock()
×
UNCOV
4774

×
UNCOV
4775
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4776
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
4777
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
4778
        // caller.
×
UNCOV
4779
        errChan := make(chan error, 1)
×
UNCOV
4780
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
4781

×
UNCOV
4782
        select {
×
UNCOV
4783
        case err := <-errChan:
×
UNCOV
4784
                return err
×
4785
        case <-s.quit:
×
4786
                return ErrServerShuttingDown
×
4787
        }
4788
}
4789

4790
// connectToPeer establishes a connection to a remote peer. errChan is used to
4791
// notify the caller if the connection attempt has failed. Otherwise, it will be
4792
// closed.
4793
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
4794
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4795

×
UNCOV
4796
        conn, err := brontide.Dial(
×
UNCOV
4797
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4798
        )
×
UNCOV
4799
        if err != nil {
×
UNCOV
4800
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4801
                select {
×
UNCOV
4802
                case errChan <- err:
×
4803
                case <-s.quit:
×
4804
                }
UNCOV
4805
                return
×
4806
        }
4807

UNCOV
4808
        close(errChan)
×
UNCOV
4809

×
UNCOV
4810
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
4811
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4812

×
UNCOV
4813
        s.OutboundPeerConnected(nil, conn)
×
4814
}
4815

4816
// DisconnectPeer sends the request to server to close the connection with peer
4817
// identified by public key.
4818
//
4819
// NOTE: This function is safe for concurrent access.
UNCOV
4820
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
4821
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
4822
        pubStr := string(pubBytes)
×
UNCOV
4823

×
UNCOV
4824
        s.mu.Lock()
×
UNCOV
4825
        defer s.mu.Unlock()
×
UNCOV
4826

×
UNCOV
4827
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
4828
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
4829
        // currently connected to.
×
UNCOV
4830
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4831
        if err == ErrPeerNotConnected {
×
UNCOV
4832
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
4833
        }
×
4834

UNCOV
4835
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
4836

×
UNCOV
4837
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
4838

×
UNCOV
4839
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
4840
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
4841
        // disconnect.
×
UNCOV
4842
        delete(s.persistentPeers, pubStr)
×
UNCOV
4843
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
4844

×
UNCOV
4845
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
4846
        // removePeer, which bypassed the peerTerminationWatcher.
×
UNCOV
4847
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
4848

×
UNCOV
4849
        return nil
×
4850
}
4851

4852
// OpenChannel sends a request to the server to open a channel to the specified
4853
// peer identified by nodeKey with the passed channel funding parameters.
4854
//
4855
// NOTE: This function is safe for concurrent access.
4856
func (s *server) OpenChannel(
UNCOV
4857
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
4858

×
UNCOV
4859
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
4860
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
4861
        // not blocked if the caller is not reading the updates.
×
UNCOV
4862
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
4863
        req.Err = make(chan error, 1)
×
UNCOV
4864

×
UNCOV
4865
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
4866
        // we're unable to locate the peer then this request will fail.
×
UNCOV
4867
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
4868
        s.mu.RLock()
×
UNCOV
4869
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
4870
        if !ok {
×
4871
                s.mu.RUnlock()
×
4872

×
4873
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4874
                return req.Updates, req.Err
×
4875
        }
×
UNCOV
4876
        req.Peer = peer
×
UNCOV
4877
        s.mu.RUnlock()
×
UNCOV
4878

×
UNCOV
4879
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
4880
        // opening process.
×
UNCOV
4881
        select {
×
UNCOV
4882
        case <-peer.ActiveSignal():
×
4883
        case <-peer.QuitSignal():
×
4884
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4885
                return req.Updates, req.Err
×
4886
        case <-s.quit:
×
4887
                req.Err <- ErrServerShuttingDown
×
4888
                return req.Updates, req.Err
×
4889
        }
4890

4891
        // If the fee rate wasn't specified at this point we fail the funding
4892
        // because of the missing fee rate information. The caller of the
4893
        // `OpenChannel` method needs to make sure that default values for the
4894
        // fee rate are set beforehand.
UNCOV
4895
        if req.FundingFeePerKw == 0 {
×
4896
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4897
                        "the channel opening transaction")
×
4898

×
4899
                return req.Updates, req.Err
×
4900
        }
×
4901

4902
        // Spawn a goroutine to send the funding workflow request to the funding
4903
        // manager. This allows the server to continue handling queries instead
4904
        // of blocking on this request which is exported as a synchronous
4905
        // request to the outside world.
UNCOV
4906
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
4907

×
UNCOV
4908
        return req.Updates, req.Err
×
4909
}
4910

4911
// Peers returns a slice of all active peers.
4912
//
4913
// NOTE: This function is safe for concurrent access.
UNCOV
4914
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
4915
        s.mu.RLock()
×
UNCOV
4916
        defer s.mu.RUnlock()
×
UNCOV
4917

×
UNCOV
4918
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
4919
        for _, peer := range s.peersByPub {
×
UNCOV
4920
                peers = append(peers, peer)
×
UNCOV
4921
        }
×
4922

UNCOV
4923
        return peers
×
4924
}
4925

4926
// computeNextBackoff uses a truncated exponential backoff to compute the next
4927
// backoff using the value of the exiting backoff. The returned duration is
4928
// randomized in either direction by 1/20 to prevent tight loops from
4929
// stabilizing.
UNCOV
4930
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
4931
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
4932
        nextBackoff := 2 * currBackoff
×
UNCOV
4933
        if nextBackoff > maxBackoff {
×
UNCOV
4934
                nextBackoff = maxBackoff
×
UNCOV
4935
        }
×
4936

4937
        // Using 1/10 of our duration as a margin, compute a random offset to
4938
        // avoid the nodes entering connection cycles.
UNCOV
4939
        margin := nextBackoff / 10
×
UNCOV
4940

×
UNCOV
4941
        var wiggle big.Int
×
UNCOV
4942
        wiggle.SetUint64(uint64(margin))
×
UNCOV
4943
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
4944
                // Randomizing is not mission critical, so we'll just return the
×
4945
                // current backoff.
×
4946
                return nextBackoff
×
4947
        }
×
4948

4949
        // Otherwise add in our wiggle, but subtract out half of the margin so
4950
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
4951
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
4952
}
4953

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

4958
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
UNCOV
4959
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
4960
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
4961
        if err != nil {
×
4962
                return nil, err
×
4963
        }
×
4964

UNCOV
4965
        node, err := s.graphDB.FetchLightningNode(vertex)
×
UNCOV
4966
        if err != nil {
×
UNCOV
4967
                return nil, err
×
UNCOV
4968
        }
×
4969

UNCOV
4970
        if len(node.Addresses) == 0 {
×
UNCOV
4971
                return nil, errNoAdvertisedAddr
×
UNCOV
4972
        }
×
4973

UNCOV
4974
        return node.Addresses, nil
×
4975
}
4976

4977
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4978
// channel update for a target channel.
4979
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
4980
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
4981

×
UNCOV
4982
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
4983
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
4984
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
4985
                if err != nil {
×
UNCOV
4986
                        return nil, err
×
UNCOV
4987
                }
×
4988

UNCOV
4989
                return netann.ExtractChannelUpdate(
×
UNCOV
4990
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
4991
                )
×
4992
        }
4993
}
4994

4995
// applyChannelUpdate applies the channel update to the different sub-systems of
4996
// the server. The useAlias boolean denotes whether or not to send an alias in
4997
// place of the real SCID.
4998
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
4999
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
5000

×
UNCOV
5001
        var (
×
UNCOV
5002
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
5003
                defaultAlias lnwire.ShortChannelID
×
UNCOV
5004
        )
×
UNCOV
5005

×
UNCOV
5006
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
5007

×
UNCOV
5008
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
5009
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
5010
        if useAlias {
×
UNCOV
5011
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
5012
                if foundAlias != defaultAlias {
×
UNCOV
5013
                        peerAlias = &foundAlias
×
UNCOV
5014
                }
×
5015
        }
5016

UNCOV
5017
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
5018
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
5019
        )
×
UNCOV
5020
        select {
×
UNCOV
5021
        case err := <-errChan:
×
UNCOV
5022
                return err
×
5023
        case <-s.quit:
×
5024
                return ErrServerShuttingDown
×
5025
        }
5026
}
5027

5028
// SendCustomMessage sends a custom message to the peer with the specified
5029
// pubkey.
5030
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
5031
        data []byte) error {
×
UNCOV
5032

×
UNCOV
5033
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
5034
        if err != nil {
×
5035
                return err
×
5036
        }
×
5037

5038
        // We'll wait until the peer is active.
UNCOV
5039
        select {
×
UNCOV
5040
        case <-peer.ActiveSignal():
×
5041
        case <-peer.QuitSignal():
×
5042
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5043
        case <-s.quit:
×
5044
                return ErrServerShuttingDown
×
5045
        }
5046

UNCOV
5047
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
5048
        if err != nil {
×
UNCOV
5049
                return err
×
UNCOV
5050
        }
×
5051

5052
        // Send the message as low-priority. For now we assume that all
5053
        // application-defined message are low priority.
UNCOV
5054
        return peer.SendMessageLazy(true, msg)
×
5055
}
5056

5057
// newSweepPkScriptGen creates closure that generates a new public key script
5058
// which should be used to sweep any funds into the on-chain wallet.
5059
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5060
// (p2wkh) output.
5061
func newSweepPkScriptGen(
5062
        wallet lnwallet.WalletController,
UNCOV
5063
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5064

×
UNCOV
5065
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5066
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5067
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5068
                        lnwallet.DefaultAccountName,
×
UNCOV
5069
                )
×
UNCOV
5070
                if err != nil {
×
5071
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5072
                }
×
5073

UNCOV
5074
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5075
                if err != nil {
×
5076
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5077
                }
×
5078

UNCOV
5079
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5080
                        wallet, netParams, addr,
×
UNCOV
5081
                )
×
UNCOV
5082
                if err != nil {
×
5083
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5084
                }
×
5085

UNCOV
5086
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5087
                        DeliveryAddress: addr,
×
UNCOV
5088
                        InternalKey:     internalKeyDesc,
×
UNCOV
5089
                })
×
5090
        }
5091
}
5092

5093
// shouldPeerBootstrap returns true if we should attempt to perform peer
5094
// bootstrapping to actively seek our peers using the set of active network
5095
// bootstrappers.
5096
func shouldPeerBootstrap(cfg *Config) bool {
6✔
5097
        isSimnet := cfg.Bitcoin.SimNet
6✔
5098
        isSignet := cfg.Bitcoin.SigNet
6✔
5099
        isRegtest := cfg.Bitcoin.RegTest
6✔
5100
        isDevNetwork := isSimnet || isSignet || isRegtest
6✔
5101

6✔
5102
        // TODO(yy): remove the check on simnet/regtest such that the itest is
6✔
5103
        // covering the bootstrapping process.
6✔
5104
        return !cfg.NoNetBootstrap && !isDevNetwork
6✔
5105
}
6✔
5106

5107
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5108
// finished.
UNCOV
5109
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5110
        // Get a list of closed channels.
×
UNCOV
5111
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5112
        if err != nil {
×
5113
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5114
                return nil
×
5115
        }
×
5116

5117
        // Save the SCIDs in a map.
UNCOV
5118
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5119
        for _, c := range channels {
×
UNCOV
5120
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5121
                if !c.IsPending {
×
UNCOV
5122
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5123
                }
×
5124
        }
5125

5126
        // Double check whether the reported closed channel has indeed finished
5127
        // closing.
5128
        //
5129
        // NOTE: There are misalignments regarding when a channel's FC is
5130
        // marked as finalized. We double check the pending channels to make
5131
        // sure the returned SCIDs are indeed terminated.
5132
        //
5133
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5134
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5135
        if err != nil {
×
5136
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5137
                return nil
×
5138
        }
×
5139

UNCOV
5140
        for _, c := range pendings {
×
UNCOV
5141
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5142
                        continue
×
5143
                }
5144

5145
                // If the channel is still reported as pending, remove it from
5146
                // the map.
5147
                delete(closedSCIDs, c.ShortChannelID)
×
5148

×
5149
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5150
                        c.ShortChannelID)
×
5151
        }
5152

UNCOV
5153
        return closedSCIDs
×
5154
}
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