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

lightningnetwork / lnd / 11393106485

17 Oct 2024 09:10PM UTC coverage: 57.848% (-1.0%) from 58.81%
11393106485

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%)

18983 existing lines in 242 files now uncovered.

99003 of 171143 relevant lines covered (57.85%)

36968.25 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

138
// errPeerAlreadyConnected is an error returned by the server when we're
139
// commanded to connect to a peer, but they're already connected.
140
type errPeerAlreadyConnected struct {
141
        peer *peer.Brontide
142
}
143

144
// Error returns the human readable version of this error type.
145
//
146
// NOTE: Part of the error interface.
UNCOV
147
func (e *errPeerAlreadyConnected) Error() string {
×
UNCOV
148
        return fmt.Sprintf("already connected to peer: %v", e.peer)
×
UNCOV
149
}
×
150

151
// server is the main server of the Lightning Network Daemon. The server houses
152
// global state pertaining to the wallet, database, and the rpcserver.
153
// Additionally, the server is also used as a central messaging bus to interact
154
// with any of its companion objects.
155
type server struct {
156
        active   int32 // atomic
157
        stopping int32 // atomic
158

159
        start sync.Once
160
        stop  sync.Once
161

162
        cfg *Config
163

164
        implCfg *ImplementationCfg
165

166
        // identityECDH is an ECDH capable wrapper for the private key used
167
        // to authenticate any incoming connections.
168
        identityECDH keychain.SingleKeyECDH
169

170
        // identityKeyLoc is the key locator for the above wrapped identity key.
171
        identityKeyLoc keychain.KeyLocator
172

173
        // nodeSigner is an implementation of the MessageSigner implementation
174
        // that's backed by the identity private key of the running lnd node.
175
        nodeSigner *netann.NodeSigner
176

177
        chanStatusMgr *netann.ChanStatusManager
178

179
        // listenAddrs is the list of addresses the server is currently
180
        // listening on.
181
        listenAddrs []net.Addr
182

183
        // torController is a client that will communicate with a locally
184
        // running Tor server. This client will handle initiating and
185
        // authenticating the connection to the Tor server, automatically
186
        // creating and setting up onion services, etc.
187
        torController *tor.Controller
188

189
        // natTraversal is the specific NAT traversal technique used to
190
        // automatically set up port forwarding rules in order to advertise to
191
        // the network that the node is accepting inbound connections.
192
        natTraversal nat.Traversal
193

194
        // lastDetectedIP is the last IP detected by the NAT traversal technique
195
        // above. This IP will be watched periodically in a goroutine in order
196
        // to handle dynamic IP changes.
197
        lastDetectedIP net.IP
198

199
        mu         sync.RWMutex
200
        peersByPub map[string]*peer.Brontide
201

202
        inboundPeers  map[string]*peer.Brontide
203
        outboundPeers map[string]*peer.Brontide
204

205
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
206
        peerDisconnectedListeners map[string][]chan<- struct{}
207

208
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
209
        // will continue to send messages even if there are no active channels
210
        // and the value below is false. Once it's pruned, all its connections
211
        // will be closed, thus the Brontide.Start will return an error.
212
        persistentPeers        map[string]bool
213
        persistentPeersBackoff map[string]time.Duration
214
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
215
        persistentConnReqs     map[string][]*connmgr.ConnReq
216
        persistentRetryCancels map[string]chan struct{}
217

218
        // peerErrors keeps a set of peer error buffers for peers that have
219
        // disconnected from us. This allows us to track historic peer errors
220
        // over connections. The string of the peer's compressed pubkey is used
221
        // as a key for this map.
222
        peerErrors map[string]*queue.CircularBuffer
223

224
        // ignorePeerTermination tracks peers for which the server has initiated
225
        // a disconnect. Adding a peer to this map causes the peer termination
226
        // watcher to short circuit in the event that peers are purposefully
227
        // disconnected.
228
        ignorePeerTermination map[*peer.Brontide]struct{}
229

230
        // scheduledPeerConnection maps a pubkey string to a callback that
231
        // should be executed in the peerTerminationWatcher the prior peer with
232
        // the same pubkey exits.  This allows the server to wait until the
233
        // prior peer has cleaned up successfully, before adding the new peer
234
        // intended to replace it.
235
        scheduledPeerConnection map[string]func()
236

237
        // pongBuf is a shared pong reply buffer we'll use across all active
238
        // peer goroutines. We know the max size of a pong message
239
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
240
        // avoid allocations each time we need to send a pong message.
241
        pongBuf []byte
242

243
        cc *chainreg.ChainControl
244

245
        fundingMgr *funding.Manager
246

247
        graphDB *channeldb.ChannelGraph
248

249
        chanStateDB *channeldb.ChannelStateDB
250

251
        addrSource chanbackup.AddressSource
252

253
        // miscDB is the DB that contains all "other" databases within the main
254
        // channel DB that haven't been separated out yet.
255
        miscDB *channeldb.DB
256

257
        invoicesDB invoices.InvoiceDB
258

259
        aliasMgr *aliasmgr.Manager
260

261
        htlcSwitch *htlcswitch.Switch
262

263
        interceptableSwitch *htlcswitch.InterceptableSwitch
264

265
        invoices *invoices.InvoiceRegistry
266

267
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
268

269
        channelNotifier *channelnotifier.ChannelNotifier
270

271
        peerNotifier *peernotifier.PeerNotifier
272

273
        htlcNotifier *htlcswitch.HtlcNotifier
274

275
        witnessBeacon contractcourt.WitnessBeacon
276

277
        breachArbitrator *contractcourt.BreachArbitrator
278

279
        missionController *routing.MissionController
280
        defaultMC         *routing.MissionControl
281

282
        graphBuilder *graph.Builder
283

284
        chanRouter *routing.ChannelRouter
285

286
        controlTower routing.ControlTower
287

288
        authGossiper *discovery.AuthenticatedGossiper
289

290
        localChanMgr *localchans.Manager
291

292
        utxoNursery *contractcourt.UtxoNursery
293

294
        sweeper *sweep.UtxoSweeper
295

296
        chainArb *contractcourt.ChainArbitrator
297

298
        sphinx *hop.OnionProcessor
299

300
        towerClientMgr *wtclient.Manager
301

302
        connMgr *connmgr.ConnManager
303

304
        sigPool *lnwallet.SigPool
305

306
        writePool *pool.Write
307

308
        readPool *pool.Read
309

310
        tlsManager *TLSManager
311

312
        // featureMgr dispatches feature vectors for various contexts within the
313
        // daemon.
314
        featureMgr *feature.Manager
315

316
        // currentNodeAnn is the node announcement that has been broadcast to
317
        // the network upon startup, if the attributes of the node (us) has
318
        // changed since last start.
319
        currentNodeAnn *lnwire.NodeAnnouncement
320

321
        // chansToRestore is the set of channels that upon starting, the server
322
        // should attempt to restore/recover.
323
        chansToRestore walletunlocker.ChannelsToRecover
324

325
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
326
        // backups are consistent at all times. It interacts with the
327
        // channelNotifier to be notified of newly opened and closed channels.
328
        chanSubSwapper *chanbackup.SubSwapper
329

330
        // chanEventStore tracks the behaviour of channels and their remote peers to
331
        // provide insights into their health and performance.
332
        chanEventStore *chanfitness.ChannelEventStore
333

334
        hostAnn *netann.HostAnnouncer
335

336
        // livenessMonitor monitors that lnd has access to critical resources.
337
        livenessMonitor *healthcheck.Monitor
338

339
        customMessageServer *subscribe.Server
340

341
        // txPublisher is a publisher with fee-bumping capability.
342
        txPublisher *sweep.TxPublisher
343

344
        quit chan struct{}
345

346
        wg sync.WaitGroup
347
}
348

349
// updatePersistentPeerAddrs subscribes to topology changes and stores
350
// advertised addresses for any NodeAnnouncements from our persisted peers.
UNCOV
351
func (s *server) updatePersistentPeerAddrs() error {
×
UNCOV
352
        graphSub, err := s.graphBuilder.SubscribeTopology()
×
UNCOV
353
        if err != nil {
×
354
                return err
×
355
        }
×
356

UNCOV
357
        s.wg.Add(1)
×
UNCOV
358
        go func() {
×
UNCOV
359
                defer func() {
×
UNCOV
360
                        graphSub.Cancel()
×
UNCOV
361
                        s.wg.Done()
×
UNCOV
362
                }()
×
363

UNCOV
364
                for {
×
UNCOV
365
                        select {
×
UNCOV
366
                        case <-s.quit:
×
UNCOV
367
                                return
×
368

UNCOV
369
                        case topChange, ok := <-graphSub.TopologyChanges:
×
UNCOV
370
                                // If the router is shutting down, then we will
×
UNCOV
371
                                // as well.
×
UNCOV
372
                                if !ok {
×
373
                                        return
×
374
                                }
×
375

UNCOV
376
                                for _, update := range topChange.NodeUpdates {
×
UNCOV
377
                                        pubKeyStr := string(
×
UNCOV
378
                                                update.IdentityKey.
×
UNCOV
379
                                                        SerializeCompressed(),
×
UNCOV
380
                                        )
×
UNCOV
381

×
UNCOV
382
                                        // We only care about updates from
×
UNCOV
383
                                        // our persistentPeers.
×
UNCOV
384
                                        s.mu.RLock()
×
UNCOV
385
                                        _, ok := s.persistentPeers[pubKeyStr]
×
UNCOV
386
                                        s.mu.RUnlock()
×
UNCOV
387
                                        if !ok {
×
UNCOV
388
                                                continue
×
389
                                        }
390

UNCOV
391
                                        addrs := make([]*lnwire.NetAddress, 0,
×
UNCOV
392
                                                len(update.Addresses))
×
UNCOV
393

×
UNCOV
394
                                        for _, addr := range update.Addresses {
×
UNCOV
395
                                                addrs = append(addrs,
×
UNCOV
396
                                                        &lnwire.NetAddress{
×
UNCOV
397
                                                                IdentityKey: update.IdentityKey,
×
UNCOV
398
                                                                Address:     addr,
×
UNCOV
399
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
400
                                                        },
×
UNCOV
401
                                                )
×
UNCOV
402
                                        }
×
403

UNCOV
404
                                        s.mu.Lock()
×
UNCOV
405

×
UNCOV
406
                                        // Update the stored addresses for this
×
UNCOV
407
                                        // to peer to reflect the new set.
×
UNCOV
408
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
×
UNCOV
409

×
UNCOV
410
                                        // If there are no outstanding
×
UNCOV
411
                                        // connection requests for this peer
×
UNCOV
412
                                        // then our work is done since we are
×
UNCOV
413
                                        // not currently trying to connect to
×
UNCOV
414
                                        // them.
×
UNCOV
415
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
×
UNCOV
416
                                                s.mu.Unlock()
×
UNCOV
417
                                                continue
×
418
                                        }
419

UNCOV
420
                                        s.mu.Unlock()
×
UNCOV
421

×
UNCOV
422
                                        s.connectToPersistentPeer(pubKeyStr)
×
423
                                }
424
                        }
425
                }
426
        }()
427

UNCOV
428
        return nil
×
429
}
430

431
// CustomMessage is a custom message that is received from a peer.
432
type CustomMessage struct {
433
        // Peer is the peer pubkey
434
        Peer [33]byte
435

436
        // Msg is the custom wire message.
437
        Msg *lnwire.Custom
438
}
439

440
// parseAddr parses an address from its string format to a net.Addr.
UNCOV
441
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
×
UNCOV
442
        var (
×
UNCOV
443
                host string
×
UNCOV
444
                port int
×
UNCOV
445
        )
×
UNCOV
446

×
UNCOV
447
        // Split the address into its host and port components.
×
UNCOV
448
        h, p, err := net.SplitHostPort(address)
×
UNCOV
449
        if err != nil {
×
450
                // If a port wasn't specified, we'll assume the address only
×
451
                // contains the host so we'll use the default port.
×
452
                host = address
×
453
                port = defaultPeerPort
×
UNCOV
454
        } else {
×
UNCOV
455
                // Otherwise, we'll note both the host and ports.
×
UNCOV
456
                host = h
×
UNCOV
457
                portNum, err := strconv.Atoi(p)
×
UNCOV
458
                if err != nil {
×
459
                        return nil, err
×
460
                }
×
UNCOV
461
                port = portNum
×
462
        }
463

UNCOV
464
        if tor.IsOnionHost(host) {
×
465
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
466
        }
×
467

468
        // If the host is part of a TCP address, we'll use the network
469
        // specific ResolveTCPAddr function in order to resolve these
470
        // addresses over Tor in order to prevent leaking your real IP
471
        // address.
UNCOV
472
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
×
UNCOV
473
        return netCfg.ResolveTCPAddr("tcp", hostPort)
×
474
}
475

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

×
UNCOV
481
        return func(a net.Addr) (net.Conn, error) {
×
UNCOV
482
                lnAddr := a.(*lnwire.NetAddress)
×
UNCOV
483
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
×
UNCOV
484
        }
×
485
}
486

487
// newServer creates a new instance of the server which is to listen using the
488
// passed listener address.
489
func newServer(cfg *Config, listenAddrs []net.Addr,
490
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
491
        nodeKeyDesc *keychain.KeyDescriptor,
492
        chansToRestore walletunlocker.ChannelsToRecover,
493
        chanPredicate chanacceptor.ChannelAcceptor,
494
        torController *tor.Controller, tlsManager *TLSManager,
495
        leaderElector cluster.LeaderElector,
UNCOV
496
        implCfg *ImplementationCfg) (*server, error) {
×
UNCOV
497

×
UNCOV
498
        var (
×
UNCOV
499
                err         error
×
UNCOV
500
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
×
UNCOV
501

×
UNCOV
502
                // We just derived the full descriptor, so we know the public
×
UNCOV
503
                // key is set on it.
×
UNCOV
504
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
×
UNCOV
505
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
×
UNCOV
506
                )
×
UNCOV
507
        )
×
UNCOV
508

×
UNCOV
509
        listeners := make([]net.Listener, len(listenAddrs))
×
UNCOV
510
        for i, listenAddr := range listenAddrs {
×
UNCOV
511
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
×
UNCOV
512
                // doesn't need to call the general lndResolveTCP function
×
UNCOV
513
                // since we are resolving a local address.
×
UNCOV
514
                listeners[i], err = brontide.NewListener(
×
UNCOV
515
                        nodeKeyECDH, listenAddr.String(),
×
UNCOV
516
                )
×
UNCOV
517
                if err != nil {
×
518
                        return nil, err
×
519
                }
×
520
        }
521

UNCOV
522
        var serializedPubKey [33]byte
×
UNCOV
523
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
524

×
UNCOV
525
        netParams := cfg.ActiveNetParams.Params
×
UNCOV
526

×
UNCOV
527
        // Initialize the sphinx router.
×
UNCOV
528
        replayLog := htlcswitch.NewDecayedLog(
×
UNCOV
529
                dbs.DecayedLogDB, cc.ChainNotifier,
×
UNCOV
530
        )
×
UNCOV
531
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
×
UNCOV
532

×
UNCOV
533
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
534
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
535
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
536
        )
×
UNCOV
537

×
UNCOV
538
        writePool := pool.NewWrite(
×
UNCOV
539
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
UNCOV
540
        )
×
UNCOV
541

×
UNCOV
542
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
543
                pool.DefaultReadBufferGCInterval,
×
UNCOV
544
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
545
        )
×
UNCOV
546

×
UNCOV
547
        readPool := pool.NewRead(
×
UNCOV
548
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
UNCOV
549
        )
×
UNCOV
550

×
UNCOV
551
        // If the taproot overlay flag is set, but we don't have an aux funding
×
UNCOV
552
        // controller, then we'll exit as this is incompatible.
×
UNCOV
553
        if cfg.ProtocolOptions.TaprootOverlayChans &&
×
UNCOV
554
                implCfg.AuxFundingController.IsNone() {
×
555

×
556
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
557
                        "aux controllers")
×
558
        }
×
559

560
        //nolint:lll
UNCOV
561
        featureMgr, err := feature.NewManager(feature.Config{
×
UNCOV
562
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
×
UNCOV
563
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
×
UNCOV
564
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
×
UNCOV
565
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
566
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
×
UNCOV
567
                NoKeysend:                !cfg.AcceptKeySend,
×
UNCOV
568
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
×
UNCOV
569
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
×
UNCOV
570
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
×
UNCOV
571
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
×
UNCOV
572
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
×
UNCOV
573
                NoTaprootOverlay:         !cfg.ProtocolOptions.TaprootOverlayChans,
×
UNCOV
574
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
×
UNCOV
575
        })
×
UNCOV
576
        if err != nil {
×
577
                return nil, err
×
578
        }
×
579

UNCOV
580
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
UNCOV
581
        registryConfig := invoices.RegistryConfig{
×
UNCOV
582
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
583
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
UNCOV
584
                Clock:                       clock.NewDefaultClock(),
×
UNCOV
585
                AcceptKeySend:               cfg.AcceptKeySend,
×
UNCOV
586
                AcceptAMP:                   cfg.AcceptAMP,
×
UNCOV
587
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
UNCOV
588
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
UNCOV
589
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
UNCOV
590
                HtlcInterceptor:             invoiceHtlcModifier,
×
UNCOV
591
        }
×
UNCOV
592

×
UNCOV
593
        s := &server{
×
UNCOV
594
                cfg:            cfg,
×
UNCOV
595
                implCfg:        implCfg,
×
UNCOV
596
                graphDB:        dbs.GraphDB.ChannelGraph(),
×
UNCOV
597
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
598
                addrSource:     dbs.ChanStateDB,
×
UNCOV
599
                miscDB:         dbs.ChanStateDB,
×
UNCOV
600
                invoicesDB:     dbs.InvoiceDB,
×
UNCOV
601
                cc:             cc,
×
UNCOV
602
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
×
UNCOV
603
                writePool:      writePool,
×
UNCOV
604
                readPool:       readPool,
×
UNCOV
605
                chansToRestore: chansToRestore,
×
UNCOV
606

×
UNCOV
607
                channelNotifier: channelnotifier.New(
×
UNCOV
608
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
609
                ),
×
UNCOV
610

×
UNCOV
611
                identityECDH:   nodeKeyECDH,
×
UNCOV
612
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
613
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
614

×
UNCOV
615
                listenAddrs: listenAddrs,
×
UNCOV
616

×
UNCOV
617
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
618
                // schedule
×
UNCOV
619
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
620

×
UNCOV
621
                torController: torController,
×
UNCOV
622

×
UNCOV
623
                persistentPeers:         make(map[string]bool),
×
UNCOV
624
                persistentPeersBackoff:  make(map[string]time.Duration),
×
UNCOV
625
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
UNCOV
626
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
UNCOV
627
                persistentRetryCancels:  make(map[string]chan struct{}),
×
UNCOV
628
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
UNCOV
629
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
UNCOV
630
                scheduledPeerConnection: make(map[string]func()),
×
UNCOV
631
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
UNCOV
632

×
UNCOV
633
                peersByPub:                make(map[string]*peer.Brontide),
×
UNCOV
634
                inboundPeers:              make(map[string]*peer.Brontide),
×
UNCOV
635
                outboundPeers:             make(map[string]*peer.Brontide),
×
UNCOV
636
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
UNCOV
637
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
UNCOV
638

×
UNCOV
639
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
640

×
UNCOV
641
                customMessageServer: subscribe.NewServer(),
×
UNCOV
642

×
UNCOV
643
                tlsManager: tlsManager,
×
UNCOV
644

×
UNCOV
645
                featureMgr: featureMgr,
×
UNCOV
646
                quit:       make(chan struct{}),
×
UNCOV
647
        }
×
UNCOV
648

×
UNCOV
649
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
650
        if err != nil {
×
651
                return nil, err
×
652
        }
×
653

UNCOV
654
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
655
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
656
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
657
        )
×
UNCOV
658
        s.invoices = invoices.NewRegistry(
×
UNCOV
659
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
660
        )
×
UNCOV
661

×
UNCOV
662
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
663

×
UNCOV
664
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
665
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
666

×
UNCOV
667
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
668
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
669
                if err != nil {
×
670
                        return err
×
671
                }
×
672

UNCOV
673
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
674

×
UNCOV
675
                return nil
×
676
        }
677

UNCOV
678
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
679
        if err != nil {
×
680
                return nil, err
×
681
        }
×
682

UNCOV
683
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
684
                DB:                   dbs.ChanStateDB,
×
UNCOV
685
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
×
UNCOV
686
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
687
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
688
                LocalChannelClose: func(pubKey []byte,
×
UNCOV
689
                        request *htlcswitch.ChanClose) {
×
UNCOV
690

×
UNCOV
691
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
UNCOV
692
                        if err != nil {
×
693
                                srvrLog.Errorf("unable to close channel, peer"+
×
694
                                        " with %v id can't be found: %v",
×
695
                                        pubKey, err,
×
696
                                )
×
697
                                return
×
698
                        }
×
699

UNCOV
700
                        peer.HandleLocalCloseChanReqs(request)
×
701
                },
702
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
703
                SwitchPackager:         channeldb.NewSwitchPackager(),
704
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
705
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
706
                Notifier:               s.cc.ChainNotifier,
707
                HtlcNotifier:           s.htlcNotifier,
708
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
709
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
710
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
711
                AllowCircularRoute:     cfg.AllowCircularRoute,
712
                RejectHTLC:             cfg.RejectHTLC,
713
                Clock:                  clock.NewDefaultClock(),
714
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
715
                MaxFeeExposure:         thresholdMSats,
716
                SignAliasUpdate:        s.signAliasUpdate,
717
                IsAlias:                aliasmgr.IsAlias,
718
        }, uint32(currentHeight))
UNCOV
719
        if err != nil {
×
720
                return nil, err
×
721
        }
×
UNCOV
722
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
×
UNCOV
723
                &htlcswitch.InterceptableSwitchConfig{
×
UNCOV
724
                        Switch:             s.htlcSwitch,
×
UNCOV
725
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
726
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
×
UNCOV
727
                        RequireInterceptor: s.cfg.RequireInterceptor,
×
UNCOV
728
                        Notifier:           s.cc.ChainNotifier,
×
UNCOV
729
                },
×
UNCOV
730
        )
×
UNCOV
731
        if err != nil {
×
732
                return nil, err
×
733
        }
×
734

UNCOV
735
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
736
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
737
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
738
        )
×
UNCOV
739

×
UNCOV
740
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
741
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
742
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
UNCOV
743
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
UNCOV
744
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
745
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
746
                MessageSigner:            s.nodeSigner,
×
UNCOV
747
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
×
UNCOV
748
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
749
                DB:                       s.chanStateDB,
×
UNCOV
750
                Graph:                    dbs.GraphDB.ChannelGraph(),
×
UNCOV
751
        }
×
UNCOV
752

×
UNCOV
753
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
754
        if err != nil {
×
755
                return nil, err
×
756
        }
×
UNCOV
757
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
758

×
UNCOV
759
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
760
        // port forwarding for users behind a NAT.
×
UNCOV
761
        if cfg.NAT {
×
762
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
763

×
764
                discoveryTimeout := time.Duration(10 * time.Second)
×
765

×
766
                ctx, cancel := context.WithTimeout(
×
767
                        context.Background(), discoveryTimeout,
×
768
                )
×
769
                defer cancel()
×
770
                upnp, err := nat.DiscoverUPnP(ctx)
×
771
                if err == nil {
×
772
                        s.natTraversal = upnp
×
773
                } else {
×
774
                        // If we were not able to discover a UPnP enabled device
×
775
                        // on the local network, we'll fall back to attempting
×
776
                        // to discover a NAT-PMP enabled device.
×
777
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
778
                                "device on the local network: %v", err)
×
779

×
780
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
781
                                "enabled device")
×
782

×
783
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
784
                        if err != nil {
×
785
                                err := fmt.Errorf("unable to discover a "+
×
786
                                        "NAT-PMP enabled device on the local "+
×
787
                                        "network: %v", err)
×
788
                                srvrLog.Error(err)
×
789
                                return nil, err
×
790
                        }
×
791

792
                        s.natTraversal = pmp
×
793
                }
794
        }
795

796
        // If we were requested to automatically configure port forwarding,
797
        // we'll use the ports that the server will be listening on.
UNCOV
798
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
799
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
800
                externalIPStrings[idx] = ip.String()
×
UNCOV
801
        }
×
UNCOV
802
        if s.natTraversal != nil {
×
803
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
804
                for _, listenAddr := range listenAddrs {
×
805
                        // At this point, the listen addresses should have
×
806
                        // already been normalized, so it's safe to ignore the
×
807
                        // errors.
×
808
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
809
                        port, _ := strconv.Atoi(portStr)
×
810

×
811
                        listenPorts = append(listenPorts, uint16(port))
×
812
                }
×
813

814
                ips, err := s.configurePortForwarding(listenPorts...)
×
815
                if err != nil {
×
816
                        srvrLog.Errorf("Unable to automatically set up port "+
×
817
                                "forwarding using %s: %v",
×
818
                                s.natTraversal.Name(), err)
×
819
                } else {
×
820
                        srvrLog.Infof("Automatically set up port forwarding "+
×
821
                                "using %s to advertise external IP",
×
822
                                s.natTraversal.Name())
×
823
                        externalIPStrings = append(externalIPStrings, ips...)
×
824
                }
×
825
        }
826

827
        // If external IP addresses have been specified, add those to the list
828
        // of this server's addresses.
UNCOV
829
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
830
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
831
                cfg.net.ResolveTCPAddr,
×
UNCOV
832
        )
×
UNCOV
833
        if err != nil {
×
834
                return nil, err
×
835
        }
×
836

UNCOV
837
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
UNCOV
838
        selfAddrs = append(selfAddrs, externalIPs...)
×
UNCOV
839

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

×
UNCOV
844
        // We'll now reconstruct a node announcement based on our current
×
UNCOV
845
        // configuration so we can send it out as a sort of heart beat within
×
UNCOV
846
        // the network.
×
UNCOV
847
        //
×
UNCOV
848
        // We'll start by parsing the node color from configuration.
×
UNCOV
849
        color, err := lncfg.ParseHexColor(cfg.Color)
×
UNCOV
850
        if err != nil {
×
851
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
852
                return nil, err
×
853
        }
×
854

855
        // If no alias is provided, default to first 10 characters of public
856
        // key.
UNCOV
857
        alias := cfg.Alias
×
UNCOV
858
        if alias == "" {
×
UNCOV
859
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
860
        }
×
UNCOV
861
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
862
        if err != nil {
×
863
                return nil, err
×
864
        }
×
UNCOV
865
        selfNode := &channeldb.LightningNode{
×
UNCOV
866
                HaveNodeAnnouncement: true,
×
UNCOV
867
                LastUpdate:           time.Now(),
×
UNCOV
868
                Addresses:            selfAddrs,
×
UNCOV
869
                Alias:                nodeAlias.String(),
×
UNCOV
870
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
871
                Color:                color,
×
UNCOV
872
        }
×
UNCOV
873
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
874

×
UNCOV
875
        // Based on the disk representation of the node announcement generated
×
UNCOV
876
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
877
        // network so we can properly sign it.
×
UNCOV
878
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
879
        if err != nil {
×
880
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
881
        }
×
882

883
        // With the announcement generated, we'll sign it to properly
884
        // authenticate the message on the network.
UNCOV
885
        authSig, err := netann.SignAnnouncement(
×
UNCOV
886
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
887
        )
×
UNCOV
888
        if err != nil {
×
889
                return nil, fmt.Errorf("unable to generate signature for "+
×
890
                        "self node announcement: %v", err)
×
891
        }
×
UNCOV
892
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
893
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
894
                selfNode.AuthSigBytes,
×
UNCOV
895
        )
×
UNCOV
896
        if err != nil {
×
897
                return nil, err
×
898
        }
×
899

900
        // Finally, we'll update the representation on disk, and update our
901
        // cached in-memory version as well.
UNCOV
902
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
×
903
                return nil, fmt.Errorf("can't set self node: %w", err)
×
904
        }
×
UNCOV
905
        s.currentNodeAnn = nodeAnn
×
UNCOV
906

×
UNCOV
907
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
908
        // can generate unique payment IDs.
×
UNCOV
909
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
910
        if err != nil {
×
911
                return nil, err
×
912
        }
×
913

914
        // Instantiate mission control with config from the sub server.
915
        //
916
        // TODO(joostjager): When we are further in the process of moving to sub
917
        // servers, the mission control instance itself can be moved there too.
UNCOV
918
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
919

×
UNCOV
920
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
921
        var estimator routing.Estimator
×
UNCOV
922
        if cfg.Estimator != nil {
×
923
                estimator = cfg.Estimator
×
UNCOV
924
        } else {
×
UNCOV
925
                switch routingConfig.ProbabilityEstimatorType {
×
UNCOV
926
                case routing.AprioriEstimatorName:
×
UNCOV
927
                        aCfg := routingConfig.AprioriConfig
×
UNCOV
928
                        aprioriConfig := routing.AprioriConfig{
×
UNCOV
929
                                AprioriHopProbability: aCfg.HopProbability,
×
UNCOV
930
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
UNCOV
931
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
932
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
933
                        }
×
UNCOV
934

×
UNCOV
935
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
936
                                aprioriConfig,
×
UNCOV
937
                        )
×
UNCOV
938
                        if err != nil {
×
939
                                return nil, err
×
940
                        }
×
941

942
                case routing.BimodalEstimatorName:
×
943
                        bCfg := routingConfig.BimodalConfig
×
944
                        bimodalConfig := routing.BimodalConfig{
×
945
                                BimodalNodeWeight: bCfg.NodeWeight,
×
946
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
947
                                        bCfg.Scale,
×
948
                                ),
×
949
                                BimodalDecayTime: bCfg.DecayTime,
×
950
                        }
×
951

×
952
                        estimator, err = routing.NewBimodalEstimator(
×
953
                                bimodalConfig,
×
954
                        )
×
955
                        if err != nil {
×
956
                                return nil, err
×
957
                        }
×
958

959
                default:
×
960
                        return nil, fmt.Errorf("unknown estimator type %v",
×
961
                                routingConfig.ProbabilityEstimatorType)
×
962
                }
963
        }
964

UNCOV
965
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
966
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
967
                Estimator:               estimator,
×
UNCOV
968
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
969
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
970
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
UNCOV
971
        }
×
UNCOV
972

×
UNCOV
973
        s.missionController, err = routing.NewMissionController(
×
UNCOV
974
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
UNCOV
975
        )
×
UNCOV
976
        if err != nil {
×
977
                return nil, fmt.Errorf("can't create mission control "+
×
978
                        "manager: %w", err)
×
979
        }
×
UNCOV
980
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
981
                routing.DefaultMissionControlNamespace,
×
UNCOV
982
        )
×
UNCOV
983
        if err != nil {
×
984
                return nil, fmt.Errorf("can't create mission control in the "+
×
985
                        "default namespace: %w", err)
×
986
        }
×
987

UNCOV
988
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
989
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
990
                int64(routingConfig.AttemptCost),
×
UNCOV
991
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
992
                routingConfig.MinRouteProbability)
×
UNCOV
993

×
UNCOV
994
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
995
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
996
                        routingConfig.AttemptCost,
×
UNCOV
997
                ),
×
UNCOV
998
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
999
                MinProbability: routingConfig.MinRouteProbability,
×
UNCOV
1000
        }
×
UNCOV
1001

×
UNCOV
1002
        sourceNode, err := chanGraph.SourceNode()
×
UNCOV
1003
        if err != nil {
×
1004
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1005
        }
×
UNCOV
1006
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
1007
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
×
UNCOV
1008
                        chanGraph,
×
UNCOV
1009
                ),
×
UNCOV
1010
                SourceNode:        sourceNode,
×
UNCOV
1011
                MissionControl:    s.defaultMC,
×
UNCOV
1012
                GetLink:           s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1013
                PathFindingConfig: pathFindingConfig,
×
UNCOV
1014
        }
×
UNCOV
1015

×
UNCOV
1016
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1017

×
UNCOV
1018
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1019

×
UNCOV
1020
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1021
                cfg.Routing.StrictZombiePruning
×
UNCOV
1022

×
UNCOV
1023
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1024
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1025
                Graph:               chanGraph,
×
UNCOV
1026
                Chain:               cc.ChainIO,
×
UNCOV
1027
                ChainView:           cc.ChainView,
×
UNCOV
1028
                Notifier:            cc.ChainNotifier,
×
UNCOV
1029
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1030
                GraphPruneInterval:  time.Hour,
×
UNCOV
1031
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1032
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1033
                StrictZombiePruning: strictPruning,
×
UNCOV
1034
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1035
        })
×
UNCOV
1036
        if err != nil {
×
1037
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1038
        }
×
1039

UNCOV
1040
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1041
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1042
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
×
UNCOV
1043
                Chain:              cc.ChainIO,
×
UNCOV
1044
                Payer:              s.htlcSwitch,
×
UNCOV
1045
                Control:            s.controlTower,
×
UNCOV
1046
                MissionControl:     s.defaultMC,
×
UNCOV
1047
                SessionSource:      paymentSessionSource,
×
UNCOV
1048
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1049
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1050
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1051
                Clock:              clock.NewDefaultClock(),
×
UNCOV
1052
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
×
UNCOV
1053
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1054
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1055
        })
×
UNCOV
1056
        if err != nil {
×
1057
                return nil, fmt.Errorf("can't create router: %w", err)
×
1058
        }
×
1059

UNCOV
1060
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1061
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1062
        if err != nil {
×
1063
                return nil, err
×
1064
        }
×
UNCOV
1065
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1066
        if err != nil {
×
1067
                return nil, err
×
1068
        }
×
1069

UNCOV
1070
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1071

×
UNCOV
1072
        s.authGossiper = discovery.New(discovery.Config{
×
UNCOV
1073
                Graph:                 s.graphBuilder,
×
UNCOV
1074
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1075
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1076
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1077
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1078
                ChanSeries:            chanSeries,
×
UNCOV
1079
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1080
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1081
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
UNCOV
1082
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1083
                        error) {
×
1084

×
1085
                        return s.genNodeAnnouncement(nil)
×
1086
                },
×
1087
                ProofMatureDelta:        0,
1088
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1089
                RetransmitTicker:        ticker.New(time.Minute * 30),
1090
                RebroadcastInterval:     time.Hour * 24,
1091
                WaitingProofStore:       waitingProofStore,
1092
                MessageStore:            gossipMessageStore,
1093
                AnnSigner:               s.nodeSigner,
1094
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1095
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1096
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1097
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
1098
                MinimumBatchSize:        10,
1099
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1100
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1101
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1102
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1103
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1104
                IsAlias:                 aliasmgr.IsAlias,
1105
                SignAliasUpdate:         s.signAliasUpdate,
1106
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1107
                GetAlias:                s.aliasMgr.GetPeerAlias,
1108
                FindChannel:             s.findChannel,
1109
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1110
                ScidCloser:              scidCloserMan,
1111
        }, nodeKeyDesc)
1112

1113
        //nolint:lll
UNCOV
1114
        s.localChanMgr = &localchans.Manager{
×
UNCOV
1115
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
×
UNCOV
1116
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
×
UNCOV
1117
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
×
UNCOV
1118
                FetchChannel:              s.chanStateDB.FetchChannel,
×
UNCOV
1119
        }
×
UNCOV
1120

×
UNCOV
1121
        utxnStore, err := contractcourt.NewNurseryStore(
×
UNCOV
1122
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
×
UNCOV
1123
        )
×
UNCOV
1124
        if err != nil {
×
1125
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1126
                return nil, err
×
1127
        }
×
1128

UNCOV
1129
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1130
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1131
        )
×
UNCOV
1132
        if err != nil {
×
1133
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1134
                return nil, err
×
1135
        }
×
1136

UNCOV
1137
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1138
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1139
                s.implCfg.AuxSweeper,
×
UNCOV
1140
        )
×
UNCOV
1141

×
UNCOV
1142
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
×
UNCOV
1143
                Signer:     cc.Wallet.Cfg.Signer,
×
UNCOV
1144
                Wallet:     cc.Wallet,
×
UNCOV
1145
                Estimator:  cc.FeeEstimator,
×
UNCOV
1146
                Notifier:   cc.ChainNotifier,
×
UNCOV
1147
                AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1148
        })
×
UNCOV
1149

×
UNCOV
1150
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
UNCOV
1151
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1152
                GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1153
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1154
                ),
×
UNCOV
1155
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1156
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1157
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1158
                Notifier:             cc.ChainNotifier,
×
UNCOV
1159
                Store:                sweeperStore,
×
UNCOV
1160
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1161
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1162
                Aggregator:           aggregator,
×
UNCOV
1163
                Publisher:            s.txPublisher,
×
UNCOV
1164
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1165
        })
×
UNCOV
1166

×
UNCOV
1167
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1168
                ChainIO:             cc.ChainIO,
×
UNCOV
1169
                ConfDepth:           1,
×
UNCOV
1170
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1171
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1172
                Notifier:            cc.ChainNotifier,
×
UNCOV
1173
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1174
                Store:               utxnStore,
×
UNCOV
1175
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1176
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1177
        })
×
UNCOV
1178

×
UNCOV
1179
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1180
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1181
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1182
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1183
                // returned by CloseLink.
×
UNCOV
1184

×
UNCOV
1185
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1186
                // delivery script or target fee per kw because user input is not
×
UNCOV
1187
                // available when the remote peer closes the channel.
×
UNCOV
1188
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
×
UNCOV
1189
        }
×
1190

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

×
UNCOV
1195
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1196
                &contractcourt.BreachConfig{
×
UNCOV
1197
                        CloseLink: closeLink,
×
UNCOV
1198
                        DB:        s.chanStateDB,
×
UNCOV
1199
                        Estimator: s.cc.FeeEstimator,
×
UNCOV
1200
                        GenSweepScript: newSweepPkScriptGen(
×
UNCOV
1201
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
×
UNCOV
1202
                        ),
×
UNCOV
1203
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1204
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1205
                        ContractBreaches:   contractBreaches,
×
UNCOV
1206
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1207
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1208
                                dbs.ChanStateDB,
×
UNCOV
1209
                        ),
×
UNCOV
1210
                        AuxSweeper: s.implCfg.AuxSweeper,
×
UNCOV
1211
                },
×
UNCOV
1212
        )
×
UNCOV
1213

×
UNCOV
1214
        //nolint:lll
×
UNCOV
1215
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1216
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1217
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1218
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1219
                NewSweepAddr: func() ([]byte, error) {
×
1220
                        addr, err := newSweepPkScriptGen(
×
1221
                                cc.Wallet, netParams,
×
1222
                        )().Unpack()
×
1223
                        if err != nil {
×
1224
                                return nil, err
×
1225
                        }
×
1226

1227
                        return addr.DeliveryAddress, nil
×
1228
                },
1229
                PublishTx: cc.Wallet.PublishTransaction,
UNCOV
1230
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1231
                        for _, msg := range msgs {
×
UNCOV
1232
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1233
                                if err != nil {
×
1234
                                        return err
×
1235
                                }
×
1236
                        }
UNCOV
1237
                        return nil
×
1238
                },
1239
                IncubateOutputs: func(chanPoint wire.OutPoint,
1240
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1241
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1242
                        broadcastHeight uint32,
UNCOV
1243
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1244

×
UNCOV
1245
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1246
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1247
                                broadcastHeight, deadlineHeight,
×
UNCOV
1248
                        )
×
UNCOV
1249
                },
×
1250
                PreimageDB:   s.witnessBeacon,
1251
                Notifier:     cc.ChainNotifier,
1252
                Mempool:      cc.MempoolNotifier,
1253
                Signer:       cc.Wallet.Cfg.Signer,
1254
                FeeEstimator: cc.FeeEstimator,
1255
                ChainIO:      cc.ChainIO,
UNCOV
1256
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
UNCOV
1257
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1258
                        s.htlcSwitch.RemoveLink(chanID)
×
UNCOV
1259
                        return nil
×
UNCOV
1260
                },
×
1261
                IsOurAddress: cc.Wallet.IsOurAddress,
1262
                ContractBreach: func(chanPoint wire.OutPoint,
UNCOV
1263
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1264

×
UNCOV
1265
                        // processACK will handle the BreachArbitrator ACKing
×
UNCOV
1266
                        // the event.
×
UNCOV
1267
                        finalErr := make(chan error, 1)
×
UNCOV
1268
                        processACK := func(brarErr error) {
×
UNCOV
1269
                                if brarErr != nil {
×
1270
                                        finalErr <- brarErr
×
1271
                                        return
×
1272
                                }
×
1273

1274
                                // If the BreachArbitrator successfully handled
1275
                                // the event, we can signal that the handoff
1276
                                // was successful.
UNCOV
1277
                                finalErr <- nil
×
1278
                        }
1279

UNCOV
1280
                        event := &contractcourt.ContractBreachEvent{
×
UNCOV
1281
                                ChanPoint:         chanPoint,
×
UNCOV
1282
                                ProcessACK:        processACK,
×
UNCOV
1283
                                BreachRetribution: breachRet,
×
UNCOV
1284
                        }
×
UNCOV
1285

×
UNCOV
1286
                        // Send the contract breach event to the
×
UNCOV
1287
                        // BreachArbitrator.
×
UNCOV
1288
                        select {
×
UNCOV
1289
                        case contractBreaches <- event:
×
1290
                        case <-s.quit:
×
1291
                                return ErrServerShuttingDown
×
1292
                        }
1293

1294
                        // We'll wait for a final error to be available from
1295
                        // the BreachArbitrator.
UNCOV
1296
                        select {
×
UNCOV
1297
                        case err := <-finalErr:
×
UNCOV
1298
                                return err
×
1299
                        case <-s.quit:
×
1300
                                return ErrServerShuttingDown
×
1301
                        }
1302
                },
UNCOV
1303
                DisableChannel: func(chanPoint wire.OutPoint) error {
×
UNCOV
1304
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
×
UNCOV
1305
                },
×
1306
                Sweeper:                       s.sweeper,
1307
                Registry:                      s.invoices,
1308
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1309
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1310
                OnionProcessor:                s.sphinx,
1311
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1312
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1313
                Clock:                         clock.NewDefaultClock(),
1314
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1315
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1316
                HtlcNotifier:                  s.htlcNotifier,
1317
                Budget:                        *s.cfg.Sweeper.Budget,
1318

1319
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1320
                QueryIncomingCircuit: func(
UNCOV
1321
                        circuit models.CircuitKey) *models.CircuitKey {
×
UNCOV
1322

×
UNCOV
1323
                        // Get the circuit map.
×
UNCOV
1324
                        circuits := s.htlcSwitch.CircuitLookup()
×
UNCOV
1325

×
UNCOV
1326
                        // Lookup the outgoing circuit.
×
UNCOV
1327
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1328
                        if pc == nil {
×
UNCOV
1329
                                return nil
×
UNCOV
1330
                        }
×
1331

UNCOV
1332
                        return &pc.Incoming
×
1333
                },
1334
                AuxLeafStore: implCfg.AuxLeafStore,
1335
                AuxSigner:    implCfg.AuxSigner,
1336
                AuxResolver:  implCfg.AuxContractResolver,
1337
        }, dbs.ChanStateDB)
1338

1339
        // Select the configuration and funding parameters for Bitcoin.
UNCOV
1340
        chainCfg := cfg.Bitcoin
×
UNCOV
1341
        minRemoteDelay := funding.MinBtcRemoteDelay
×
UNCOV
1342
        maxRemoteDelay := funding.MaxBtcRemoteDelay
×
UNCOV
1343

×
UNCOV
1344
        var chanIDSeed [32]byte
×
UNCOV
1345
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
×
1346
                return nil, err
×
1347
        }
×
1348

1349
        // Wrap the DeleteChannelEdges method so that the funding manager can
1350
        // use it without depending on several layers of indirection.
UNCOV
1351
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1352
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1353

×
UNCOV
1354
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1355
                        scid.ToUint64(),
×
UNCOV
1356
                )
×
UNCOV
1357
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
×
1358
                        // This is unlikely but there is a slim chance of this
×
1359
                        // being hit if lnd was killed via SIGKILL and the
×
1360
                        // funding manager was stepping through the delete
×
1361
                        // alias edge logic.
×
1362
                        return nil, nil
×
UNCOV
1363
                } else if err != nil {
×
1364
                        return nil, err
×
1365
                }
×
1366

1367
                // Grab our key to find our policy.
UNCOV
1368
                var ourKey [33]byte
×
UNCOV
1369
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
1370

×
UNCOV
1371
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1372
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1373
                        ourPolicy = e1
×
UNCOV
1374
                } else {
×
UNCOV
1375
                        ourPolicy = e2
×
UNCOV
1376
                }
×
1377

UNCOV
1378
                if ourPolicy == nil {
×
1379
                        // Something is wrong, so return an error.
×
1380
                        return nil, fmt.Errorf("we don't have an edge")
×
1381
                }
×
1382

UNCOV
1383
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1384
                        false, false, scid.ToUint64(),
×
UNCOV
1385
                )
×
UNCOV
1386
                return ourPolicy, err
×
1387
        }
1388

1389
        // For the reservationTimeout and the zombieSweeperInterval different
1390
        // values are set in case we are in a dev environment so enhance test
1391
        // capacilities.
UNCOV
1392
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1393
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1394

×
UNCOV
1395
        // Get the development config for funding manager. If we are not in
×
UNCOV
1396
        // development mode, this would be nil.
×
UNCOV
1397
        var devCfg *funding.DevConfig
×
UNCOV
1398
        if lncfg.IsDevBuild() {
×
UNCOV
1399
                devCfg = &funding.DevConfig{
×
UNCOV
1400
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1401
                }
×
UNCOV
1402

×
UNCOV
1403
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1404
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1405

×
UNCOV
1406
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
UNCOV
1407
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
×
UNCOV
1408
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1409
        }
×
1410

1411
        //nolint:lll
UNCOV
1412
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
×
UNCOV
1413
                Dev:                devCfg,
×
UNCOV
1414
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1415
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1416
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
UNCOV
1417
                Wallet:             cc.Wallet,
×
UNCOV
1418
                PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1419
                UpdateLabel: func(hash chainhash.Hash, label string) error {
×
UNCOV
1420
                        return cc.Wallet.LabelTransaction(hash, label, true)
×
UNCOV
1421
                },
×
1422
                Notifier:     cc.ChainNotifier,
1423
                ChannelDB:    s.chanStateDB,
1424
                FeeEstimator: cc.FeeEstimator,
1425
                SignMessage:  cc.MsgSigner.SignMessage,
1426
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1427
                        error) {
×
UNCOV
1428

×
UNCOV
1429
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1430
                },
×
1431
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1432
                NotifyWhenOnline:     s.NotifyWhenOnline,
1433
                TempChanIDSeed:       chanIDSeed,
1434
                FindChannel:          s.findChannel,
1435
                DefaultRoutingPolicy: cc.RoutingPolicy,
1436
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1437
                NumRequiredConfs: func(chanAmt btcutil.Amount,
UNCOV
1438
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1439
                        // For large channels we increase the number
×
UNCOV
1440
                        // of confirmations we require for the
×
UNCOV
1441
                        // channel to be considered open. As it is
×
UNCOV
1442
                        // always the responder that gets to choose
×
UNCOV
1443
                        // value, the pushAmt is value being pushed
×
UNCOV
1444
                        // to us. This means we have more to lose
×
UNCOV
1445
                        // in the case this gets re-orged out, and
×
UNCOV
1446
                        // we will require more confirmations before
×
UNCOV
1447
                        // we consider it open.
×
UNCOV
1448

×
UNCOV
1449
                        // In case the user has explicitly specified
×
UNCOV
1450
                        // a default value for the number of
×
UNCOV
1451
                        // confirmations, we use it.
×
UNCOV
1452
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
×
UNCOV
1453
                        if defaultConf != 0 {
×
UNCOV
1454
                                return defaultConf
×
UNCOV
1455
                        }
×
1456

1457
                        minConf := uint64(3)
×
1458
                        maxConf := uint64(6)
×
1459

×
1460
                        // If this is a wumbo channel, then we'll require the
×
1461
                        // max amount of confirmations.
×
1462
                        if chanAmt > MaxFundingAmount {
×
1463
                                return uint16(maxConf)
×
1464
                        }
×
1465

1466
                        // If not we return a value scaled linearly
1467
                        // between 3 and 6, depending on channel size.
1468
                        // TODO(halseth): Use 1 as minimum?
1469
                        maxChannelSize := uint64(
×
1470
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1471
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1472
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1473
                        if conf < minConf {
×
1474
                                conf = minConf
×
1475
                        }
×
1476
                        if conf > maxConf {
×
1477
                                conf = maxConf
×
1478
                        }
×
1479
                        return uint16(conf)
×
1480
                },
UNCOV
1481
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1482
                        // We scale the remote CSV delay (the time the
×
UNCOV
1483
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1484
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1485
                        // for small channels, to maxRemoteDelay blocks
×
UNCOV
1486
                        // for channels of size MaxFundingAmount.
×
UNCOV
1487

×
UNCOV
1488
                        // In case the user has explicitly specified
×
UNCOV
1489
                        // a default value for the remote delay, we
×
UNCOV
1490
                        // use it.
×
UNCOV
1491
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1492
                        if defaultDelay > 0 {
×
UNCOV
1493
                                return defaultDelay
×
UNCOV
1494
                        }
×
1495

1496
                        // If this is a wumbo channel, then we'll require the
1497
                        // max value.
1498
                        if chanAmt > MaxFundingAmount {
×
1499
                                return maxRemoteDelay
×
1500
                        }
×
1501

1502
                        // If not we scale according to channel size.
1503
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1504
                                chanAmt / MaxFundingAmount)
×
1505
                        if delay < minRemoteDelay {
×
1506
                                delay = minRemoteDelay
×
1507
                        }
×
1508
                        if delay > maxRemoteDelay {
×
1509
                                delay = maxRemoteDelay
×
1510
                        }
×
1511
                        return delay
×
1512
                },
1513
                WatchNewChannel: func(channel *channeldb.OpenChannel,
UNCOV
1514
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1515

×
UNCOV
1516
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1517
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1518
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1519
                        // we'll set false to prevent the server from continuing
×
UNCOV
1520
                        // to connect to this peer even if the number of
×
UNCOV
1521
                        // channels with this peer is zero.
×
UNCOV
1522
                        s.mu.Lock()
×
UNCOV
1523
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1524
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
1525
                                s.persistentPeers[pubStr] = false
×
UNCOV
1526
                        }
×
UNCOV
1527
                        s.mu.Unlock()
×
UNCOV
1528

×
UNCOV
1529
                        // With that taken care of, we'll send this channel to
×
UNCOV
1530
                        // the chain arb so it can react to on-chain events.
×
UNCOV
1531
                        return s.chainArb.WatchNewChannel(channel)
×
1532
                },
UNCOV
1533
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1534
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1535
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1536
                },
×
1537
                RequiredRemoteChanReserve: func(chanAmt,
UNCOV
1538
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1539

×
UNCOV
1540
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1541
                        // at least 1% of the total channel capacity at all
×
UNCOV
1542
                        // times. If this value ends up dipping below the dust
×
UNCOV
1543
                        // limit, then we'll use the dust limit itself as the
×
UNCOV
1544
                        // reserve as required by BOLT #2.
×
UNCOV
1545
                        reserve := chanAmt / 100
×
UNCOV
1546
                        if reserve < dustLimit {
×
UNCOV
1547
                                reserve = dustLimit
×
UNCOV
1548
                        }
×
1549

UNCOV
1550
                        return reserve
×
1551
                },
UNCOV
1552
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1553
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1554
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1555
                        // required reserve.
×
UNCOV
1556
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1557
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1558
                },
×
UNCOV
1559
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1560
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1561
                                return cfg.DefaultRemoteMaxHtlcs
×
UNCOV
1562
                        }
×
1563

1564
                        // By default, we'll permit them to utilize the full
1565
                        // channel bandwidth.
1566
                        return uint16(input.MaxHTLCNumber / 2)
×
1567
                },
1568
                ZombieSweeperInterval:         zombieSweeperInterval,
1569
                ReservationTimeout:            reservationTimeout,
1570
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1571
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1572
                MaxPendingChannels:            cfg.MaxPendingChannels,
1573
                RejectPush:                    cfg.RejectPush,
1574
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1575
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1576
                OpenChannelPredicate:          chanPredicate,
1577
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1578
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1579
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1580
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1581
                DeleteAliasEdge:      deleteAliasEdge,
1582
                AliasManager:         s.aliasMgr,
1583
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1584
                AuxFundingController: implCfg.AuxFundingController,
1585
                AuxSigner:            implCfg.AuxSigner,
1586
                AuxResolver:          implCfg.AuxContractResolver,
1587
        })
UNCOV
1588
        if err != nil {
×
1589
                return nil, err
×
1590
        }
×
1591

1592
        // Next, we'll assemble the sub-system that will maintain an on-disk
1593
        // static backup of the latest channel state.
UNCOV
1594
        chanNotifier := &channelNotifier{
×
UNCOV
1595
                chanNotifier: s.channelNotifier,
×
UNCOV
1596
                addrs:        dbs.ChanStateDB,
×
UNCOV
1597
        }
×
UNCOV
1598
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
×
UNCOV
1599
        startingChans, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
1600
                s.chanStateDB, s.addrSource,
×
UNCOV
1601
        )
×
UNCOV
1602
        if err != nil {
×
1603
                return nil, err
×
1604
        }
×
UNCOV
1605
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
×
UNCOV
1606
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
×
UNCOV
1607
        )
×
UNCOV
1608
        if err != nil {
×
1609
                return nil, err
×
1610
        }
×
1611

1612
        // Assemble a peer notifier which will provide clients with subscriptions
1613
        // to peer online and offline events.
UNCOV
1614
        s.peerNotifier = peernotifier.New()
×
UNCOV
1615

×
UNCOV
1616
        // Create a channel event store which monitors all open channels.
×
UNCOV
1617
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
×
UNCOV
1618
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1619
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1620
                },
×
UNCOV
1621
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
UNCOV
1622
                        return s.peerNotifier.SubscribePeerEvents()
×
UNCOV
1623
                },
×
1624
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1625
                Clock:           clock.NewDefaultClock(),
1626
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1627
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1628
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1629
        })
1630

UNCOV
1631
        if cfg.WtClient.Active {
×
UNCOV
1632
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1633
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1634

×
UNCOV
1635
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1636
                // protocol operations on sat/kw.
×
UNCOV
1637
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1638
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1639
                )
×
UNCOV
1640

×
UNCOV
1641
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
UNCOV
1642

×
UNCOV
1643
                if err := policy.Validate(); err != nil {
×
1644
                        return nil, err
×
1645
                }
×
1646

1647
                // authDial is the wrapper around the btrontide.Dial for the
1648
                // watchtower.
UNCOV
1649
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1650
                        netAddr *lnwire.NetAddress,
×
UNCOV
1651
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1652

×
UNCOV
1653
                        return brontide.Dial(
×
UNCOV
1654
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
UNCOV
1655
                        )
×
UNCOV
1656
                }
×
1657

1658
                // buildBreachRetribution is a call-back that can be used to
1659
                // query the BreachRetribution info and channel type given a
1660
                // channel ID and commitment height.
UNCOV
1661
                buildBreachRetribution := func(chanID lnwire.ChannelID,
×
UNCOV
1662
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1663
                        channeldb.ChannelType, error) {
×
UNCOV
1664

×
UNCOV
1665
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1666
                                nil, chanID,
×
UNCOV
1667
                        )
×
UNCOV
1668
                        if err != nil {
×
1669
                                return nil, 0, err
×
1670
                        }
×
1671

UNCOV
1672
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1673
                                channel, commitHeight, 0, nil,
×
UNCOV
1674
                                implCfg.AuxLeafStore,
×
UNCOV
1675
                                implCfg.AuxContractResolver,
×
UNCOV
1676
                        )
×
UNCOV
1677
                        if err != nil {
×
1678
                                return nil, 0, err
×
1679
                        }
×
1680

UNCOV
1681
                        return br, channel.ChanType, nil
×
1682
                }
1683

UNCOV
1684
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1685

×
UNCOV
1686
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1687
                // signalling support for anchor channels.
×
UNCOV
1688
                anchorPolicy := policy
×
UNCOV
1689
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
UNCOV
1690

×
UNCOV
1691
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1692
                // signalling support for taproot channels.
×
UNCOV
1693
                taprootPolicy := policy
×
UNCOV
1694
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1695
                        blob.FlagTaprootChannel,
×
UNCOV
1696
                )
×
UNCOV
1697

×
UNCOV
1698
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1699
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1700
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1701
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1702
                        ChainNotifier:          s.cc.ChainNotifier,
×
UNCOV
1703
                        SubscribeChannelEvents: func() (subscribe.Subscription,
×
UNCOV
1704
                                error) {
×
UNCOV
1705

×
UNCOV
1706
                                return s.channelNotifier.
×
UNCOV
1707
                                        SubscribeChannelEvents()
×
UNCOV
1708
                        },
×
1709
                        Signer: cc.Wallet.Cfg.Signer,
UNCOV
1710
                        NewAddress: func() ([]byte, error) {
×
UNCOV
1711
                                addr, err := newSweepPkScriptGen(
×
UNCOV
1712
                                        cc.Wallet, netParams,
×
UNCOV
1713
                                )().Unpack()
×
UNCOV
1714
                                if err != nil {
×
1715
                                        return nil, err
×
1716
                                }
×
1717

UNCOV
1718
                                return addr.DeliveryAddress, nil
×
1719
                        },
1720
                        SecretKeyRing:      s.cc.KeyRing,
1721
                        Dial:               cfg.net.Dial,
1722
                        AuthDial:           authDial,
1723
                        DB:                 dbs.TowerClientDB,
1724
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1725
                        MinBackoff:         10 * time.Second,
1726
                        MaxBackoff:         5 * time.Minute,
1727
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1728
                }, policy, anchorPolicy, taprootPolicy)
UNCOV
1729
                if err != nil {
×
1730
                        return nil, err
×
1731
                }
×
1732
        }
1733

UNCOV
1734
        if len(cfg.ExternalHosts) != 0 {
×
1735
                advertisedIPs := make(map[string]struct{})
×
1736
                for _, addr := range s.currentNodeAnn.Addresses {
×
1737
                        advertisedIPs[addr.String()] = struct{}{}
×
1738
                }
×
1739

1740
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1741
                        Hosts:         cfg.ExternalHosts,
×
1742
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1743
                        LookupHost: func(host string) (net.Addr, error) {
×
1744
                                return lncfg.ParseAddressString(
×
1745
                                        host, strconv.Itoa(defaultPeerPort),
×
1746
                                        cfg.net.ResolveTCPAddr,
×
1747
                                )
×
1748
                        },
×
1749
                        AdvertisedIPs: advertisedIPs,
1750
                        AnnounceNewIPs: netann.IPAnnouncer(
1751
                                func(modifier ...netann.NodeAnnModifier) (
1752
                                        lnwire.NodeAnnouncement, error) {
×
1753

×
1754
                                        return s.genNodeAnnouncement(
×
1755
                                                nil, modifier...,
×
1756
                                        )
×
1757
                                }),
×
1758
                })
1759
        }
1760

1761
        // Create liveness monitor.
UNCOV
1762
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
UNCOV
1763

×
UNCOV
1764
        // Create the connection manager which will be responsible for
×
UNCOV
1765
        // maintaining persistent outbound connections and also accepting new
×
UNCOV
1766
        // incoming connections
×
UNCOV
1767
        cmgr, err := connmgr.New(&connmgr.Config{
×
UNCOV
1768
                Listeners:      listeners,
×
UNCOV
1769
                OnAccept:       s.InboundPeerConnected,
×
UNCOV
1770
                RetryDuration:  time.Second * 5,
×
UNCOV
1771
                TargetOutbound: 100,
×
UNCOV
1772
                Dial: noiseDial(
×
UNCOV
1773
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
×
UNCOV
1774
                ),
×
UNCOV
1775
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1776
        })
×
UNCOV
1777
        if err != nil {
×
1778
                return nil, err
×
1779
        }
×
UNCOV
1780
        s.connMgr = cmgr
×
UNCOV
1781

×
UNCOV
1782
        return s, nil
×
1783
}
1784

1785
// UpdateRoutingConfig is a callback function to update the routing config
1786
// values in the main cfg.
UNCOV
1787
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1788
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1789

×
UNCOV
1790
        switch c := cfg.Estimator.Config().(type) {
×
UNCOV
1791
        case routing.AprioriConfig:
×
UNCOV
1792
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1793
                        routing.AprioriEstimatorName
×
UNCOV
1794

×
UNCOV
1795
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1796
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1797
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1798
                targetCfg.CapacityFraction = c.CapacityFraction
×
UNCOV
1799
                targetCfg.HopProbability = c.AprioriHopProbability
×
1800

UNCOV
1801
        case routing.BimodalConfig:
×
UNCOV
1802
                routerCfg.ProbabilityEstimatorType =
×
UNCOV
1803
                        routing.BimodalEstimatorName
×
UNCOV
1804

×
UNCOV
1805
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1806
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1807
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1808
                targetCfg.DecayTime = c.BimodalDecayTime
×
1809
        }
1810

UNCOV
1811
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
1812
}
1813

1814
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1815
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1816
// may differ from what is on disk.
1817
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
UNCOV
1818
        error) {
×
UNCOV
1819

×
UNCOV
1820
        data, err := u.DataToSign()
×
UNCOV
1821
        if err != nil {
×
1822
                return nil, err
×
1823
        }
×
1824

UNCOV
1825
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
×
1826
}
1827

1828
// createLivenessMonitor creates a set of health checks using our configured
1829
// values and uses these checks to create a liveness monitor. Available
1830
// health checks,
1831
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1832
//   - diskCheck
1833
//   - tlsHealthCheck
1834
//   - torController, only created when tor is enabled.
1835
//
1836
// If a health check has been disabled by setting attempts to 0, our monitor
1837
// will not run it.
1838
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
UNCOV
1839
        leaderElector cluster.LeaderElector) {
×
UNCOV
1840

×
UNCOV
1841
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
×
UNCOV
1842
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1843
                srvrLog.Info("Disabling chain backend checks for " +
×
1844
                        "nochainbackend mode")
×
1845

×
1846
                chainBackendAttempts = 0
×
1847
        }
×
1848

UNCOV
1849
        chainHealthCheck := healthcheck.NewObservation(
×
UNCOV
1850
                "chain backend",
×
UNCOV
1851
                cc.HealthCheck,
×
UNCOV
1852
                cfg.HealthChecks.ChainCheck.Interval,
×
UNCOV
1853
                cfg.HealthChecks.ChainCheck.Timeout,
×
UNCOV
1854
                cfg.HealthChecks.ChainCheck.Backoff,
×
UNCOV
1855
                chainBackendAttempts,
×
UNCOV
1856
        )
×
UNCOV
1857

×
UNCOV
1858
        diskCheck := healthcheck.NewObservation(
×
UNCOV
1859
                "disk space",
×
UNCOV
1860
                func() error {
×
1861
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1862
                                cfg.LndDir,
×
1863
                        )
×
1864
                        if err != nil {
×
1865
                                return err
×
1866
                        }
×
1867

1868
                        // If we have more free space than we require,
1869
                        // we return a nil error.
1870
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1871
                                return nil
×
1872
                        }
×
1873

1874
                        return fmt.Errorf("require: %v free space, got: %v",
×
1875
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1876
                                free)
×
1877
                },
1878
                cfg.HealthChecks.DiskCheck.Interval,
1879
                cfg.HealthChecks.DiskCheck.Timeout,
1880
                cfg.HealthChecks.DiskCheck.Backoff,
1881
                cfg.HealthChecks.DiskCheck.Attempts,
1882
        )
1883

UNCOV
1884
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
1885
                "tls",
×
UNCOV
1886
                func() error {
×
1887
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1888
                                s.cc.KeyRing,
×
1889
                        )
×
1890
                        if err != nil {
×
1891
                                return err
×
1892
                        }
×
1893
                        if expired {
×
1894
                                return fmt.Errorf("TLS certificate is "+
×
1895
                                        "expired as of %v", expTime)
×
1896
                        }
×
1897

1898
                        // If the certificate is not outdated, no error needs
1899
                        // to be returned
1900
                        return nil
×
1901
                },
1902
                cfg.HealthChecks.TLSCheck.Interval,
1903
                cfg.HealthChecks.TLSCheck.Timeout,
1904
                cfg.HealthChecks.TLSCheck.Backoff,
1905
                cfg.HealthChecks.TLSCheck.Attempts,
1906
        )
1907

UNCOV
1908
        checks := []*healthcheck.Observation{
×
UNCOV
1909
                chainHealthCheck, diskCheck, tlsHealthCheck,
×
UNCOV
1910
        }
×
UNCOV
1911

×
UNCOV
1912
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
1913
        if s.torController != nil {
×
1914
                torConnectionCheck := healthcheck.NewObservation(
×
1915
                        "tor connection",
×
1916
                        func() error {
×
1917
                                return healthcheck.CheckTorServiceStatus(
×
1918
                                        s.torController,
×
1919
                                        s.createNewHiddenService,
×
1920
                                )
×
1921
                        },
×
1922
                        cfg.HealthChecks.TorConnection.Interval,
1923
                        cfg.HealthChecks.TorConnection.Timeout,
1924
                        cfg.HealthChecks.TorConnection.Backoff,
1925
                        cfg.HealthChecks.TorConnection.Attempts,
1926
                )
1927
                checks = append(checks, torConnectionCheck)
×
1928
        }
1929

1930
        // If remote signing is enabled, add the healthcheck for the remote
1931
        // signing RPC interface.
UNCOV
1932
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
1933
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
1934
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
1935
                // returns exactly on time.
×
UNCOV
1936
                overhead := time.Millisecond * 10
×
UNCOV
1937

×
UNCOV
1938
                remoteSignerConnectionCheck := healthcheck.NewObservation(
×
UNCOV
1939
                        "remote signer connection",
×
UNCOV
1940
                        rpcwallet.HealthCheck(
×
UNCOV
1941
                                s.cfg.RemoteSigner,
×
UNCOV
1942

×
UNCOV
1943
                                // For the health check we might to be even
×
UNCOV
1944
                                // stricter than the initial/normal connect, so
×
UNCOV
1945
                                // we use the health check timeout here.
×
UNCOV
1946
                                cfg.HealthChecks.RemoteSigner.Timeout,
×
UNCOV
1947
                        ),
×
UNCOV
1948
                        cfg.HealthChecks.RemoteSigner.Interval,
×
UNCOV
1949
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
1950
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
1951
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
1952
                )
×
UNCOV
1953
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
1954
        }
×
1955

1956
        // If we have a leader elector, we add a health check to ensure we are
1957
        // still the leader. During normal operation, we should always be the
1958
        // leader, but there are circumstances where this may change, such as
1959
        // when we lose network connectivity for long enough expiring out lease.
UNCOV
1960
        if leaderElector != nil {
×
1961
                leaderCheck := healthcheck.NewObservation(
×
1962
                        "leader status",
×
1963
                        func() error {
×
1964
                                // Check if we are still the leader. Note that
×
1965
                                // we don't need to use a timeout context here
×
1966
                                // as the healthcheck observer will handle the
×
1967
                                // timeout case for us.
×
1968
                                timeoutCtx, cancel := context.WithTimeout(
×
1969
                                        context.Background(),
×
1970
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
1971
                                )
×
1972
                                defer cancel()
×
1973

×
1974
                                leader, err := leaderElector.IsLeader(
×
1975
                                        timeoutCtx,
×
1976
                                )
×
1977
                                if err != nil {
×
1978
                                        return fmt.Errorf("unable to check if "+
×
1979
                                                "still leader: %v", err)
×
1980
                                }
×
1981

1982
                                if !leader {
×
1983
                                        srvrLog.Debug("Not the current leader")
×
1984
                                        return fmt.Errorf("not the current " +
×
1985
                                                "leader")
×
1986
                                }
×
1987

1988
                                return nil
×
1989
                        },
1990
                        cfg.HealthChecks.LeaderCheck.Interval,
1991
                        cfg.HealthChecks.LeaderCheck.Timeout,
1992
                        cfg.HealthChecks.LeaderCheck.Backoff,
1993
                        cfg.HealthChecks.LeaderCheck.Attempts,
1994
                )
1995

1996
                checks = append(checks, leaderCheck)
×
1997
        }
1998

1999
        // If we have not disabled all of our health checks, we create a
2000
        // liveness monitor with our configured checks.
UNCOV
2001
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
2002
                &healthcheck.Config{
×
UNCOV
2003
                        Checks:   checks,
×
UNCOV
2004
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
2005
                },
×
UNCOV
2006
        )
×
2007
}
2008

2009
// Started returns true if the server has been started, and false otherwise.
2010
// NOTE: This function is safe for concurrent access.
UNCOV
2011
func (s *server) Started() bool {
×
UNCOV
2012
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
2013
}
×
2014

2015
// cleaner is used to aggregate "cleanup" functions during an operation that
2016
// starts several subsystems. In case one of the subsystem fails to start
2017
// and a proper resource cleanup is required, the "run" method achieves this
2018
// by running all these added "cleanup" functions.
2019
type cleaner []func() error
2020

2021
// add is used to add a cleanup function to be called when
2022
// the run function is executed.
UNCOV
2023
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
2024
        return append(c, cleanup)
×
UNCOV
2025
}
×
2026

2027
// run is used to run all the previousely added cleanup functions.
2028
func (c cleaner) run() {
×
2029
        for i := len(c) - 1; i >= 0; i-- {
×
2030
                if err := c[i](); err != nil {
×
2031
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2032
                }
×
2033
        }
2034
}
2035

2036
// Start starts the main daemon server, all requested listeners, and any helper
2037
// goroutines.
2038
// NOTE: This function is safe for concurrent access.
2039
//
2040
//nolint:funlen
UNCOV
2041
func (s *server) Start() error {
×
UNCOV
2042
        var startErr error
×
UNCOV
2043

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

×
UNCOV
2049
        s.start.Do(func() {
×
UNCOV
2050
                cleanup = cleanup.add(s.customMessageServer.Stop)
×
UNCOV
2051
                if err := s.customMessageServer.Start(); err != nil {
×
2052
                        startErr = err
×
2053
                        return
×
2054
                }
×
2055

UNCOV
2056
                if s.hostAnn != nil {
×
2057
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2058
                        if err := s.hostAnn.Start(); err != nil {
×
2059
                                startErr = err
×
2060
                                return
×
2061
                        }
×
2062
                }
2063

UNCOV
2064
                if s.livenessMonitor != nil {
×
UNCOV
2065
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
UNCOV
2066
                        if err := s.livenessMonitor.Start(); err != nil {
×
2067
                                startErr = err
×
2068
                                return
×
2069
                        }
×
2070
                }
2071

2072
                // Start the notification server. This is used so channel
2073
                // management goroutines can be notified when a funding
2074
                // transaction reaches a sufficient number of confirmations, or
2075
                // when the input for the funding transaction is spent in an
2076
                // attempt at an uncooperative close by the counterparty.
UNCOV
2077
                cleanup = cleanup.add(s.sigPool.Stop)
×
UNCOV
2078
                if err := s.sigPool.Start(); err != nil {
×
2079
                        startErr = err
×
2080
                        return
×
2081
                }
×
2082

UNCOV
2083
                cleanup = cleanup.add(s.writePool.Stop)
×
UNCOV
2084
                if err := s.writePool.Start(); err != nil {
×
2085
                        startErr = err
×
2086
                        return
×
2087
                }
×
2088

UNCOV
2089
                cleanup = cleanup.add(s.readPool.Stop)
×
UNCOV
2090
                if err := s.readPool.Start(); err != nil {
×
2091
                        startErr = err
×
2092
                        return
×
2093
                }
×
2094

UNCOV
2095
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
UNCOV
2096
                if err := s.cc.ChainNotifier.Start(); err != nil {
×
2097
                        startErr = err
×
2098
                        return
×
2099
                }
×
2100

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

UNCOV
2107
                cleanup = cleanup.add(s.channelNotifier.Stop)
×
UNCOV
2108
                if err := s.channelNotifier.Start(); err != nil {
×
2109
                        startErr = err
×
2110
                        return
×
2111
                }
×
2112

UNCOV
2113
                cleanup = cleanup.add(func() error {
×
2114
                        return s.peerNotifier.Stop()
×
2115
                })
×
UNCOV
2116
                if err := s.peerNotifier.Start(); err != nil {
×
2117
                        startErr = err
×
2118
                        return
×
2119
                }
×
2120

UNCOV
2121
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2122
                if err := s.htlcNotifier.Start(); err != nil {
×
2123
                        startErr = err
×
2124
                        return
×
2125
                }
×
2126

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

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

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

UNCOV
2147
                cleanup = cleanup.add(s.utxoNursery.Stop)
×
UNCOV
2148
                if err := s.utxoNursery.Start(); err != nil {
×
2149
                        startErr = err
×
2150
                        return
×
2151
                }
×
2152

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

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

2165
                // htlcSwitch must be started before chainArb since the latter
2166
                // relies on htlcSwitch to deliver resolution message upon
2167
                // start.
UNCOV
2168
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2169
                if err := s.htlcSwitch.Start(); err != nil {
×
2170
                        startErr = err
×
2171
                        return
×
2172
                }
×
2173

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

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

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

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

UNCOV
2198
                cleanup = cleanup.add(s.chanRouter.Stop)
×
UNCOV
2199
                if err := s.chanRouter.Start(); err != nil {
×
2200
                        startErr = err
×
2201
                        return
×
2202
                }
×
2203
                // The authGossiper depends on the chanRouter and therefore
2204
                // should be started after it.
UNCOV
2205
                cleanup = cleanup.add(s.authGossiper.Stop)
×
UNCOV
2206
                if err := s.authGossiper.Start(); err != nil {
×
2207
                        startErr = err
×
2208
                        return
×
2209
                }
×
2210

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

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

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

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

UNCOV
2235
                cleanup.add(func() error {
×
2236
                        s.missionController.StopStoreTickers()
×
2237
                        return nil
×
2238
                })
×
UNCOV
2239
                s.missionController.RunStoreTickers()
×
UNCOV
2240

×
UNCOV
2241
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2242
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2243
                // that have all the information we need to handle channel
×
UNCOV
2244
                // recovery _before_ we even accept connections from any peers.
×
UNCOV
2245
                chanRestorer := &chanDBRestorer{
×
UNCOV
2246
                        db:         s.chanStateDB,
×
UNCOV
2247
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2248
                        chainArb:   s.chainArb,
×
UNCOV
2249
                }
×
UNCOV
2250
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2251
                        err := chanbackup.UnpackAndRecoverSingles(
×
2252
                                s.chansToRestore.PackedSingleChanBackups,
×
2253
                                s.cc.KeyRing, chanRestorer, s,
×
2254
                        )
×
2255
                        if err != nil {
×
2256
                                startErr = fmt.Errorf("unable to unpack single "+
×
2257
                                        "backups: %v", err)
×
2258
                                return
×
2259
                        }
×
2260
                }
UNCOV
2261
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2262
                        err := chanbackup.UnpackAndRecoverMulti(
×
UNCOV
2263
                                s.chansToRestore.PackedMultiChanBackup,
×
UNCOV
2264
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2265
                        )
×
UNCOV
2266
                        if err != nil {
×
2267
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2268
                                        "backup: %v", err)
×
2269
                                return
×
2270
                        }
×
2271
                }
2272

2273
                // chanSubSwapper must be started after the `channelNotifier`
2274
                // because it depends on channel events as a synchronization
2275
                // point.
UNCOV
2276
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2277
                if err := s.chanSubSwapper.Start(); err != nil {
×
2278
                        startErr = err
×
2279
                        return
×
2280
                }
×
2281

UNCOV
2282
                if s.torController != nil {
×
2283
                        cleanup = cleanup.add(s.torController.Stop)
×
2284
                        if err := s.createNewHiddenService(); err != nil {
×
2285
                                startErr = err
×
2286
                                return
×
2287
                        }
×
2288
                }
2289

UNCOV
2290
                if s.natTraversal != nil {
×
2291
                        s.wg.Add(1)
×
2292
                        go s.watchExternalIP()
×
2293
                }
×
2294

2295
                // Start connmgr last to prevent connections before init.
UNCOV
2296
                cleanup = cleanup.add(func() error {
×
2297
                        s.connMgr.Stop()
×
2298
                        return nil
×
2299
                })
×
UNCOV
2300
                s.connMgr.Start()
×
UNCOV
2301

×
UNCOV
2302
                // If peers are specified as a config option, we'll add those
×
UNCOV
2303
                // peers first.
×
UNCOV
2304
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2305
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2306
                                peerAddrCfg,
×
UNCOV
2307
                        )
×
UNCOV
2308
                        if err != nil {
×
2309
                                startErr = fmt.Errorf("unable to parse peer "+
×
2310
                                        "pubkey from config: %v", err)
×
2311
                                return
×
2312
                        }
×
UNCOV
2313
                        addr, err := parseAddr(parsedHost, s.cfg.net)
×
UNCOV
2314
                        if err != nil {
×
2315
                                startErr = fmt.Errorf("unable to parse peer "+
×
2316
                                        "address provided as a config option: "+
×
2317
                                        "%v", err)
×
2318
                                return
×
2319
                        }
×
2320

UNCOV
2321
                        peerAddr := &lnwire.NetAddress{
×
UNCOV
2322
                                IdentityKey: parsedPubkey,
×
UNCOV
2323
                                Address:     addr,
×
UNCOV
2324
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2325
                        }
×
UNCOV
2326

×
UNCOV
2327
                        err = s.ConnectToPeer(
×
UNCOV
2328
                                peerAddr, true,
×
UNCOV
2329
                                s.cfg.ConnectionTimeout,
×
UNCOV
2330
                        )
×
UNCOV
2331
                        if err != nil {
×
2332
                                startErr = fmt.Errorf("unable to connect to "+
×
2333
                                        "peer address provided as a config "+
×
2334
                                        "option: %v", err)
×
2335
                                return
×
2336
                        }
×
2337
                }
2338

2339
                // Subscribe to NodeAnnouncements that advertise new addresses
2340
                // our persistent peers.
UNCOV
2341
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2342
                        startErr = err
×
2343
                        return
×
2344
                }
×
2345

2346
                // With all the relevant sub-systems started, we'll now attempt
2347
                // to establish persistent connections to our direct channel
2348
                // collaborators within the network. Before doing so however,
2349
                // we'll prune our set of link nodes found within the database
2350
                // to ensure we don't reconnect to any nodes we no longer have
2351
                // open channels with.
UNCOV
2352
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2353
                        startErr = err
×
2354
                        return
×
2355
                }
×
UNCOV
2356
                if err := s.establishPersistentConnections(); err != nil {
×
2357
                        startErr = err
×
2358
                        return
×
2359
                }
×
2360

2361
                // setSeedList is a helper function that turns multiple DNS seed
2362
                // server tuples from the command line or config file into the
2363
                // data structure we need and does a basic formal sanity check
2364
                // in the process.
UNCOV
2365
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2366
                        if len(tuples) == 0 {
×
2367
                                return
×
2368
                        }
×
2369

2370
                        result := make([][2]string, len(tuples))
×
2371
                        for idx, tuple := range tuples {
×
2372
                                tuple = strings.TrimSpace(tuple)
×
2373
                                if len(tuple) == 0 {
×
2374
                                        return
×
2375
                                }
×
2376

2377
                                servers := strings.Split(tuple, ",")
×
2378
                                if len(servers) > 2 || len(servers) == 0 {
×
2379
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2380
                                                "seed tuple: %v", servers)
×
2381
                                        return
×
2382
                                }
×
2383

2384
                                copy(result[idx][:], servers)
×
2385
                        }
2386

2387
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2388
                }
2389

2390
                // Let users overwrite the DNS seed nodes. We only allow them
2391
                // for bitcoin mainnet/testnet/signet.
UNCOV
2392
                if s.cfg.Bitcoin.MainNet {
×
2393
                        setSeedList(
×
2394
                                s.cfg.Bitcoin.DNSSeeds,
×
2395
                                chainreg.BitcoinMainnetGenesis,
×
2396
                        )
×
2397
                }
×
UNCOV
2398
                if s.cfg.Bitcoin.TestNet3 {
×
2399
                        setSeedList(
×
2400
                                s.cfg.Bitcoin.DNSSeeds,
×
2401
                                chainreg.BitcoinTestnetGenesis,
×
2402
                        )
×
2403
                }
×
UNCOV
2404
                if s.cfg.Bitcoin.SigNet {
×
2405
                        setSeedList(
×
2406
                                s.cfg.Bitcoin.DNSSeeds,
×
2407
                                chainreg.BitcoinSignetGenesis,
×
2408
                        )
×
2409
                }
×
2410

2411
                // If network bootstrapping hasn't been disabled, then we'll
2412
                // configure the set of active bootstrappers, and launch a
2413
                // dedicated goroutine to maintain a set of persistent
2414
                // connections.
UNCOV
2415
                if shouldPeerBootstrap(s.cfg) {
×
2416
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2417
                        if err != nil {
×
2418
                                startErr = err
×
2419
                                return
×
2420
                        }
×
2421

2422
                        s.wg.Add(1)
×
2423
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
UNCOV
2424
                } else {
×
UNCOV
2425
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
UNCOV
2426
                }
×
2427

2428
                // Set the active flag now that we've completed the full
2429
                // startup.
UNCOV
2430
                atomic.StoreInt32(&s.active, 1)
×
2431
        })
2432

UNCOV
2433
        if startErr != nil {
×
2434
                cleanup.run()
×
2435
        }
×
UNCOV
2436
        return startErr
×
2437
}
2438

2439
// Stop gracefully shutsdown the main daemon server. This function will signal
2440
// any active goroutines, or helper objects to exit, then blocks until they've
2441
// all successfully exited. Additionally, any/all listeners are closed.
2442
// NOTE: This function is safe for concurrent access.
UNCOV
2443
func (s *server) Stop() error {
×
UNCOV
2444
        s.stop.Do(func() {
×
UNCOV
2445
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2446

×
UNCOV
2447
                close(s.quit)
×
UNCOV
2448

×
UNCOV
2449
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2450
                s.connMgr.Stop()
×
UNCOV
2451

×
UNCOV
2452
                // Shutdown the wallet, funding manager, and the rpc server.
×
UNCOV
2453
                if err := s.chanStatusMgr.Stop(); err != nil {
×
2454
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2455
                }
×
UNCOV
2456
                if err := s.htlcSwitch.Stop(); err != nil {
×
2457
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2458
                }
×
UNCOV
2459
                if err := s.sphinx.Stop(); err != nil {
×
2460
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2461
                }
×
UNCOV
2462
                if err := s.invoices.Stop(); err != nil {
×
2463
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2464
                }
×
UNCOV
2465
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2466
                        srvrLog.Warnf("failed to stop interceptable "+
×
2467
                                "switch: %v", err)
×
2468
                }
×
UNCOV
2469
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
×
2470
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2471
                                "modifier: %v", err)
×
2472
                }
×
UNCOV
2473
                if err := s.chanRouter.Stop(); err != nil {
×
2474
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2475
                }
×
UNCOV
2476
                if err := s.chainArb.Stop(); err != nil {
×
2477
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2478
                }
×
UNCOV
2479
                if err := s.fundingMgr.Stop(); err != nil {
×
2480
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2481
                }
×
UNCOV
2482
                if err := s.breachArbitrator.Stop(); err != nil {
×
2483
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2484
                                err)
×
2485
                }
×
UNCOV
2486
                if err := s.utxoNursery.Stop(); err != nil {
×
2487
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2488
                }
×
UNCOV
2489
                if err := s.authGossiper.Stop(); err != nil {
×
2490
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2491
                }
×
UNCOV
2492
                if err := s.sweeper.Stop(); err != nil {
×
2493
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2494
                }
×
UNCOV
2495
                if err := s.txPublisher.Stop(); err != nil {
×
2496
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2497
                }
×
UNCOV
2498
                if err := s.channelNotifier.Stop(); err != nil {
×
2499
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2500
                }
×
UNCOV
2501
                if err := s.peerNotifier.Stop(); err != nil {
×
2502
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2503
                }
×
UNCOV
2504
                if err := s.htlcNotifier.Stop(); err != nil {
×
2505
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2506
                }
×
2507

2508
                // Update channel.backup file. Make sure to do it before
2509
                // stopping chanSubSwapper.
UNCOV
2510
                singles, err := chanbackup.FetchStaticChanBackups(
×
UNCOV
2511
                        s.chanStateDB, s.addrSource,
×
UNCOV
2512
                )
×
UNCOV
2513
                if err != nil {
×
2514
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2515
                                err)
×
UNCOV
2516
                } else {
×
UNCOV
2517
                        err := s.chanSubSwapper.ManualUpdate(singles)
×
UNCOV
2518
                        if err != nil {
×
UNCOV
2519
                                srvrLog.Warnf("Manual update of channel "+
×
UNCOV
2520
                                        "backup failed: %v", err)
×
UNCOV
2521
                        }
×
2522
                }
2523

UNCOV
2524
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2525
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2526
                }
×
UNCOV
2527
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2528
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2529
                }
×
UNCOV
2530
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2531
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2532
                                err)
×
2533
                }
×
UNCOV
2534
                if err := s.chanEventStore.Stop(); err != nil {
×
2535
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2536
                                err)
×
2537
                }
×
UNCOV
2538
                s.missionController.StopStoreTickers()
×
UNCOV
2539

×
UNCOV
2540
                // Disconnect from each active peers to ensure that
×
UNCOV
2541
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2542
                for _, peer := range s.Peers() {
×
UNCOV
2543
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2544
                        if err != nil {
×
2545
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2546
                                        "received error: %v", peer.IdentityKey(),
×
2547
                                        err,
×
2548
                                )
×
2549
                        }
×
2550
                }
2551

2552
                // Now that all connections have been torn down, stop the tower
2553
                // client which will reliably flush all queued states to the
2554
                // tower. If this is halted for any reason, the force quit timer
2555
                // will kick in and abort to allow this method to return.
UNCOV
2556
                if s.towerClientMgr != nil {
×
UNCOV
2557
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2558
                                srvrLog.Warnf("Unable to shut down tower "+
×
2559
                                        "client manager: %v", err)
×
2560
                        }
×
2561
                }
2562

UNCOV
2563
                if s.hostAnn != nil {
×
2564
                        if err := s.hostAnn.Stop(); err != nil {
×
2565
                                srvrLog.Warnf("unable to shut down host "+
×
2566
                                        "annoucner: %v", err)
×
2567
                        }
×
2568
                }
2569

UNCOV
2570
                if s.livenessMonitor != nil {
×
UNCOV
2571
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2572
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2573
                                        "monitor: %v", err)
×
2574
                        }
×
2575
                }
2576

2577
                // Wait for all lingering goroutines to quit.
UNCOV
2578
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2579
                s.wg.Wait()
×
UNCOV
2580

×
UNCOV
2581
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2582
                s.sigPool.Stop()
×
UNCOV
2583
                s.writePool.Stop()
×
UNCOV
2584
                s.readPool.Stop()
×
2585
        })
2586

UNCOV
2587
        return nil
×
2588
}
2589

2590
// Stopped returns true if the server has been instructed to shutdown.
2591
// NOTE: This function is safe for concurrent access.
UNCOV
2592
func (s *server) Stopped() bool {
×
UNCOV
2593
        return atomic.LoadInt32(&s.stopping) != 0
×
UNCOV
2594
}
×
2595

2596
// configurePortForwarding attempts to set up port forwarding for the different
2597
// ports that the server will be listening on.
2598
//
2599
// NOTE: This should only be used when using some kind of NAT traversal to
2600
// automatically set up forwarding rules.
2601
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2602
        ip, err := s.natTraversal.ExternalIP()
×
2603
        if err != nil {
×
2604
                return nil, err
×
2605
        }
×
2606
        s.lastDetectedIP = ip
×
2607

×
2608
        externalIPs := make([]string, 0, len(ports))
×
2609
        for _, port := range ports {
×
2610
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2611
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2612
                        continue
×
2613
                }
2614

2615
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2616
                externalIPs = append(externalIPs, hostIP)
×
2617
        }
2618

2619
        return externalIPs, nil
×
2620
}
2621

2622
// removePortForwarding attempts to clear the forwarding rules for the different
2623
// ports the server is currently listening on.
2624
//
2625
// NOTE: This should only be used when using some kind of NAT traversal to
2626
// automatically set up forwarding rules.
2627
func (s *server) removePortForwarding() {
×
2628
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2629
        for _, port := range forwardedPorts {
×
2630
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2631
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2632
                                "port %d: %v", port, err)
×
2633
                }
×
2634
        }
2635
}
2636

2637
// watchExternalIP continuously checks for an updated external IP address every
2638
// 15 minutes. Once a new IP address has been detected, it will automatically
2639
// handle port forwarding rules and send updated node announcements to the
2640
// currently connected peers.
2641
//
2642
// NOTE: This MUST be run as a goroutine.
2643
func (s *server) watchExternalIP() {
×
2644
        defer s.wg.Done()
×
2645

×
2646
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2647
        // up by the server.
×
2648
        defer s.removePortForwarding()
×
2649

×
2650
        // Keep track of the external IPs set by the user to avoid replacing
×
2651
        // them when detecting a new IP.
×
2652
        ipsSetByUser := make(map[string]struct{})
×
2653
        for _, ip := range s.cfg.ExternalIPs {
×
2654
                ipsSetByUser[ip.String()] = struct{}{}
×
2655
        }
×
2656

2657
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2658

×
2659
        ticker := time.NewTicker(15 * time.Minute)
×
2660
        defer ticker.Stop()
×
2661
out:
×
2662
        for {
×
2663
                select {
×
2664
                case <-ticker.C:
×
2665
                        // We'll start off by making sure a new IP address has
×
2666
                        // been detected.
×
2667
                        ip, err := s.natTraversal.ExternalIP()
×
2668
                        if err != nil {
×
2669
                                srvrLog.Debugf("Unable to retrieve the "+
×
2670
                                        "external IP address: %v", err)
×
2671
                                continue
×
2672
                        }
2673

2674
                        // Periodically renew the NAT port forwarding.
2675
                        for _, port := range forwardedPorts {
×
2676
                                err := s.natTraversal.AddPortMapping(port)
×
2677
                                if err != nil {
×
2678
                                        srvrLog.Warnf("Unable to automatically "+
×
2679
                                                "re-create port forwarding using %s: %v",
×
2680
                                                s.natTraversal.Name(), err)
×
2681
                                } else {
×
2682
                                        srvrLog.Debugf("Automatically re-created "+
×
2683
                                                "forwarding for port %d using %s to "+
×
2684
                                                "advertise external IP",
×
2685
                                                port, s.natTraversal.Name())
×
2686
                                }
×
2687
                        }
2688

2689
                        if ip.Equal(s.lastDetectedIP) {
×
2690
                                continue
×
2691
                        }
2692

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

×
2695
                        // Next, we'll craft the new addresses that will be
×
2696
                        // included in the new node announcement and advertised
×
2697
                        // to the network. Each address will consist of the new
×
2698
                        // IP detected and one of the currently advertised
×
2699
                        // ports.
×
2700
                        var newAddrs []net.Addr
×
2701
                        for _, port := range forwardedPorts {
×
2702
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2703
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2704
                                if err != nil {
×
2705
                                        srvrLog.Debugf("Unable to resolve "+
×
2706
                                                "host %v: %v", addr, err)
×
2707
                                        continue
×
2708
                                }
2709

2710
                                newAddrs = append(newAddrs, addr)
×
2711
                        }
2712

2713
                        // Skip the update if we weren't able to resolve any of
2714
                        // the new addresses.
2715
                        if len(newAddrs) == 0 {
×
2716
                                srvrLog.Debug("Skipping node announcement " +
×
2717
                                        "update due to not being able to " +
×
2718
                                        "resolve any new addresses")
×
2719
                                continue
×
2720
                        }
2721

2722
                        // Now, we'll need to update the addresses in our node's
2723
                        // announcement in order to propagate the update
2724
                        // throughout the network. We'll only include addresses
2725
                        // that have a different IP from the previous one, as
2726
                        // the previous IP is no longer valid.
2727
                        currentNodeAnn := s.getNodeAnnouncement()
×
2728

×
2729
                        for _, addr := range currentNodeAnn.Addresses {
×
2730
                                host, _, err := net.SplitHostPort(addr.String())
×
2731
                                if err != nil {
×
2732
                                        srvrLog.Debugf("Unable to determine "+
×
2733
                                                "host from address %v: %v",
×
2734
                                                addr, err)
×
2735
                                        continue
×
2736
                                }
2737

2738
                                // We'll also make sure to include external IPs
2739
                                // set manually by the user.
2740
                                _, setByUser := ipsSetByUser[addr.String()]
×
2741
                                if setByUser || host != s.lastDetectedIP.String() {
×
2742
                                        newAddrs = append(newAddrs, addr)
×
2743
                                }
×
2744
                        }
2745

2746
                        // Then, we'll generate a new timestamped node
2747
                        // announcement with the updated addresses and broadcast
2748
                        // it to our peers.
2749
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2750
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2751
                        )
×
2752
                        if err != nil {
×
2753
                                srvrLog.Debugf("Unable to generate new node "+
×
2754
                                        "announcement: %v", err)
×
2755
                                continue
×
2756
                        }
2757

2758
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2759
                        if err != nil {
×
2760
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2761
                                        "announcement to peers: %v", err)
×
2762
                                continue
×
2763
                        }
2764

2765
                        // Finally, update the last IP seen to the current one.
2766
                        s.lastDetectedIP = ip
×
2767
                case <-s.quit:
×
2768
                        break out
×
2769
                }
2770
        }
2771
}
2772

2773
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2774
// based on the server, and currently active bootstrap mechanisms as defined
2775
// within the current configuration.
2776
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2777
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2778

×
2779
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2780

×
2781
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2782
        // this can be used by default if we've already partially seeded the
×
2783
        // network.
×
2784
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2785
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
2786
        if err != nil {
×
2787
                return nil, err
×
2788
        }
×
2789
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
2790

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

×
2796
                // If we have a set of DNS seeds for this chain, then we'll add
×
2797
                // it as an additional bootstrapping source.
×
2798
                if ok {
×
2799
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2800
                                "seeds: %v", dnsSeeds)
×
2801

×
2802
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2803
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2804
                        )
×
2805
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2806
                }
×
2807
        }
2808

2809
        return bootStrappers, nil
×
2810
}
2811

2812
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2813
// needs to ignore, which is made of three parts,
2814
//   - the node itself needs to be skipped as it doesn't make sense to connect
2815
//     to itself.
2816
//   - the peers that already have connections with, as in s.peersByPub.
2817
//   - the peers that we are attempting to connect, as in s.persistentPeers.
2818
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2819
        s.mu.RLock()
×
2820
        defer s.mu.RUnlock()
×
2821

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

×
2824
        // We should ignore ourselves from bootstrapping.
×
2825
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2826
        ignore[selfKey] = struct{}{}
×
2827

×
2828
        // Ignore all connected peers.
×
2829
        for _, peer := range s.peersByPub {
×
2830
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2831
                ignore[nID] = struct{}{}
×
2832
        }
×
2833

2834
        // Ignore all persistent peers as they have a dedicated reconnecting
2835
        // process.
2836
        for pubKeyStr := range s.persistentPeers {
×
2837
                var nID autopilot.NodeID
×
2838
                copy(nID[:], []byte(pubKeyStr))
×
2839
                ignore[nID] = struct{}{}
×
2840
        }
×
2841

2842
        return ignore
×
2843
}
2844

2845
// peerBootstrapper is a goroutine which is tasked with attempting to establish
2846
// and maintain a target minimum number of outbound connections. With this
2847
// invariant, we ensure that our node is connected to a diverse set of peers
2848
// and that nodes newly joining the network receive an up to date network view
2849
// as soon as possible.
2850
func (s *server) peerBootstrapper(numTargetPeers uint32,
2851
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2852

×
2853
        defer s.wg.Done()
×
2854

×
2855
        // Before we continue, init the ignore peers map.
×
2856
        ignoreList := s.createBootstrapIgnorePeers()
×
2857

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

×
2862
        // Once done, we'll attempt to maintain our target minimum number of
×
2863
        // peers.
×
2864
        //
×
2865
        // We'll use a 15 second backoff, and double the time every time an
×
2866
        // epoch fails up to a ceiling.
×
2867
        backOff := time.Second * 15
×
2868

×
2869
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2870
        // see if we've reached our minimum number of peers.
×
2871
        sampleTicker := time.NewTicker(backOff)
×
2872
        defer sampleTicker.Stop()
×
2873

×
2874
        // We'll use the number of attempts and errors to determine if we need
×
2875
        // to increase the time between discovery epochs.
×
2876
        var epochErrors uint32 // To be used atomically.
×
2877
        var epochAttempts uint32
×
2878

×
2879
        for {
×
2880
                select {
×
2881
                // The ticker has just woken us up, so we'll need to check if
2882
                // we need to attempt to connect our to any more peers.
2883
                case <-sampleTicker.C:
×
2884
                        // Obtain the current number of peers, so we can gauge
×
2885
                        // if we need to sample more peers or not.
×
2886
                        s.mu.RLock()
×
2887
                        numActivePeers := uint32(len(s.peersByPub))
×
2888
                        s.mu.RUnlock()
×
2889

×
2890
                        // If we have enough peers, then we can loop back
×
2891
                        // around to the next round as we're done here.
×
2892
                        if numActivePeers >= numTargetPeers {
×
2893
                                continue
×
2894
                        }
2895

2896
                        // If all of our attempts failed during this last back
2897
                        // off period, then will increase our backoff to 5
2898
                        // minute ceiling to avoid an excessive number of
2899
                        // queries
2900
                        //
2901
                        // TODO(roasbeef): add reverse policy too?
2902

2903
                        if epochAttempts > 0 &&
×
2904
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2905

×
2906
                                sampleTicker.Stop()
×
2907

×
2908
                                backOff *= 2
×
2909
                                if backOff > bootstrapBackOffCeiling {
×
2910
                                        backOff = bootstrapBackOffCeiling
×
2911
                                }
×
2912

2913
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2914
                                        "%v", backOff)
×
2915
                                sampleTicker = time.NewTicker(backOff)
×
2916
                                continue
×
2917
                        }
2918

2919
                        atomic.StoreUint32(&epochErrors, 0)
×
2920
                        epochAttempts = 0
×
2921

×
2922
                        // Since we know need more peers, we'll compute the
×
2923
                        // exact number we need to reach our threshold.
×
2924
                        numNeeded := numTargetPeers - numActivePeers
×
2925

×
2926
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2927
                                "peers", numNeeded)
×
2928

×
2929
                        // With the number of peers we need calculated, we'll
×
2930
                        // query the network bootstrappers to sample a set of
×
2931
                        // random addrs for us.
×
2932
                        //
×
2933
                        // Before we continue, get a copy of the ignore peers
×
2934
                        // map.
×
2935
                        ignoreList = s.createBootstrapIgnorePeers()
×
2936

×
2937
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
2938
                                ignoreList, numNeeded*2, bootstrappers...,
×
2939
                        )
×
2940
                        if err != nil {
×
2941
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
2942
                                        "peers: %v", err)
×
2943
                                continue
×
2944
                        }
2945

2946
                        // Finally, we'll launch a new goroutine for each
2947
                        // prospective peer candidates.
2948
                        for _, addr := range peerAddrs {
×
2949
                                epochAttempts++
×
2950

×
2951
                                go func(a *lnwire.NetAddress) {
×
2952
                                        // TODO(roasbeef): can do AS, subnet,
×
2953
                                        // country diversity, etc
×
2954
                                        errChan := make(chan error, 1)
×
2955
                                        s.connectToPeer(
×
2956
                                                a, errChan,
×
2957
                                                s.cfg.ConnectionTimeout,
×
2958
                                        )
×
2959
                                        select {
×
2960
                                        case err := <-errChan:
×
2961
                                                if err == nil {
×
2962
                                                        return
×
2963
                                                }
×
2964

2965
                                                srvrLog.Errorf("Unable to "+
×
2966
                                                        "connect to %v: %v",
×
2967
                                                        a, err)
×
2968
                                                atomic.AddUint32(&epochErrors, 1)
×
2969
                                        case <-s.quit:
×
2970
                                        }
2971
                                }(addr)
2972
                        }
2973
                case <-s.quit:
×
2974
                        return
×
2975
                }
2976
        }
2977
}
2978

2979
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
2980
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
2981
// query back off each time we encounter a failure.
2982
const bootstrapBackOffCeiling = time.Minute * 5
2983

2984
// initialPeerBootstrap attempts to continuously connect to peers on startup
2985
// until the target number of peers has been reached. This ensures that nodes
2986
// receive an up to date network view as soon as possible.
2987
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2988
        numTargetPeers uint32,
2989
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2990

×
2991
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2992
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2993

×
2994
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2995
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2996
        var delaySignal <-chan time.Time
×
2997
        delayTime := time.Second * 2
×
2998

×
2999
        // As want to be more aggressive, we'll use a lower back off celling
×
3000
        // then the main peer bootstrap logic.
×
3001
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3002

×
3003
        for attempts := 0; ; attempts++ {
×
3004
                // Check if the server has been requested to shut down in order
×
3005
                // to prevent blocking.
×
3006
                if s.Stopped() {
×
3007
                        return
×
3008
                }
×
3009

3010
                // We can exit our aggressive initial peer bootstrapping stage
3011
                // if we've reached out target number of peers.
3012
                s.mu.RLock()
×
3013
                numActivePeers := uint32(len(s.peersByPub))
×
3014
                s.mu.RUnlock()
×
3015

×
3016
                if numActivePeers >= numTargetPeers {
×
3017
                        return
×
3018
                }
×
3019

3020
                if attempts > 0 {
×
3021
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3022
                                "bootstrap peers (attempt #%v)", delayTime,
×
3023
                                attempts)
×
3024

×
3025
                        // We've completed at least one iterating and haven't
×
3026
                        // finished, so we'll start to insert a delay period
×
3027
                        // between each attempt.
×
3028
                        delaySignal = time.After(delayTime)
×
3029
                        select {
×
3030
                        case <-delaySignal:
×
3031
                        case <-s.quit:
×
3032
                                return
×
3033
                        }
3034

3035
                        // After our delay, we'll double the time we wait up to
3036
                        // the max back off period.
3037
                        delayTime *= 2
×
3038
                        if delayTime > backOffCeiling {
×
3039
                                delayTime = backOffCeiling
×
3040
                        }
×
3041
                }
3042

3043
                // Otherwise, we'll request for the remaining number of peers
3044
                // in order to reach our target.
3045
                peersNeeded := numTargetPeers - numActivePeers
×
3046
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3047
                        ignore, peersNeeded, bootstrappers...,
×
3048
                )
×
3049
                if err != nil {
×
3050
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3051
                                "peers: %v", err)
×
3052
                        continue
×
3053
                }
3054

3055
                // Then, we'll attempt to establish a connection to the
3056
                // different peer addresses retrieved by our bootstrappers.
3057
                var wg sync.WaitGroup
×
3058
                for _, bootstrapAddr := range bootstrapAddrs {
×
3059
                        wg.Add(1)
×
3060
                        go func(addr *lnwire.NetAddress) {
×
3061
                                defer wg.Done()
×
3062

×
3063
                                errChan := make(chan error, 1)
×
3064
                                go s.connectToPeer(
×
3065
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3066
                                )
×
3067

×
3068
                                // We'll only allow this connection attempt to
×
3069
                                // take up to 3 seconds. This allows us to move
×
3070
                                // quickly by discarding peers that are slowing
×
3071
                                // us down.
×
3072
                                select {
×
3073
                                case err := <-errChan:
×
3074
                                        if err == nil {
×
3075
                                                return
×
3076
                                        }
×
3077
                                        srvrLog.Errorf("Unable to connect to "+
×
3078
                                                "%v: %v", addr, err)
×
3079
                                // TODO: tune timeout? 3 seconds might be *too*
3080
                                // aggressive but works well.
3081
                                case <-time.After(3 * time.Second):
×
3082
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3083
                                                "to not establishing a "+
×
3084
                                                "connection within 3 seconds",
×
3085
                                                addr)
×
3086
                                case <-s.quit:
×
3087
                                }
3088
                        }(bootstrapAddr)
3089
                }
3090

3091
                wg.Wait()
×
3092
        }
3093
}
3094

3095
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3096
// order to listen for inbound connections over Tor.
3097
func (s *server) createNewHiddenService() error {
×
3098
        // Determine the different ports the server is listening on. The onion
×
3099
        // service's virtual port will map to these ports and one will be picked
×
3100
        // at random when the onion service is being accessed.
×
3101
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3102
        for _, listenAddr := range s.listenAddrs {
×
3103
                port := listenAddr.(*net.TCPAddr).Port
×
3104
                listenPorts = append(listenPorts, port)
×
3105
        }
×
3106

3107
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3108
        if err != nil {
×
3109
                return err
×
3110
        }
×
3111

3112
        // Once the port mapping has been set, we can go ahead and automatically
3113
        // create our onion service. The service's private key will be saved to
3114
        // disk in order to regain access to this service when restarting `lnd`.
3115
        onionCfg := tor.AddOnionConfig{
×
3116
                VirtualPort: defaultPeerPort,
×
3117
                TargetPorts: listenPorts,
×
3118
                Store: tor.NewOnionFile(
×
3119
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3120
                        encrypter,
×
3121
                ),
×
3122
        }
×
3123

×
3124
        switch {
×
3125
        case s.cfg.Tor.V2:
×
3126
                onionCfg.Type = tor.V2
×
3127
        case s.cfg.Tor.V3:
×
3128
                onionCfg.Type = tor.V3
×
3129
        }
3130

3131
        addr, err := s.torController.AddOnion(onionCfg)
×
3132
        if err != nil {
×
3133
                return err
×
3134
        }
×
3135

3136
        // Now that the onion service has been created, we'll add the onion
3137
        // address it can be reached at to our list of advertised addresses.
3138
        newNodeAnn, err := s.genNodeAnnouncement(
×
3139
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3140
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3141
                },
×
3142
        )
3143
        if err != nil {
×
3144
                return fmt.Errorf("unable to generate new node "+
×
3145
                        "announcement: %v", err)
×
3146
        }
×
3147

3148
        // Finally, we'll update the on-disk version of our announcement so it
3149
        // will eventually propagate to nodes in the network.
3150
        selfNode := &channeldb.LightningNode{
×
3151
                HaveNodeAnnouncement: true,
×
3152
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3153
                Addresses:            newNodeAnn.Addresses,
×
3154
                Alias:                newNodeAnn.Alias.String(),
×
3155
                Features: lnwire.NewFeatureVector(
×
3156
                        newNodeAnn.Features, lnwire.Features,
×
3157
                ),
×
3158
                Color:        newNodeAnn.RGBColor,
×
3159
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3160
        }
×
3161
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3162
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3163
                return fmt.Errorf("can't set self node: %w", err)
×
3164
        }
×
3165

3166
        return nil
×
3167
}
3168

3169
// findChannel finds a channel given a public key and ChannelID. It is an
3170
// optimization that is quicker than seeking for a channel given only the
3171
// ChannelID.
3172
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
UNCOV
3173
        *channeldb.OpenChannel, error) {
×
UNCOV
3174

×
UNCOV
3175
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
UNCOV
3176
        if err != nil {
×
3177
                return nil, err
×
3178
        }
×
3179

UNCOV
3180
        for _, channel := range nodeChans {
×
UNCOV
3181
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3182
                        return channel, nil
×
UNCOV
3183
                }
×
3184
        }
3185

UNCOV
3186
        return nil, fmt.Errorf("unable to find channel")
×
3187
}
3188

3189
// getNodeAnnouncement fetches the current, fully signed node announcement.
UNCOV
3190
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
×
UNCOV
3191
        s.mu.Lock()
×
UNCOV
3192
        defer s.mu.Unlock()
×
UNCOV
3193

×
UNCOV
3194
        return *s.currentNodeAnn
×
UNCOV
3195
}
×
3196

3197
// genNodeAnnouncement generates and returns the current fully signed node
3198
// announcement. The time stamp of the announcement will be updated in order
3199
// to ensure it propagates through the network.
3200
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
UNCOV
3201
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3202

×
UNCOV
3203
        s.mu.Lock()
×
UNCOV
3204
        defer s.mu.Unlock()
×
UNCOV
3205

×
UNCOV
3206
        // First, try to update our feature manager with the updated set of
×
UNCOV
3207
        // features.
×
UNCOV
3208
        if features != nil {
×
UNCOV
3209
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
×
UNCOV
3210
                        feature.SetNodeAnn: features,
×
UNCOV
3211
                }
×
UNCOV
3212
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
×
UNCOV
3213
                if err != nil {
×
UNCOV
3214
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3215
                }
×
3216

3217
                // If we could successfully update our feature manager, add
3218
                // an update modifier to include these new features to our
3219
                // set.
UNCOV
3220
                modifiers = append(
×
UNCOV
3221
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3222
                )
×
3223
        }
3224

3225
        // Always update the timestamp when refreshing to ensure the update
3226
        // propagates.
UNCOV
3227
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
UNCOV
3228

×
UNCOV
3229
        // Apply the requested changes to the node announcement.
×
UNCOV
3230
        for _, modifier := range modifiers {
×
UNCOV
3231
                modifier(s.currentNodeAnn)
×
UNCOV
3232
        }
×
3233

3234
        // Sign a new update after applying all of the passed modifiers.
UNCOV
3235
        err := netann.SignNodeAnnouncement(
×
UNCOV
3236
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
UNCOV
3237
        )
×
UNCOV
3238
        if err != nil {
×
3239
                return lnwire.NodeAnnouncement{}, err
×
3240
        }
×
3241

UNCOV
3242
        return *s.currentNodeAnn, nil
×
3243
}
3244

3245
// updateAndBrodcastSelfNode generates a new node announcement
3246
// applying the giving modifiers and updating the time stamp
3247
// to ensure it propagates through the network. Then it brodcasts
3248
// it to the network.
3249
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
UNCOV
3250
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3251

×
UNCOV
3252
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3253
        if err != nil {
×
UNCOV
3254
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3255
                        "announcement: %v", err)
×
UNCOV
3256
        }
×
3257

3258
        // Update the on-disk version of our announcement.
3259
        // Load and modify self node istead of creating anew instance so we
3260
        // don't risk overwriting any existing values.
UNCOV
3261
        selfNode, err := s.graphDB.SourceNode()
×
UNCOV
3262
        if err != nil {
×
3263
                return fmt.Errorf("unable to get current source node: %w", err)
×
3264
        }
×
3265

UNCOV
3266
        selfNode.HaveNodeAnnouncement = true
×
UNCOV
3267
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
×
UNCOV
3268
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3269
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3270
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3271
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3272
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3273

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

×
UNCOV
3276
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3277
                return fmt.Errorf("can't set self node: %w", err)
×
3278
        }
×
3279

3280
        // Finally, propagate it to the nodes in the network.
UNCOV
3281
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
UNCOV
3282
        if err != nil {
×
3283
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3284
                        "announcement to peers: %v", err)
×
3285
                return err
×
3286
        }
×
3287

UNCOV
3288
        return nil
×
3289
}
3290

3291
type nodeAddresses struct {
3292
        pubKey    *btcec.PublicKey
3293
        addresses []net.Addr
3294
}
3295

3296
// establishPersistentConnections attempts to establish persistent connections
3297
// to all our direct channel collaborators. In order to promote liveness of our
3298
// active channels, we instruct the connection manager to attempt to establish
3299
// and maintain persistent connections to all our direct channel counterparties.
UNCOV
3300
func (s *server) establishPersistentConnections() error {
×
UNCOV
3301
        // nodeAddrsMap stores the combination of node public keys and addresses
×
UNCOV
3302
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3303
        // since other PubKey forms can't be compared.
×
UNCOV
3304
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3305

×
UNCOV
3306
        // Iterate through the list of LinkNodes to find addresses we should
×
UNCOV
3307
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3308
        // the reconnection port to the default peer port.
×
UNCOV
3309
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3310
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3311
                return err
×
3312
        }
×
UNCOV
3313
        for _, node := range linkNodes {
×
UNCOV
3314
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3315
                nodeAddrs := &nodeAddresses{
×
UNCOV
3316
                        pubKey:    node.IdentityPub,
×
UNCOV
3317
                        addresses: node.Addresses,
×
UNCOV
3318
                }
×
UNCOV
3319
                nodeAddrsMap[pubStr] = nodeAddrs
×
UNCOV
3320
        }
×
3321

3322
        // After checking our previous connections for addresses to connect to,
3323
        // iterate through the nodes in our channel graph to find addresses
3324
        // that have been added via NodeAnnouncement messages.
UNCOV
3325
        sourceNode, err := s.graphDB.SourceNode()
×
UNCOV
3326
        if err != nil {
×
3327
                return err
×
3328
        }
×
3329

3330
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3331
        // each of the nodes.
UNCOV
3332
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
3333
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
×
UNCOV
3334
                tx kvdb.RTx,
×
UNCOV
3335
                chanInfo *models.ChannelEdgeInfo,
×
UNCOV
3336
                policy, _ *models.ChannelEdgePolicy) error {
×
UNCOV
3337

×
UNCOV
3338
                // If the remote party has announced the channel to us, but we
×
UNCOV
3339
                // haven't yet, then we won't have a policy. However, we don't
×
UNCOV
3340
                // need this to connect to the peer, so we'll log it and move on.
×
UNCOV
3341
                if policy == nil {
×
3342
                        srvrLog.Warnf("No channel policy found for "+
×
3343
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3344
                }
×
3345

3346
                // We'll now fetch the peer opposite from us within this
3347
                // channel so we can queue up a direct connection to them.
UNCOV
3348
                channelPeer, err := s.graphDB.FetchOtherNode(
×
UNCOV
3349
                        tx, chanInfo, selfPub,
×
UNCOV
3350
                )
×
UNCOV
3351
                if err != nil {
×
3352
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3353
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3354
                                err)
×
3355
                }
×
3356

UNCOV
3357
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3358

×
UNCOV
3359
                // Add all unique addresses from channel
×
UNCOV
3360
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3361
                // connect to for this peer.
×
UNCOV
3362
                addrSet := make(map[string]net.Addr)
×
UNCOV
3363
                for _, addr := range channelPeer.Addresses {
×
UNCOV
3364
                        switch addr.(type) {
×
UNCOV
3365
                        case *net.TCPAddr:
×
UNCOV
3366
                                addrSet[addr.String()] = addr
×
3367

3368
                        // We'll only attempt to connect to Tor addresses if Tor
3369
                        // outbound support is enabled.
3370
                        case *tor.OnionAddr:
×
3371
                                if s.cfg.Tor.Active {
×
3372
                                        addrSet[addr.String()] = addr
×
3373
                                }
×
3374
                        }
3375
                }
3376

3377
                // If this peer is also recorded as a link node, we'll add any
3378
                // additional addresses that have not already been selected.
UNCOV
3379
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3380
                if ok {
×
UNCOV
3381
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3382
                                switch lnAddress.(type) {
×
UNCOV
3383
                                case *net.TCPAddr:
×
UNCOV
3384
                                        addrSet[lnAddress.String()] = lnAddress
×
3385

3386
                                // We'll only attempt to connect to Tor
3387
                                // addresses if Tor outbound support is enabled.
3388
                                case *tor.OnionAddr:
×
3389
                                        if s.cfg.Tor.Active {
×
3390
                                                addrSet[lnAddress.String()] = lnAddress
×
3391
                                        }
×
3392
                                }
3393
                        }
3394
                }
3395

3396
                // Construct a slice of the deduped addresses.
UNCOV
3397
                var addrs []net.Addr
×
UNCOV
3398
                for _, addr := range addrSet {
×
UNCOV
3399
                        addrs = append(addrs, addr)
×
UNCOV
3400
                }
×
3401

UNCOV
3402
                n := &nodeAddresses{
×
UNCOV
3403
                        addresses: addrs,
×
UNCOV
3404
                }
×
UNCOV
3405
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3406
                if err != nil {
×
3407
                        return err
×
3408
                }
×
3409

UNCOV
3410
                nodeAddrsMap[pubStr] = n
×
UNCOV
3411
                return nil
×
3412
        })
UNCOV
3413
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
×
3414
                return err
×
3415
        }
×
3416

UNCOV
3417
        srvrLog.Debugf("Establishing %v persistent connections on start",
×
UNCOV
3418
                len(nodeAddrsMap))
×
UNCOV
3419

×
UNCOV
3420
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3421
        // have been recorded and sent to the connection manager.
×
UNCOV
3422
        s.mu.Lock()
×
UNCOV
3423
        defer s.mu.Unlock()
×
UNCOV
3424

×
UNCOV
3425
        // Iterate through the combined list of addresses from prior links and
×
UNCOV
3426
        // node announcements and attempt to reconnect to each node.
×
UNCOV
3427
        var numOutboundConns int
×
UNCOV
3428
        for pubStr, nodeAddr := range nodeAddrsMap {
×
UNCOV
3429
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3430
                // persistent connection with. We set the value to false to
×
UNCOV
3431
                // indicate that we should not continue to reconnect if the
×
UNCOV
3432
                // number of channels returns to zero, since this peer has not
×
UNCOV
3433
                // been requested as perm by the user.
×
UNCOV
3434
                s.persistentPeers[pubStr] = false
×
UNCOV
3435
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
×
UNCOV
3436
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
×
UNCOV
3437
                }
×
3438

UNCOV
3439
                for _, address := range nodeAddr.addresses {
×
UNCOV
3440
                        // Create a wrapper address which couples the IP and
×
UNCOV
3441
                        // the pubkey so the brontide authenticated connection
×
UNCOV
3442
                        // can be established.
×
UNCOV
3443
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3444
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3445
                                Address:     address,
×
UNCOV
3446
                        }
×
UNCOV
3447

×
UNCOV
3448
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3449
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
UNCOV
3450
                }
×
3451

3452
                // We'll connect to the first 10 peers immediately, then
3453
                // randomly stagger any remaining connections if the
3454
                // stagger initial reconnect flag is set. This ensures
3455
                // that mobile nodes or nodes with a small number of
3456
                // channels obtain connectivity quickly, but larger
3457
                // nodes are able to disperse the costs of connecting to
3458
                // all peers at once.
UNCOV
3459
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3460
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3461

×
UNCOV
3462
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3463
                } else {
×
3464
                        go s.delayInitialReconnect(pubStr)
×
3465
                }
×
3466

UNCOV
3467
                numOutboundConns++
×
3468
        }
3469

UNCOV
3470
        return nil
×
3471
}
3472

3473
// delayInitialReconnect will attempt a reconnection to the given peer after
3474
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3475
//
3476
// NOTE: This method MUST be run as a goroutine.
3477
func (s *server) delayInitialReconnect(pubStr string) {
×
3478
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3479
        select {
×
3480
        case <-time.After(delay):
×
3481
                s.connectToPersistentPeer(pubStr)
×
3482
        case <-s.quit:
×
3483
        }
3484
}
3485

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

×
UNCOV
3492
        s.mu.Lock()
×
UNCOV
3493
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
UNCOV
3494
                delete(s.persistentPeers, pubKeyStr)
×
UNCOV
3495
                delete(s.persistentPeersBackoff, pubKeyStr)
×
UNCOV
3496
                delete(s.persistentPeerAddrs, pubKeyStr)
×
UNCOV
3497
                s.cancelConnReqs(pubKeyStr, nil)
×
UNCOV
3498
                s.mu.Unlock()
×
UNCOV
3499

×
UNCOV
3500
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3501
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3502

×
UNCOV
3503
                return
×
UNCOV
3504
        }
×
UNCOV
3505
        s.mu.Unlock()
×
3506
}
3507

3508
// BroadcastMessage sends a request to the server to broadcast a set of
3509
// messages to all peers other than the one specified by the `skips` parameter.
3510
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3511
// the target peers.
3512
//
3513
// NOTE: This function is safe for concurrent access.
3514
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
UNCOV
3515
        msgs ...lnwire.Message) error {
×
UNCOV
3516

×
UNCOV
3517
        // Filter out peers found in the skips map. We synchronize access to
×
UNCOV
3518
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3519
        // exact set of peers present at the time of invocation.
×
UNCOV
3520
        s.mu.RLock()
×
UNCOV
3521
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3522
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3523
                if skips != nil {
×
UNCOV
3524
                        if _, ok := skips[sPeer.PubKey()]; ok {
×
UNCOV
3525
                                srvrLog.Tracef("Skipping %x in broadcast with "+
×
UNCOV
3526
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
×
UNCOV
3527
                                continue
×
3528
                        }
3529
                }
3530

UNCOV
3531
                peers = append(peers, sPeer)
×
3532
        }
UNCOV
3533
        s.mu.RUnlock()
×
UNCOV
3534

×
UNCOV
3535
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3536
        // all messages to each of peers.
×
UNCOV
3537
        var wg sync.WaitGroup
×
UNCOV
3538
        for _, sPeer := range peers {
×
UNCOV
3539
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3540
                        sPeer.PubKey())
×
UNCOV
3541

×
UNCOV
3542
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3543
                wg.Add(1)
×
UNCOV
3544
                s.wg.Add(1)
×
UNCOV
3545
                go func(p lnpeer.Peer) {
×
UNCOV
3546
                        defer s.wg.Done()
×
UNCOV
3547
                        defer wg.Done()
×
UNCOV
3548

×
UNCOV
3549
                        p.SendMessageLazy(false, msgs...)
×
UNCOV
3550
                }(sPeer)
×
3551
        }
3552

3553
        // Wait for all messages to have been dispatched before returning to
3554
        // caller.
UNCOV
3555
        wg.Wait()
×
UNCOV
3556

×
UNCOV
3557
        return nil
×
3558
}
3559

3560
// NotifyWhenOnline can be called by other subsystems to get notified when a
3561
// particular peer comes online. The peer itself is sent across the peerChan.
3562
//
3563
// NOTE: This function is safe for concurrent access.
3564
func (s *server) NotifyWhenOnline(peerKey [33]byte,
UNCOV
3565
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3566

×
UNCOV
3567
        s.mu.Lock()
×
UNCOV
3568

×
UNCOV
3569
        // Compute the target peer's identifier.
×
UNCOV
3570
        pubStr := string(peerKey[:])
×
UNCOV
3571

×
UNCOV
3572
        // Check if peer is connected.
×
UNCOV
3573
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3574
        if ok {
×
UNCOV
3575
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3576
                // waiting for the peer to become active.
×
UNCOV
3577
                s.mu.Unlock()
×
UNCOV
3578

×
UNCOV
3579
                // Wait until the peer signals that it is actually active
×
UNCOV
3580
                // rather than only in the server's maps.
×
UNCOV
3581
                select {
×
UNCOV
3582
                case <-peer.ActiveSignal():
×
3583
                case <-peer.QuitSignal():
×
3584
                        // The peer quit, so we'll add the channel to the slice
×
3585
                        // and return.
×
3586
                        s.mu.Lock()
×
3587
                        s.peerConnectedListeners[pubStr] = append(
×
3588
                                s.peerConnectedListeners[pubStr], peerChan,
×
3589
                        )
×
3590
                        s.mu.Unlock()
×
3591
                        return
×
3592
                }
3593

3594
                // Connected, can return early.
UNCOV
3595
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
×
UNCOV
3596

×
UNCOV
3597
                select {
×
UNCOV
3598
                case peerChan <- peer:
×
3599
                case <-s.quit:
×
3600
                }
3601

UNCOV
3602
                return
×
3603
        }
3604

3605
        // Not connected, store this listener such that it can be notified when
3606
        // the peer comes online.
UNCOV
3607
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3608
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3609
        )
×
UNCOV
3610
        s.mu.Unlock()
×
3611
}
3612

3613
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3614
// the given public key has been disconnected. The notification is signaled by
3615
// closing the channel returned.
UNCOV
3616
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3617
        s.mu.Lock()
×
UNCOV
3618
        defer s.mu.Unlock()
×
UNCOV
3619

×
UNCOV
3620
        c := make(chan struct{})
×
UNCOV
3621

×
UNCOV
3622
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3623
        // notification.
×
UNCOV
3624
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3625
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3626
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3627
                close(c)
×
3628
                return c
×
3629
        }
×
3630

3631
        // Otherwise, the peer is online, so we'll keep track of the channel to
3632
        // trigger the notification once the server detects the peer
3633
        // disconnects.
UNCOV
3634
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
×
UNCOV
3635
                s.peerDisconnectedListeners[peerPubKeyStr], c,
×
UNCOV
3636
        )
×
UNCOV
3637

×
UNCOV
3638
        return c
×
3639
}
3640

3641
// FindPeer will return the peer that corresponds to the passed in public key.
3642
// This function is used by the funding manager, allowing it to update the
3643
// daemon's local representation of the remote peer.
3644
//
3645
// NOTE: This function is safe for concurrent access.
UNCOV
3646
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
×
UNCOV
3647
        s.mu.RLock()
×
UNCOV
3648
        defer s.mu.RUnlock()
×
UNCOV
3649

×
UNCOV
3650
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3651

×
UNCOV
3652
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3653
}
×
3654

3655
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3656
// which should be a string representation of the peer's serialized, compressed
3657
// public key.
3658
//
3659
// NOTE: This function is safe for concurrent access.
UNCOV
3660
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3661
        s.mu.RLock()
×
UNCOV
3662
        defer s.mu.RUnlock()
×
UNCOV
3663

×
UNCOV
3664
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3665
}
×
3666

3667
// findPeerByPubStr is an internal method that retrieves the specified peer from
3668
// the server's internal state using.
UNCOV
3669
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3670
        peer, ok := s.peersByPub[pubStr]
×
UNCOV
3671
        if !ok {
×
UNCOV
3672
                return nil, ErrPeerNotConnected
×
UNCOV
3673
        }
×
3674

UNCOV
3675
        return peer, nil
×
3676
}
3677

3678
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3679
// exponential backoff. If no previous backoff was known, the default is
3680
// returned.
3681
func (s *server) nextPeerBackoff(pubStr string,
UNCOV
3682
        startTime time.Time) time.Duration {
×
UNCOV
3683

×
UNCOV
3684
        // Now, determine the appropriate backoff to use for the retry.
×
UNCOV
3685
        backoff, ok := s.persistentPeersBackoff[pubStr]
×
UNCOV
3686
        if !ok {
×
UNCOV
3687
                // If an existing backoff was unknown, use the default.
×
UNCOV
3688
                return s.cfg.MinBackoff
×
UNCOV
3689
        }
×
3690

3691
        // If the peer failed to start properly, we'll just use the previous
3692
        // backoff to compute the subsequent randomized exponential backoff
3693
        // duration. This will roughly double on average.
UNCOV
3694
        if startTime.IsZero() {
×
3695
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3696
        }
×
3697

3698
        // The peer succeeded in starting. If the connection didn't last long
3699
        // enough to be considered stable, we'll continue to back off retries
3700
        // with this peer.
UNCOV
3701
        connDuration := time.Since(startTime)
×
UNCOV
3702
        if connDuration < defaultStableConnDuration {
×
UNCOV
3703
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3704
        }
×
3705

3706
        // The peer succeed in starting and this was stable peer, so we'll
3707
        // reduce the timeout duration by the length of the connection after
3708
        // applying randomized exponential backoff. We'll only apply this in the
3709
        // case that:
3710
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3711
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3712
        if relaxedBackoff > s.cfg.MinBackoff {
×
3713
                return relaxedBackoff
×
3714
        }
×
3715

3716
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3717
        // the stable connection lasted much longer than our previous backoff.
3718
        // To reward such good behavior, we'll reconnect after the default
3719
        // timeout.
3720
        return s.cfg.MinBackoff
×
3721
}
3722

3723
// shouldDropLocalConnection determines if our local connection to a remote peer
3724
// should be dropped in the case of concurrent connection establishment. In
3725
// order to deterministically decide which connection should be dropped, we'll
3726
// utilize the ordering of the local and remote public key. If we didn't use
3727
// such a tie breaker, then we risk _both_ connections erroneously being
3728
// dropped.
3729
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3730
        localPubBytes := local.SerializeCompressed()
×
3731
        remotePubPbytes := remote.SerializeCompressed()
×
3732

×
3733
        // The connection that comes from the node with a "smaller" pubkey
×
3734
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3735
        // should drop our established connection.
×
3736
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3737
}
×
3738

3739
// InboundPeerConnected initializes a new peer in response to a new inbound
3740
// connection.
3741
//
3742
// NOTE: This function is safe for concurrent access.
UNCOV
3743
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3744
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3745
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3746
        if s.Stopped() {
×
3747
                return
×
3748
        }
×
3749

UNCOV
3750
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3751
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3752
        pubStr := string(pubSer)
×
UNCOV
3753

×
UNCOV
3754
        var pubBytes [33]byte
×
UNCOV
3755
        copy(pubBytes[:], pubSer)
×
UNCOV
3756

×
UNCOV
3757
        s.mu.Lock()
×
UNCOV
3758
        defer s.mu.Unlock()
×
UNCOV
3759

×
UNCOV
3760
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3761
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3762
        if dcErr != nil {
×
3763
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3764
                        "peer: %v", dcErr)
×
3765
                conn.Close()
×
3766

×
3767
                return
×
3768
        }
×
3769

UNCOV
3770
        if shouldDc {
×
3771
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3772
                        "banned.", pubSer)
×
3773

×
3774
                conn.Close()
×
3775

×
3776
                return
×
3777
        }
×
3778

3779
        // If we already have an outbound connection to this peer, then ignore
3780
        // this new connection.
UNCOV
3781
        if p, ok := s.outboundPeers[pubStr]; ok {
×
UNCOV
3782
                srvrLog.Debugf("Already have outbound connection for %v, "+
×
UNCOV
3783
                        "ignoring inbound connection from local=%v, remote=%v",
×
UNCOV
3784
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3785

×
UNCOV
3786
                conn.Close()
×
UNCOV
3787
                return
×
UNCOV
3788
        }
×
3789

3790
        // If we already have a valid connection that is scheduled to take
3791
        // precedence once the prior peer has finished disconnecting, we'll
3792
        // ignore this connection.
UNCOV
3793
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3794
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3795
                        "scheduled", conn.RemoteAddr(), p)
×
3796
                conn.Close()
×
3797
                return
×
3798
        }
×
3799

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

×
UNCOV
3802
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3803
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3804
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3805
        // default case as we expect these to be the only error values returned
×
UNCOV
3806
        // from findPeerByPubStr.
×
UNCOV
3807
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3808
        switch err {
×
UNCOV
3809
        case ErrPeerNotConnected:
×
UNCOV
3810
                // We were unable to locate an existing connection with the
×
UNCOV
3811
                // target peer, proceed to connect.
×
UNCOV
3812
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3813
                s.peerConnected(conn, nil, true)
×
3814

3815
        case nil:
×
3816
                // We already have a connection with the incoming peer. If the
×
3817
                // connection we've already established should be kept and is
×
3818
                // not of the same type of the new connection (inbound), then
×
3819
                // we'll close out the new connection s.t there's only a single
×
3820
                // connection between us.
×
3821
                localPub := s.identityECDH.PubKey()
×
3822
                if !connectedPeer.Inbound() &&
×
3823
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3824

×
3825
                        srvrLog.Warnf("Received inbound connection from "+
×
3826
                                "peer %v, but already have outbound "+
×
3827
                                "connection, dropping conn", connectedPeer)
×
3828
                        conn.Close()
×
3829
                        return
×
3830
                }
×
3831

3832
                // Otherwise, if we should drop the connection, then we'll
3833
                // disconnect our already connected peer.
3834
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3835
                        connectedPeer)
×
3836

×
3837
                s.cancelConnReqs(pubStr, nil)
×
3838

×
3839
                // Remove the current peer from the server's internal state and
×
3840
                // signal that the peer termination watcher does not need to
×
3841
                // execute for this peer.
×
3842
                s.removePeer(connectedPeer)
×
3843
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3844
                s.scheduledPeerConnection[pubStr] = func() {
×
3845
                        s.peerConnected(conn, nil, true)
×
3846
                }
×
3847
        }
3848
}
3849

3850
// OutboundPeerConnected initializes a new peer in response to a new outbound
3851
// connection.
3852
// NOTE: This function is safe for concurrent access.
UNCOV
3853
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
3854
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3855
        // prevents any delayed callbacks from accidentally registering peers.
×
UNCOV
3856
        if s.Stopped() {
×
3857
                return
×
3858
        }
×
3859

UNCOV
3860
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3861
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3862
        pubStr := string(pubSer)
×
UNCOV
3863

×
UNCOV
3864
        var pubBytes [33]byte
×
UNCOV
3865
        copy(pubBytes[:], pubSer)
×
UNCOV
3866

×
UNCOV
3867
        s.mu.Lock()
×
UNCOV
3868
        defer s.mu.Unlock()
×
UNCOV
3869

×
UNCOV
3870
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3871
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
UNCOV
3872
        if dcErr != nil {
×
3873
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3874
                        "peer: %v", dcErr)
×
3875
                conn.Close()
×
3876

×
3877
                return
×
3878
        }
×
3879

UNCOV
3880
        if shouldDc {
×
3881
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3882
                        "banned.", pubSer)
×
3883

×
3884
                if connReq != nil {
×
3885
                        s.connMgr.Remove(connReq.ID())
×
3886
                }
×
3887

3888
                conn.Close()
×
3889

×
3890
                return
×
3891
        }
3892

3893
        // If we already have an inbound connection to this peer, then ignore
3894
        // this new connection.
UNCOV
3895
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
3896
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
3897
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
3898
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3899

×
UNCOV
3900
                if connReq != nil {
×
UNCOV
3901
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
3902
                }
×
UNCOV
3903
                conn.Close()
×
UNCOV
3904
                return
×
3905
        }
UNCOV
3906
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
3907
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3908
                s.connMgr.Remove(connReq.ID())
×
3909
                conn.Close()
×
3910
                return
×
3911
        }
×
3912

3913
        // If we already have a valid connection that is scheduled to take
3914
        // precedence once the prior peer has finished disconnecting, we'll
3915
        // ignore this connection.
UNCOV
3916
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3917
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3918

×
3919
                if connReq != nil {
×
3920
                        s.connMgr.Remove(connReq.ID())
×
3921
                }
×
3922

3923
                conn.Close()
×
3924
                return
×
3925
        }
3926

UNCOV
3927
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
UNCOV
3928
                conn.RemoteAddr())
×
UNCOV
3929

×
UNCOV
3930
        if connReq != nil {
×
UNCOV
3931
                // A successful connection was returned by the connmgr.
×
UNCOV
3932
                // Immediately cancel all pending requests, excluding the
×
UNCOV
3933
                // outbound connection we just established.
×
UNCOV
3934
                ignore := connReq.ID()
×
UNCOV
3935
                s.cancelConnReqs(pubStr, &ignore)
×
UNCOV
3936
        } else {
×
UNCOV
3937
                // This was a successful connection made by some other
×
UNCOV
3938
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
3939
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3940
        }
×
3941

3942
        // If we already have a connection with this peer, decide whether or not
3943
        // we need to drop the stale connection. We forgo adding a default case
3944
        // as we expect these to be the only error values returned from
3945
        // findPeerByPubStr.
UNCOV
3946
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3947
        switch err {
×
UNCOV
3948
        case ErrPeerNotConnected:
×
UNCOV
3949
                // We were unable to locate an existing connection with the
×
UNCOV
3950
                // target peer, proceed to connect.
×
UNCOV
3951
                s.peerConnected(conn, connReq, false)
×
3952

3953
        case nil:
×
3954
                // We already have a connection with the incoming peer. If the
×
3955
                // connection we've already established should be kept and is
×
3956
                // not of the same type of the new connection (outbound), then
×
3957
                // we'll close out the new connection s.t there's only a single
×
3958
                // connection between us.
×
3959
                localPub := s.identityECDH.PubKey()
×
3960
                if connectedPeer.Inbound() &&
×
3961
                        shouldDropLocalConnection(localPub, nodePub) {
×
3962

×
3963
                        srvrLog.Warnf("Established outbound connection to "+
×
3964
                                "peer %v, but already have inbound "+
×
3965
                                "connection, dropping conn", connectedPeer)
×
3966
                        if connReq != nil {
×
3967
                                s.connMgr.Remove(connReq.ID())
×
3968
                        }
×
3969
                        conn.Close()
×
3970
                        return
×
3971
                }
3972

3973
                // Otherwise, _their_ connection should be dropped. So we'll
3974
                // disconnect the peer and send the now obsolete peer to the
3975
                // server for garbage collection.
3976
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3977
                        connectedPeer)
×
3978

×
3979
                // Remove the current peer from the server's internal state and
×
3980
                // signal that the peer termination watcher does not need to
×
3981
                // execute for this peer.
×
3982
                s.removePeer(connectedPeer)
×
3983
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3984
                s.scheduledPeerConnection[pubStr] = func() {
×
3985
                        s.peerConnected(conn, connReq, false)
×
3986
                }
×
3987
        }
3988
}
3989

3990
// UnassignedConnID is the default connection ID that a request can have before
3991
// it actually is submitted to the connmgr.
3992
// TODO(conner): move into connmgr package, or better, add connmgr method for
3993
// generating atomic IDs
3994
const UnassignedConnID uint64 = 0
3995

3996
// cancelConnReqs stops all persistent connection requests for a given pubkey.
3997
// Any attempts initiated by the peerTerminationWatcher are canceled first.
3998
// Afterwards, each connection request removed from the connmgr. The caller can
3999
// optionally specify a connection ID to ignore, which prevents us from
4000
// canceling a successful request. All persistent connreqs for the provided
4001
// pubkey are discarded after the operationjw.
UNCOV
4002
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
4003
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
4004
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
4005
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
4006
                close(cancelChan)
×
UNCOV
4007
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
4008
        }
×
4009

4010
        // Next, check to see if we have any outstanding persistent connection
4011
        // requests to this peer. If so, then we'll remove all of these
4012
        // connection requests, and also delete the entry from the map.
UNCOV
4013
        connReqs, ok := s.persistentConnReqs[pubStr]
×
UNCOV
4014
        if !ok {
×
UNCOV
4015
                return
×
UNCOV
4016
        }
×
4017

UNCOV
4018
        for _, connReq := range connReqs {
×
UNCOV
4019
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
4020

×
UNCOV
4021
                // Atomically capture the current request identifier.
×
UNCOV
4022
                connID := connReq.ID()
×
UNCOV
4023

×
UNCOV
4024
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
4025
                // yet been schedule.
×
UNCOV
4026
                if connID == UnassignedConnID {
×
4027
                        continue
×
4028
                }
4029

4030
                // Skip a particular connection ID if instructed.
UNCOV
4031
                if skip != nil && connID == *skip {
×
UNCOV
4032
                        continue
×
4033
                }
4034

UNCOV
4035
                s.connMgr.Remove(connID)
×
4036
        }
4037

UNCOV
4038
        delete(s.persistentConnReqs, pubStr)
×
4039
}
4040

4041
// handleCustomMessage dispatches an incoming custom peers message to
4042
// subscribers.
UNCOV
4043
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
4044
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
4045
                peer, msg.Type)
×
UNCOV
4046

×
UNCOV
4047
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
4048
                Peer: peer,
×
UNCOV
4049
                Msg:  msg,
×
UNCOV
4050
        })
×
UNCOV
4051
}
×
4052

4053
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4054
// messages.
UNCOV
4055
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
4056
        return s.customMessageServer.Subscribe()
×
UNCOV
4057
}
×
4058

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

×
UNCOV
4066
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4067
        addr := conn.RemoteAddr()
×
UNCOV
4068
        pubKey := brontideConn.RemotePub()
×
UNCOV
4069

×
UNCOV
4070
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
×
UNCOV
4071
                pubKey.SerializeCompressed(), addr, inbound)
×
UNCOV
4072

×
UNCOV
4073
        peerAddr := &lnwire.NetAddress{
×
UNCOV
4074
                IdentityKey: pubKey,
×
UNCOV
4075
                Address:     addr,
×
UNCOV
4076
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
4077
        }
×
UNCOV
4078

×
UNCOV
4079
        // With the brontide connection established, we'll now craft the feature
×
UNCOV
4080
        // vectors to advertise to the remote node.
×
UNCOV
4081
        initFeatures := s.featureMgr.Get(feature.SetInit)
×
UNCOV
4082
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
×
UNCOV
4083

×
UNCOV
4084
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4085
        // found, create a fresh buffer.
×
UNCOV
4086
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4087
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4088
        if !ok {
×
UNCOV
4089
                var err error
×
UNCOV
4090
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4091
                if err != nil {
×
4092
                        srvrLog.Errorf("unable to create peer %v", err)
×
4093
                        return
×
4094
                }
×
4095
        }
4096

4097
        // If we directly set the peer.Config TowerClient member to the
4098
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4099
        // the peer.Config's TowerClient member will not evaluate to nil even
4100
        // though the underlying value is nil. To avoid this gotcha which can
4101
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4102
        // TowerClient if needed.
UNCOV
4103
        var towerClient wtclient.ClientManager
×
UNCOV
4104
        if s.towerClientMgr != nil {
×
UNCOV
4105
                towerClient = s.towerClientMgr
×
UNCOV
4106
        }
×
4107

UNCOV
4108
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4109
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4110

×
UNCOV
4111
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4112
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4113
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4114
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4115
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4116
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4117
        pCfg := peer.Config{
×
UNCOV
4118
                Conn:                    brontideConn,
×
UNCOV
4119
                ConnReq:                 connReq,
×
UNCOV
4120
                Addr:                    peerAddr,
×
UNCOV
4121
                Inbound:                 inbound,
×
UNCOV
4122
                Features:                initFeatures,
×
UNCOV
4123
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4124
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4125
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4126
                ErrorBuffer:             errBuffer,
×
UNCOV
4127
                WritePool:               s.writePool,
×
UNCOV
4128
                ReadPool:                s.readPool,
×
UNCOV
4129
                Switch:                  s.htlcSwitch,
×
UNCOV
4130
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4131
                ChannelDB:               s.chanStateDB,
×
UNCOV
4132
                ChannelGraph:            s.graphDB,
×
UNCOV
4133
                ChainArb:                s.chainArb,
×
UNCOV
4134
                AuthGossiper:            s.authGossiper,
×
UNCOV
4135
                ChanStatusMgr:           s.chanStatusMgr,
×
UNCOV
4136
                ChainIO:                 s.cc.ChainIO,
×
UNCOV
4137
                FeeEstimator:            s.cc.FeeEstimator,
×
UNCOV
4138
                Signer:                  s.cc.Wallet.Cfg.Signer,
×
UNCOV
4139
                SigPool:                 s.sigPool,
×
UNCOV
4140
                Wallet:                  s.cc.Wallet,
×
UNCOV
4141
                ChainNotifier:           s.cc.ChainNotifier,
×
UNCOV
4142
                BestBlockView:           s.cc.BestBlockTracker,
×
UNCOV
4143
                RoutingPolicy:           s.cc.RoutingPolicy,
×
UNCOV
4144
                Sphinx:                  s.sphinx,
×
UNCOV
4145
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4146
                Invoices:                s.invoices,
×
UNCOV
4147
                ChannelNotifier:         s.channelNotifier,
×
UNCOV
4148
                HtlcNotifier:            s.htlcNotifier,
×
UNCOV
4149
                TowerClient:             towerClient,
×
UNCOV
4150
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4151
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4152
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4153

×
UNCOV
4154
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4155
                },
×
4156

4157
                PongBuf: s.pongBuf,
4158

4159
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4160

4161
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4162

4163
                FundingManager: s.fundingMgr,
4164

4165
                Hodl:                    s.cfg.Hodl,
4166
                UnsafeReplay:            s.cfg.UnsafeReplay,
4167
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4168
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4169
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4170
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4171
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4172
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4173
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4174
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4175
                HandleCustomMessage:    s.handleCustomMessage,
4176
                GetAliases:             s.aliasMgr.GetAliases,
4177
                RequestAlias:           s.aliasMgr.RequestAlias,
4178
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4179
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4180
                MaxFeeExposure:         thresholdMSats,
4181
                Quit:                   s.quit,
4182
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4183
                AuxSigner:              s.implCfg.AuxSigner,
4184
                MsgRouter:              s.implCfg.MsgRouter,
4185
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4186
                AuxResolver:            s.implCfg.AuxContractResolver,
4187
        }
4188

UNCOV
4189
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4190
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4191

×
UNCOV
4192
        p := peer.NewBrontide(pCfg)
×
UNCOV
4193

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

×
UNCOV
4197
        s.addPeer(p)
×
UNCOV
4198

×
UNCOV
4199
        // Once we have successfully added the peer to the server, we can
×
UNCOV
4200
        // delete the previous error buffer from the server's map of error
×
UNCOV
4201
        // buffers.
×
UNCOV
4202
        delete(s.peerErrors, pkStr)
×
UNCOV
4203

×
UNCOV
4204
        // Dispatch a goroutine to asynchronously start the peer. This process
×
UNCOV
4205
        // includes sending and receiving Init messages, which would be a DOS
×
UNCOV
4206
        // vector if we held the server's mutex throughout the procedure.
×
UNCOV
4207
        s.wg.Add(1)
×
UNCOV
4208
        go s.peerInitializer(p)
×
4209
}
4210

4211
// addPeer adds the passed peer to the server's global state of all active
4212
// peers.
UNCOV
4213
func (s *server) addPeer(p *peer.Brontide) {
×
UNCOV
4214
        if p == nil {
×
4215
                return
×
4216
        }
×
4217

4218
        // Ignore new peers if we're shutting down.
UNCOV
4219
        if s.Stopped() {
×
4220
                p.Disconnect(ErrServerShuttingDown)
×
4221
                return
×
4222
        }
×
4223

4224
        // Track the new peer in our indexes so we can quickly look it up either
4225
        // according to its public key, or its peer ID.
4226
        // TODO(roasbeef): pipe all requests through to the
4227
        // queryHandler/peerManager
4228

UNCOV
4229
        pubSer := p.IdentityKey().SerializeCompressed()
×
UNCOV
4230
        pubStr := string(pubSer)
×
UNCOV
4231

×
UNCOV
4232
        s.peersByPub[pubStr] = p
×
UNCOV
4233

×
UNCOV
4234
        if p.Inbound() {
×
UNCOV
4235
                s.inboundPeers[pubStr] = p
×
UNCOV
4236
        } else {
×
UNCOV
4237
                s.outboundPeers[pubStr] = p
×
UNCOV
4238
        }
×
4239

4240
        // Inform the peer notifier of a peer online event so that it can be reported
4241
        // to clients listening for peer events.
UNCOV
4242
        var pubKey [33]byte
×
UNCOV
4243
        copy(pubKey[:], pubSer)
×
UNCOV
4244

×
UNCOV
4245
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
4246
}
4247

4248
// peerInitializer asynchronously starts a newly connected peer after it has
4249
// been added to the server's peer map. This method sets up a
4250
// peerTerminationWatcher for the given peer, and ensures that it executes even
4251
// if the peer failed to start. In the event of a successful connection, this
4252
// method reads the negotiated, local feature-bits and spawns the appropriate
4253
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4254
// be signaled of the new peer once the method returns.
4255
//
4256
// NOTE: This MUST be launched as a goroutine.
UNCOV
4257
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4258
        defer s.wg.Done()
×
UNCOV
4259

×
UNCOV
4260
        // Avoid initializing peers while the server is exiting.
×
UNCOV
4261
        if s.Stopped() {
×
4262
                return
×
4263
        }
×
4264

4265
        // Create a channel that will be used to signal a successful start of
4266
        // the link. This prevents the peer termination watcher from beginning
4267
        // its duty too early.
UNCOV
4268
        ready := make(chan struct{})
×
UNCOV
4269

×
UNCOV
4270
        // Before starting the peer, launch a goroutine to watch for the
×
UNCOV
4271
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4272
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4273
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4274
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4275
        // that the server has already handled the removal of this peer.
×
UNCOV
4276
        s.wg.Add(1)
×
UNCOV
4277
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4278

×
UNCOV
4279
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4280

×
UNCOV
4281
        // Start the peer! If an error occurs, we Disconnect the peer, which
×
UNCOV
4282
        // will unblock the peerTerminationWatcher.
×
UNCOV
4283
        if err := p.Start(); err != nil {
×
UNCOV
4284
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4285

×
UNCOV
4286
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4287
                return
×
UNCOV
4288
        }
×
4289

4290
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4291
        // was successful, and to begin watching the peer's wait group.
UNCOV
4292
        close(ready)
×
UNCOV
4293

×
UNCOV
4294
        s.mu.Lock()
×
UNCOV
4295
        defer s.mu.Unlock()
×
UNCOV
4296

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

×
UNCOV
4300
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4301
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4302
        pubStr := string(pubBytes)
×
UNCOV
4303
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4304
                select {
×
UNCOV
4305
                case peerChan <- p:
×
4306
                case <-s.quit:
×
4307
                        return
×
4308
                }
4309
        }
UNCOV
4310
        delete(s.peerConnectedListeners, pubStr)
×
4311
}
4312

4313
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4314
// and then cleans up all resources allocated to the peer, notifies relevant
4315
// sub-systems of its demise, and finally handles re-connecting to the peer if
4316
// it's persistent. If the server intentionally disconnects a peer, it should
4317
// have a corresponding entry in the ignorePeerTermination map which will cause
4318
// the cleanup routine to exit early. The passed `ready` chan is used to
4319
// synchronize when WaitForDisconnect should begin watching on the peer's
4320
// waitgroup. The ready chan should only be signaled if the peer starts
4321
// successfully, otherwise the peer should be disconnected instead.
4322
//
4323
// NOTE: This MUST be launched as a goroutine.
UNCOV
4324
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4325
        defer s.wg.Done()
×
UNCOV
4326

×
UNCOV
4327
        p.WaitForDisconnect(ready)
×
UNCOV
4328

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

×
UNCOV
4331
        // If the server is exiting then we can bail out early ourselves as all
×
UNCOV
4332
        // the other sub-systems will already be shutting down.
×
UNCOV
4333
        if s.Stopped() {
×
UNCOV
4334
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4335
                return
×
UNCOV
4336
        }
×
4337

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

×
UNCOV
4344
        pubKey := p.IdentityKey()
×
UNCOV
4345

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

×
UNCOV
4350
        // Tell the switch to remove all links associated with this peer.
×
UNCOV
4351
        // Passing nil as the target link indicates that all links associated
×
UNCOV
4352
        // with this interface should be closed.
×
UNCOV
4353
        //
×
UNCOV
4354
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
×
UNCOV
4355
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
×
UNCOV
4356
        if err != nil && err != htlcswitch.ErrNoLinksFound {
×
4357
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4358
        }
×
4359

UNCOV
4360
        for _, link := range links {
×
UNCOV
4361
                s.htlcSwitch.RemoveLink(link.ChanID())
×
UNCOV
4362
        }
×
4363

UNCOV
4364
        s.mu.Lock()
×
UNCOV
4365
        defer s.mu.Unlock()
×
UNCOV
4366

×
UNCOV
4367
        // If there were any notification requests for when this peer
×
UNCOV
4368
        // disconnected, we can trigger them now.
×
UNCOV
4369
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4370
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4371
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4372
                close(offlineChan)
×
UNCOV
4373
        }
×
UNCOV
4374
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4375

×
UNCOV
4376
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4377
        // peer termination watcher and skip cleanup.
×
UNCOV
4378
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4379
                delete(s.ignorePeerTermination, p)
×
4380

×
4381
                pubKey := p.PubKey()
×
4382
                pubStr := string(pubKey[:])
×
4383

×
4384
                // If a connection callback is present, we'll go ahead and
×
4385
                // execute it now that previous peer has fully disconnected. If
×
4386
                // the callback is not present, this likely implies the peer was
×
4387
                // purposefully disconnected via RPC, and that no reconnect
×
4388
                // should be attempted.
×
4389
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4390
                if ok {
×
4391
                        delete(s.scheduledPeerConnection, pubStr)
×
4392
                        connCallback()
×
4393
                }
×
4394
                return
×
4395
        }
4396

4397
        // First, cleanup any remaining state the server has regarding the peer
4398
        // in question.
UNCOV
4399
        s.removePeer(p)
×
UNCOV
4400

×
UNCOV
4401
        // Next, check to see if this is a persistent peer or not.
×
UNCOV
4402
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4403
                return
×
UNCOV
4404
        }
×
4405

4406
        // Get the last address that we used to connect to the peer.
UNCOV
4407
        addrs := []net.Addr{
×
UNCOV
4408
                p.NetAddress().Address,
×
UNCOV
4409
        }
×
UNCOV
4410

×
UNCOV
4411
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4412
        // reconnection purposes.
×
UNCOV
4413
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
UNCOV
4414
        switch {
×
4415
        // We found advertised addresses, so use them.
UNCOV
4416
        case err == nil:
×
UNCOV
4417
                addrs = advertisedAddrs
×
4418

4419
        // The peer doesn't have an advertised address.
UNCOV
4420
        case err == errNoAdvertisedAddr:
×
UNCOV
4421
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4422
                // peer address.
×
UNCOV
4423
                if !p.Inbound() {
×
UNCOV
4424
                        break
×
4425
                }
4426

4427
                // Fall back to the existing peer address if
4428
                // we're not accepting connections over Tor.
UNCOV
4429
                if s.torController == nil {
×
UNCOV
4430
                        break
×
4431
                }
4432

4433
                // If we are, the peer's address won't be known
4434
                // to us (we'll see a private address, which is
4435
                // the address used by our onion service to dial
4436
                // to lnd), so we don't have enough information
4437
                // to attempt a reconnect.
4438
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4439
                        "to inbound peer %v without "+
×
4440
                        "advertised address", p)
×
4441
                return
×
4442

4443
        // We came across an error retrieving an advertised
4444
        // address, log it, and fall back to the existing peer
4445
        // address.
UNCOV
4446
        default:
×
UNCOV
4447
                srvrLog.Errorf("Unable to retrieve advertised "+
×
UNCOV
4448
                        "address for node %x: %v", p.PubKey(),
×
UNCOV
4449
                        err)
×
4450
        }
4451

4452
        // Make an easy lookup map so that we can check if an address
4453
        // is already in the address list that we have stored for this peer.
UNCOV
4454
        existingAddrs := make(map[string]bool)
×
UNCOV
4455
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4456
                existingAddrs[addr.String()] = true
×
UNCOV
4457
        }
×
4458

4459
        // Add any missing addresses for this peer to persistentPeerAddr.
UNCOV
4460
        for _, addr := range addrs {
×
UNCOV
4461
                if existingAddrs[addr.String()] {
×
4462
                        continue
×
4463
                }
4464

UNCOV
4465
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4466
                        s.persistentPeerAddrs[pubStr],
×
UNCOV
4467
                        &lnwire.NetAddress{
×
UNCOV
4468
                                IdentityKey: p.IdentityKey(),
×
UNCOV
4469
                                Address:     addr,
×
UNCOV
4470
                                ChainNet:    p.NetAddress().ChainNet,
×
UNCOV
4471
                        },
×
UNCOV
4472
                )
×
4473
        }
4474

4475
        // Record the computed backoff in the backoff map.
UNCOV
4476
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
×
UNCOV
4477
        s.persistentPeersBackoff[pubStr] = backoff
×
UNCOV
4478

×
UNCOV
4479
        // Initialize a retry canceller for this peer if one does not
×
UNCOV
4480
        // exist.
×
UNCOV
4481
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4482
        if !ok {
×
UNCOV
4483
                cancelChan = make(chan struct{})
×
UNCOV
4484
                s.persistentRetryCancels[pubStr] = cancelChan
×
UNCOV
4485
        }
×
4486

4487
        // We choose not to wait group this go routine since the Connect
4488
        // call can stall for arbitrarily long if we shutdown while an
4489
        // outbound connection attempt is being made.
UNCOV
4490
        go func() {
×
UNCOV
4491
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
UNCOV
4492
                        "persistent peer %x in %s",
×
UNCOV
4493
                        p.IdentityKey().SerializeCompressed(), backoff)
×
UNCOV
4494

×
UNCOV
4495
                select {
×
UNCOV
4496
                case <-time.After(backoff):
×
UNCOV
4497
                case <-cancelChan:
×
UNCOV
4498
                        return
×
UNCOV
4499
                case <-s.quit:
×
UNCOV
4500
                        return
×
4501
                }
4502

UNCOV
4503
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4504
                        "connection to peer %x",
×
UNCOV
4505
                        p.IdentityKey().SerializeCompressed())
×
UNCOV
4506

×
UNCOV
4507
                s.connectToPersistentPeer(pubStr)
×
4508
        }()
4509
}
4510

4511
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4512
// to connect to the peer. It creates connection requests if there are
4513
// currently none for a given address and it removes old connection requests
4514
// if the associated address is no longer in the latest address list for the
4515
// peer.
UNCOV
4516
func (s *server) connectToPersistentPeer(pubKeyStr string) {
×
UNCOV
4517
        s.mu.Lock()
×
UNCOV
4518
        defer s.mu.Unlock()
×
UNCOV
4519

×
UNCOV
4520
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4521
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4522
        // connection requests for the associated address and then any leftover
×
UNCOV
4523
        // entries will indicate which addresses we should create new
×
UNCOV
4524
        // connection requests for.
×
UNCOV
4525
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4526
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4527
                addrMap[addr.String()] = addr
×
UNCOV
4528
        }
×
4529

4530
        // Go through each of the existing connection requests and
4531
        // check if they correspond to the latest set of addresses. If
4532
        // there is a connection requests that does not use one of the latest
4533
        // advertised addresses then remove that connection request.
UNCOV
4534
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4535
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4536
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4537

×
UNCOV
4538
                switch _, ok := addrMap[lnAddr]; ok {
×
4539
                // If the existing connection request is using one of the
4540
                // latest advertised addresses for the peer then we add it to
4541
                // updatedConnReqs and remove the associated address from
4542
                // addrMap so that we don't recreate this connReq later on.
4543
                case true:
×
4544
                        updatedConnReqs = append(
×
4545
                                updatedConnReqs, connReq,
×
4546
                        )
×
4547
                        delete(addrMap, lnAddr)
×
4548

4549
                // If the existing connection request is using an address that
4550
                // is not one of the latest advertised addresses for the peer
4551
                // then we remove the connecting request from the connection
4552
                // manager.
UNCOV
4553
                case false:
×
UNCOV
4554
                        srvrLog.Info(
×
UNCOV
4555
                                "Removing conn req:", connReq.Addr.String(),
×
UNCOV
4556
                        )
×
UNCOV
4557
                        s.connMgr.Remove(connReq.ID())
×
4558
                }
4559
        }
4560

UNCOV
4561
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4562

×
UNCOV
4563
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4564
        if !ok {
×
UNCOV
4565
                cancelChan = make(chan struct{})
×
UNCOV
4566
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4567
        }
×
4568

4569
        // Any addresses left in addrMap are new ones that we have not made
4570
        // connection requests for. So create new connection requests for those.
4571
        // If there is more than one address in the address map, stagger the
4572
        // creation of the connection requests for those.
UNCOV
4573
        go func() {
×
UNCOV
4574
                ticker := time.NewTicker(multiAddrConnectionStagger)
×
UNCOV
4575
                defer ticker.Stop()
×
UNCOV
4576

×
UNCOV
4577
                for _, addr := range addrMap {
×
UNCOV
4578
                        // Send the persistent connection request to the
×
UNCOV
4579
                        // connection manager, saving the request itself so we
×
UNCOV
4580
                        // can cancel/restart the process as needed.
×
UNCOV
4581
                        connReq := &connmgr.ConnReq{
×
UNCOV
4582
                                Addr:      addr,
×
UNCOV
4583
                                Permanent: true,
×
UNCOV
4584
                        }
×
UNCOV
4585

×
UNCOV
4586
                        s.mu.Lock()
×
UNCOV
4587
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4588
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4589
                        )
×
UNCOV
4590
                        s.mu.Unlock()
×
UNCOV
4591

×
UNCOV
4592
                        srvrLog.Debugf("Attempting persistent connection to "+
×
UNCOV
4593
                                "channel peer %v", addr)
×
UNCOV
4594

×
UNCOV
4595
                        go s.connMgr.Connect(connReq)
×
UNCOV
4596

×
UNCOV
4597
                        select {
×
UNCOV
4598
                        case <-s.quit:
×
UNCOV
4599
                                return
×
UNCOV
4600
                        case <-cancelChan:
×
UNCOV
4601
                                return
×
UNCOV
4602
                        case <-ticker.C:
×
4603
                        }
4604
                }
4605
        }()
4606
}
4607

4608
// removePeer removes the passed peer from the server's state of all active
4609
// peers.
UNCOV
4610
func (s *server) removePeer(p *peer.Brontide) {
×
UNCOV
4611
        if p == nil {
×
4612
                return
×
4613
        }
×
4614

UNCOV
4615
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4616

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

×
UNCOV
4621
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4622
        if p.ConnReq() != nil {
×
UNCOV
4623
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4624
        }
×
4625

4626
        // Ignore deleting peers if we're shutting down.
UNCOV
4627
        if s.Stopped() {
×
4628
                return
×
4629
        }
×
4630

UNCOV
4631
        pKey := p.PubKey()
×
UNCOV
4632
        pubSer := pKey[:]
×
UNCOV
4633
        pubStr := string(pubSer)
×
UNCOV
4634

×
UNCOV
4635
        delete(s.peersByPub, pubStr)
×
UNCOV
4636

×
UNCOV
4637
        if p.Inbound() {
×
UNCOV
4638
                delete(s.inboundPeers, pubStr)
×
UNCOV
4639
        } else {
×
UNCOV
4640
                delete(s.outboundPeers, pubStr)
×
UNCOV
4641
        }
×
4642

4643
        // Copy the peer's error buffer across to the server if it has any items
4644
        // in it so that we can restore peer errors across connections.
UNCOV
4645
        if p.ErrorBuffer().Total() > 0 {
×
UNCOV
4646
                s.peerErrors[pubStr] = p.ErrorBuffer()
×
UNCOV
4647
        }
×
4648

4649
        // Inform the peer notifier of a peer offline event so that it can be
4650
        // reported to clients listening for peer events.
UNCOV
4651
        var pubKey [33]byte
×
UNCOV
4652
        copy(pubKey[:], pubSer)
×
UNCOV
4653

×
UNCOV
4654
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
4655
}
4656

4657
// ConnectToPeer requests that the server connect to a Lightning Network peer
4658
// at the specified address. This function will *block* until either a
4659
// connection is established, or the initial handshake process fails.
4660
//
4661
// NOTE: This function is safe for concurrent access.
4662
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
UNCOV
4663
        perm bool, timeout time.Duration) error {
×
UNCOV
4664

×
UNCOV
4665
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4666

×
UNCOV
4667
        // Acquire mutex, but use explicit unlocking instead of defer for
×
UNCOV
4668
        // better granularity.  In certain conditions, this method requires
×
UNCOV
4669
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4670
        // lock to be released, and subsequently reacquired.
×
UNCOV
4671
        s.mu.Lock()
×
UNCOV
4672

×
UNCOV
4673
        // Ensure we're not already connected to this peer.
×
UNCOV
4674
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4675
        if err == nil {
×
UNCOV
4676
                s.mu.Unlock()
×
UNCOV
4677
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4678
        }
×
4679

4680
        // Peer was not found, continue to pursue connection with peer.
4681

4682
        // If there's already a pending connection request for this pubkey,
4683
        // then we ignore this request to ensure we don't create a redundant
4684
        // connection.
UNCOV
4685
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
×
UNCOV
4686
                srvrLog.Warnf("Already have %d persistent connection "+
×
UNCOV
4687
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4688
        }
×
4689

4690
        // If there's not already a pending or active connection to this node,
4691
        // then instruct the connection manager to attempt to establish a
4692
        // persistent connection to the peer.
UNCOV
4693
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4694
        if perm {
×
UNCOV
4695
                connReq := &connmgr.ConnReq{
×
UNCOV
4696
                        Addr:      addr,
×
UNCOV
4697
                        Permanent: true,
×
UNCOV
4698
                }
×
UNCOV
4699

×
UNCOV
4700
                // Since the user requested a permanent connection, we'll set
×
UNCOV
4701
                // the entry to true which will tell the server to continue
×
UNCOV
4702
                // reconnecting even if the number of channels with this peer is
×
UNCOV
4703
                // zero.
×
UNCOV
4704
                s.persistentPeers[targetPub] = true
×
UNCOV
4705
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4706
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4707
                }
×
UNCOV
4708
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4709
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4710
                )
×
UNCOV
4711
                s.mu.Unlock()
×
UNCOV
4712

×
UNCOV
4713
                go s.connMgr.Connect(connReq)
×
UNCOV
4714

×
UNCOV
4715
                return nil
×
4716
        }
UNCOV
4717
        s.mu.Unlock()
×
UNCOV
4718

×
UNCOV
4719
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4720
        // connect to the target peer. If the we can't make the connection, or
×
UNCOV
4721
        // the crypto negotiation breaks down, then return an error to the
×
UNCOV
4722
        // caller.
×
UNCOV
4723
        errChan := make(chan error, 1)
×
UNCOV
4724
        s.connectToPeer(addr, errChan, timeout)
×
UNCOV
4725

×
UNCOV
4726
        select {
×
UNCOV
4727
        case err := <-errChan:
×
UNCOV
4728
                return err
×
4729
        case <-s.quit:
×
4730
                return ErrServerShuttingDown
×
4731
        }
4732
}
4733

4734
// connectToPeer establishes a connection to a remote peer. errChan is used to
4735
// notify the caller if the connection attempt has failed. Otherwise, it will be
4736
// closed.
4737
func (s *server) connectToPeer(addr *lnwire.NetAddress,
UNCOV
4738
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4739

×
UNCOV
4740
        conn, err := brontide.Dial(
×
UNCOV
4741
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4742
        )
×
UNCOV
4743
        if err != nil {
×
UNCOV
4744
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4745
                select {
×
UNCOV
4746
                case errChan <- err:
×
4747
                case <-s.quit:
×
4748
                }
UNCOV
4749
                return
×
4750
        }
4751

UNCOV
4752
        close(errChan)
×
UNCOV
4753

×
UNCOV
4754
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
4755
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4756

×
UNCOV
4757
        s.OutboundPeerConnected(nil, conn)
×
4758
}
4759

4760
// DisconnectPeer sends the request to server to close the connection with peer
4761
// identified by public key.
4762
//
4763
// NOTE: This function is safe for concurrent access.
UNCOV
4764
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
4765
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
4766
        pubStr := string(pubBytes)
×
UNCOV
4767

×
UNCOV
4768
        s.mu.Lock()
×
UNCOV
4769
        defer s.mu.Unlock()
×
UNCOV
4770

×
UNCOV
4771
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
4772
        // exit in an error as we can't disconnect from a peer that we're not
×
UNCOV
4773
        // currently connected to.
×
UNCOV
4774
        peer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
4775
        if err == ErrPeerNotConnected {
×
UNCOV
4776
                return fmt.Errorf("peer %x is not connected", pubBytes)
×
UNCOV
4777
        }
×
4778

UNCOV
4779
        srvrLog.Infof("Disconnecting from %v", peer)
×
UNCOV
4780

×
UNCOV
4781
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
4782

×
UNCOV
4783
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
4784
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
4785
        // disconnect.
×
UNCOV
4786
        delete(s.persistentPeers, pubStr)
×
UNCOV
4787
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
4788

×
UNCOV
4789
        // Remove the peer by calling Disconnect. Previously this was done with
×
UNCOV
4790
        // removePeer, which bypassed the peerTerminationWatcher.
×
UNCOV
4791
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
UNCOV
4792

×
UNCOV
4793
        return nil
×
4794
}
4795

4796
// OpenChannel sends a request to the server to open a channel to the specified
4797
// peer identified by nodeKey with the passed channel funding parameters.
4798
//
4799
// NOTE: This function is safe for concurrent access.
4800
func (s *server) OpenChannel(
UNCOV
4801
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
×
UNCOV
4802

×
UNCOV
4803
        // The updateChan will have a buffer of 2, since we expect a ChanPending
×
UNCOV
4804
        // + a ChanOpen update, and we want to make sure the funding process is
×
UNCOV
4805
        // not blocked if the caller is not reading the updates.
×
UNCOV
4806
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
4807
        req.Err = make(chan error, 1)
×
UNCOV
4808

×
UNCOV
4809
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
4810
        // we're unable to locate the peer then this request will fail.
×
UNCOV
4811
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
4812
        s.mu.RLock()
×
UNCOV
4813
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
4814
        if !ok {
×
4815
                s.mu.RUnlock()
×
4816

×
4817
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4818
                return req.Updates, req.Err
×
4819
        }
×
UNCOV
4820
        req.Peer = peer
×
UNCOV
4821
        s.mu.RUnlock()
×
UNCOV
4822

×
UNCOV
4823
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
4824
        // opening process.
×
UNCOV
4825
        select {
×
UNCOV
4826
        case <-peer.ActiveSignal():
×
4827
        case <-peer.QuitSignal():
×
4828
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4829
                return req.Updates, req.Err
×
4830
        case <-s.quit:
×
4831
                req.Err <- ErrServerShuttingDown
×
4832
                return req.Updates, req.Err
×
4833
        }
4834

4835
        // If the fee rate wasn't specified at this point we fail the funding
4836
        // because of the missing fee rate information. The caller of the
4837
        // `OpenChannel` method needs to make sure that default values for the
4838
        // fee rate are set beforehand.
UNCOV
4839
        if req.FundingFeePerKw == 0 {
×
4840
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
4841
                        "the channel opening transaction")
×
4842

×
4843
                return req.Updates, req.Err
×
4844
        }
×
4845

4846
        // Spawn a goroutine to send the funding workflow request to the funding
4847
        // manager. This allows the server to continue handling queries instead
4848
        // of blocking on this request which is exported as a synchronous
4849
        // request to the outside world.
UNCOV
4850
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
4851

×
UNCOV
4852
        return req.Updates, req.Err
×
4853
}
4854

4855
// Peers returns a slice of all active peers.
4856
//
4857
// NOTE: This function is safe for concurrent access.
UNCOV
4858
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
4859
        s.mu.RLock()
×
UNCOV
4860
        defer s.mu.RUnlock()
×
UNCOV
4861

×
UNCOV
4862
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
4863
        for _, peer := range s.peersByPub {
×
UNCOV
4864
                peers = append(peers, peer)
×
UNCOV
4865
        }
×
4866

UNCOV
4867
        return peers
×
4868
}
4869

4870
// computeNextBackoff uses a truncated exponential backoff to compute the next
4871
// backoff using the value of the exiting backoff. The returned duration is
4872
// randomized in either direction by 1/20 to prevent tight loops from
4873
// stabilizing.
UNCOV
4874
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
UNCOV
4875
        // Double the current backoff, truncating if it exceeds our maximum.
×
UNCOV
4876
        nextBackoff := 2 * currBackoff
×
UNCOV
4877
        if nextBackoff > maxBackoff {
×
UNCOV
4878
                nextBackoff = maxBackoff
×
UNCOV
4879
        }
×
4880

4881
        // Using 1/10 of our duration as a margin, compute a random offset to
4882
        // avoid the nodes entering connection cycles.
UNCOV
4883
        margin := nextBackoff / 10
×
UNCOV
4884

×
UNCOV
4885
        var wiggle big.Int
×
UNCOV
4886
        wiggle.SetUint64(uint64(margin))
×
UNCOV
4887
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
×
4888
                // Randomizing is not mission critical, so we'll just return the
×
4889
                // current backoff.
×
4890
                return nextBackoff
×
4891
        }
×
4892

4893
        // Otherwise add in our wiggle, but subtract out half of the margin so
4894
        // that the backoff can tweaked by 1/20 in either direction.
UNCOV
4895
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
4896
}
4897

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

4902
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
UNCOV
4903
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
4904
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
4905
        if err != nil {
×
4906
                return nil, err
×
4907
        }
×
4908

UNCOV
4909
        node, err := s.graphDB.FetchLightningNode(vertex)
×
UNCOV
4910
        if err != nil {
×
UNCOV
4911
                return nil, err
×
UNCOV
4912
        }
×
4913

UNCOV
4914
        if len(node.Addresses) == 0 {
×
UNCOV
4915
                return nil, errNoAdvertisedAddr
×
UNCOV
4916
        }
×
4917

UNCOV
4918
        return node.Addresses, nil
×
4919
}
4920

4921
// fetchLastChanUpdate returns a function which is able to retrieve our latest
4922
// channel update for a target channel.
4923
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
UNCOV
4924
        *lnwire.ChannelUpdate1, error) {
×
UNCOV
4925

×
UNCOV
4926
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
4927
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
4928
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
4929
                if err != nil {
×
UNCOV
4930
                        return nil, err
×
UNCOV
4931
                }
×
4932

UNCOV
4933
                return netann.ExtractChannelUpdate(
×
UNCOV
4934
                        ourPubKey[:], info, edge1, edge2,
×
UNCOV
4935
                )
×
4936
        }
4937
}
4938

4939
// applyChannelUpdate applies the channel update to the different sub-systems of
4940
// the server. The useAlias boolean denotes whether or not to send an alias in
4941
// place of the real SCID.
4942
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
UNCOV
4943
        op *wire.OutPoint, useAlias bool) error {
×
UNCOV
4944

×
UNCOV
4945
        var (
×
UNCOV
4946
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
4947
                defaultAlias lnwire.ShortChannelID
×
UNCOV
4948
        )
×
UNCOV
4949

×
UNCOV
4950
        chanID := lnwire.NewChanIDFromOutPoint(*op)
×
UNCOV
4951

×
UNCOV
4952
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
4953
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
4954
        if useAlias {
×
UNCOV
4955
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
×
UNCOV
4956
                if foundAlias != defaultAlias {
×
UNCOV
4957
                        peerAlias = &foundAlias
×
UNCOV
4958
                }
×
4959
        }
4960

UNCOV
4961
        errChan := s.authGossiper.ProcessLocalAnnouncement(
×
UNCOV
4962
                update, discovery.RemoteAlias(peerAlias),
×
UNCOV
4963
        )
×
UNCOV
4964
        select {
×
UNCOV
4965
        case err := <-errChan:
×
UNCOV
4966
                return err
×
4967
        case <-s.quit:
×
4968
                return ErrServerShuttingDown
×
4969
        }
4970
}
4971

4972
// SendCustomMessage sends a custom message to the peer with the specified
4973
// pubkey.
4974
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
4975
        data []byte) error {
×
UNCOV
4976

×
UNCOV
4977
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
UNCOV
4978
        if err != nil {
×
4979
                return err
×
4980
        }
×
4981

4982
        // We'll wait until the peer is active.
UNCOV
4983
        select {
×
UNCOV
4984
        case <-peer.ActiveSignal():
×
4985
        case <-peer.QuitSignal():
×
4986
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4987
        case <-s.quit:
×
4988
                return ErrServerShuttingDown
×
4989
        }
4990

UNCOV
4991
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
4992
        if err != nil {
×
UNCOV
4993
                return err
×
UNCOV
4994
        }
×
4995

4996
        // Send the message as low-priority. For now we assume that all
4997
        // application-defined message are low priority.
UNCOV
4998
        return peer.SendMessageLazy(true, msg)
×
4999
}
5000

5001
// newSweepPkScriptGen creates closure that generates a new public key script
5002
// which should be used to sweep any funds into the on-chain wallet.
5003
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5004
// (p2wkh) output.
5005
func newSweepPkScriptGen(
5006
        wallet lnwallet.WalletController,
UNCOV
5007
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5008

×
UNCOV
5009
        return func() fn.Result[lnwallet.AddrWithKey] {
×
UNCOV
5010
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
5011
                        lnwallet.TaprootPubkey, false,
×
UNCOV
5012
                        lnwallet.DefaultAccountName,
×
UNCOV
5013
                )
×
UNCOV
5014
                if err != nil {
×
5015
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5016
                }
×
5017

UNCOV
5018
                addr, err := txscript.PayToAddrScript(sweepAddr)
×
UNCOV
5019
                if err != nil {
×
5020
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5021
                }
×
5022

UNCOV
5023
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
×
UNCOV
5024
                        wallet, netParams, addr,
×
UNCOV
5025
                )
×
UNCOV
5026
                if err != nil {
×
5027
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5028
                }
×
5029

UNCOV
5030
                return fn.Ok(lnwallet.AddrWithKey{
×
UNCOV
5031
                        DeliveryAddress: addr,
×
UNCOV
5032
                        InternalKey:     internalKeyDesc,
×
UNCOV
5033
                })
×
5034
        }
5035
}
5036

5037
// shouldPeerBootstrap returns true if we should attempt to perform peer
5038
// bootstrapping to actively seek our peers using the set of active network
5039
// bootstrappers.
5040
func shouldPeerBootstrap(cfg *Config) bool {
6✔
5041
        isSimnet := cfg.Bitcoin.SimNet
6✔
5042
        isSignet := cfg.Bitcoin.SigNet
6✔
5043
        isRegtest := cfg.Bitcoin.RegTest
6✔
5044
        isDevNetwork := isSimnet || isSignet || isRegtest
6✔
5045

6✔
5046
        // TODO(yy): remove the check on simnet/regtest such that the itest is
6✔
5047
        // covering the bootstrapping process.
6✔
5048
        return !cfg.NoNetBootstrap && !isDevNetwork
6✔
5049
}
6✔
5050

5051
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5052
// finished.
UNCOV
5053
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
×
UNCOV
5054
        // Get a list of closed channels.
×
UNCOV
5055
        channels, err := s.chanStateDB.FetchClosedChannels(false)
×
UNCOV
5056
        if err != nil {
×
5057
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5058
                return nil
×
5059
        }
×
5060

5061
        // Save the SCIDs in a map.
UNCOV
5062
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
×
UNCOV
5063
        for _, c := range channels {
×
UNCOV
5064
                // If the channel is not pending, its FC has been finalized.
×
UNCOV
5065
                if !c.IsPending {
×
UNCOV
5066
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
5067
                }
×
5068
        }
5069

5070
        // Double check whether the reported closed channel has indeed finished
5071
        // closing.
5072
        //
5073
        // NOTE: There are misalignments regarding when a channel's FC is
5074
        // marked as finalized. We double check the pending channels to make
5075
        // sure the returned SCIDs are indeed terminated.
5076
        //
5077
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
UNCOV
5078
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5079
        if err != nil {
×
5080
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5081
                return nil
×
5082
        }
×
5083

UNCOV
5084
        for _, c := range pendings {
×
UNCOV
5085
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5086
                        continue
×
5087
                }
5088

5089
                // If the channel is still reported as pending, remove it from
5090
                // the map.
5091
                delete(closedSCIDs, c.ShortChannelID)
×
5092

×
5093
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5094
                        c.ShortChannelID)
×
5095
        }
5096

UNCOV
5097
        return closedSCIDs
×
5098
}
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