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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

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

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

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

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

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

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

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

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

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

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

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

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

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

158
        start sync.Once
159
        stop  sync.Once
160

161
        cfg *Config
162

163
        implCfg *ImplementationCfg
164

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

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

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

176
        chanStatusMgr *netann.ChanStatusManager
177

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

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

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

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

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

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

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

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

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

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

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

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

242
        cc *chainreg.ChainControl
243

244
        fundingMgr *funding.Manager
245

246
        graphDB *channeldb.ChannelGraph
247

248
        chanStateDB *channeldb.ChannelStateDB
249

250
        addrSource chanbackup.AddressSource
251

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

256
        invoicesDB invoices.InvoiceDB
257

258
        aliasMgr *aliasmgr.Manager
259

260
        htlcSwitch *htlcswitch.Switch
261

262
        interceptableSwitch *htlcswitch.InterceptableSwitch
263

264
        invoices *invoices.InvoiceRegistry
265

266
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
267

268
        channelNotifier *channelnotifier.ChannelNotifier
269

270
        peerNotifier *peernotifier.PeerNotifier
271

272
        htlcNotifier *htlcswitch.HtlcNotifier
273

274
        witnessBeacon contractcourt.WitnessBeacon
275

276
        breachArbitrator *contractcourt.BreachArbitrator
277

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

281
        graphBuilder *graph.Builder
282

283
        chanRouter *routing.ChannelRouter
284

285
        controlTower routing.ControlTower
286

287
        authGossiper *discovery.AuthenticatedGossiper
288

289
        localChanMgr *localchans.Manager
290

291
        utxoNursery *contractcourt.UtxoNursery
292

293
        sweeper *sweep.UtxoSweeper
294

295
        chainArb *contractcourt.ChainArbitrator
296

297
        sphinx *hop.OnionProcessor
298

299
        towerClientMgr *wtclient.Manager
300

301
        connMgr *connmgr.ConnManager
302

303
        sigPool *lnwallet.SigPool
304

305
        writePool *pool.Write
306

307
        readPool *pool.Read
308

309
        tlsManager *TLSManager
310

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

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

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

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

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

333
        hostAnn *netann.HostAnnouncer
334

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

338
        customMessageServer *subscribe.Server
339

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

343
        quit chan struct{}
344

345
        wg sync.WaitGroup
346
}
347

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

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

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

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

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

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

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

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

×
403
                                        s.mu.Lock()
UNCOV
404

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

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

419
                                        s.mu.Unlock()
UNCOV
420

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

427
        return nil
UNCOV
428
}
×
429

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
530
        writeBufferPool := pool.NewWriteBuffer(
×
UNCOV
531
                pool.DefaultWriteBufferGCInterval,
×
UNCOV
532
                pool.DefaultWriteBufferExpiryInterval,
×
UNCOV
533
        )
×
UNCOV
534

×
UNCOV
535
        writePool := pool.NewWrite(
×
UNCOV
536
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
×
UNCOV
537
        )
×
UNCOV
538

×
UNCOV
539
        readBufferPool := pool.NewReadBuffer(
×
UNCOV
540
                pool.DefaultReadBufferGCInterval,
×
UNCOV
541
                pool.DefaultReadBufferExpiryInterval,
×
UNCOV
542
        )
×
UNCOV
543

×
UNCOV
544
        readPool := pool.NewRead(
×
UNCOV
545
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
×
UNCOV
546
        )
×
UNCOV
547

×
UNCOV
548
        //nolint:lll
×
UNCOV
549
        featureMgr, err := feature.NewManager(feature.Config{
×
UNCOV
550
                NoTLVOnion:               cfg.ProtocolOptions.LegacyOnion(),
×
UNCOV
551
                NoStaticRemoteKey:        cfg.ProtocolOptions.NoStaticRemoteKey(),
×
UNCOV
552
                NoAnchors:                cfg.ProtocolOptions.NoAnchorCommitments(),
×
UNCOV
553
                NoWumbo:                  !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
554
                NoScriptEnforcementLease: cfg.ProtocolOptions.NoScriptEnforcementLease(),
×
UNCOV
555
                NoKeysend:                !cfg.AcceptKeySend,
×
UNCOV
556
                NoOptionScidAlias:        !cfg.ProtocolOptions.ScidAlias(),
×
UNCOV
557
                NoZeroConf:               !cfg.ProtocolOptions.ZeroConf(),
×
UNCOV
558
                NoAnySegwit:              cfg.ProtocolOptions.NoAnySegwit(),
×
559
                CustomFeatures:           cfg.ProtocolOptions.CustomFeatures(),
560
                NoTaprootChans:           !cfg.ProtocolOptions.TaprootChans,
UNCOV
561
                NoRouteBlinding:          cfg.ProtocolOptions.NoRouteBlinding(),
×
UNCOV
562
        })
×
UNCOV
563
        if err != nil {
×
564
                return nil, err
×
565
        }
×
UNCOV
566

×
UNCOV
567
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
×
UNCOV
568
        registryConfig := invoices.RegistryConfig{
×
UNCOV
569
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
×
UNCOV
570
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
×
UNCOV
571
                Clock:                       clock.NewDefaultClock(),
×
UNCOV
572
                AcceptKeySend:               cfg.AcceptKeySend,
×
UNCOV
573
                AcceptAMP:                   cfg.AcceptAMP,
×
UNCOV
574
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
×
UNCOV
575
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
×
UNCOV
576
                KeysendHoldTime:             cfg.KeysendHoldTime,
×
UNCOV
577
                HtlcInterceptor:             invoiceHtlcModifier,
×
UNCOV
578
        }
×
579

UNCOV
580
        s := &server{
×
UNCOV
581
                cfg:            cfg,
×
UNCOV
582
                implCfg:        implCfg,
×
UNCOV
583
                graphDB:        dbs.GraphDB.ChannelGraph(),
×
UNCOV
584
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
585
                addrSource:     dbs.ChanStateDB,
×
UNCOV
586
                miscDB:         dbs.ChanStateDB,
×
UNCOV
587
                invoicesDB:     dbs.InvoiceDB,
×
UNCOV
588
                cc:             cc,
×
UNCOV
589
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
×
UNCOV
590
                writePool:      writePool,
×
UNCOV
591
                readPool:       readPool,
×
UNCOV
592
                chansToRestore: chansToRestore,
×
UNCOV
593

×
UNCOV
594
                channelNotifier: channelnotifier.New(
×
UNCOV
595
                        dbs.ChanStateDB.ChannelStateDB(),
×
UNCOV
596
                ),
×
UNCOV
597

×
UNCOV
598
                identityECDH:   nodeKeyECDH,
×
UNCOV
599
                identityKeyLoc: nodeKeyDesc.KeyLocator,
×
UNCOV
600
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
×
UNCOV
601

×
UNCOV
602
                listenAddrs: listenAddrs,
×
UNCOV
603

×
UNCOV
604
                // TODO(roasbeef): derive proper onion key based on rotation
×
UNCOV
605
                // schedule
×
UNCOV
606
                sphinx: hop.NewOnionProcessor(sphinxRouter),
×
UNCOV
607

×
UNCOV
608
                torController: torController,
×
UNCOV
609

×
UNCOV
610
                persistentPeers:         make(map[string]bool),
×
UNCOV
611
                persistentPeersBackoff:  make(map[string]time.Duration),
×
UNCOV
612
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
×
UNCOV
613
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
×
UNCOV
614
                persistentRetryCancels:  make(map[string]chan struct{}),
×
UNCOV
615
                peerErrors:              make(map[string]*queue.CircularBuffer),
×
UNCOV
616
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
×
UNCOV
617
                scheduledPeerConnection: make(map[string]func()),
×
UNCOV
618
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
×
UNCOV
619

×
UNCOV
620
                peersByPub:                make(map[string]*peer.Brontide),
×
UNCOV
621
                inboundPeers:              make(map[string]*peer.Brontide),
×
UNCOV
622
                outboundPeers:             make(map[string]*peer.Brontide),
×
UNCOV
623
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
×
UNCOV
624
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
×
UNCOV
625

×
UNCOV
626
                invoiceHtlcModifier: invoiceHtlcModifier,
×
UNCOV
627

×
UNCOV
628
                customMessageServer: subscribe.NewServer(),
×
UNCOV
629

×
UNCOV
630
                tlsManager: tlsManager,
×
UNCOV
631

×
UNCOV
632
                featureMgr: featureMgr,
×
UNCOV
633
                quit:       make(chan struct{}),
×
UNCOV
634
        }
×
UNCOV
635

×
UNCOV
636
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
×
UNCOV
637
        if err != nil {
×
638
                return nil, err
×
639
        }
×
UNCOV
640

×
UNCOV
641
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
×
UNCOV
642
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
×
UNCOV
643
                uint32(currentHeight), currentHash, cc.ChainNotifier,
×
UNCOV
644
        )
×
UNCOV
645
        s.invoices = invoices.NewRegistry(
×
UNCOV
646
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
×
UNCOV
647
        )
×
UNCOV
648

×
UNCOV
649
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
×
UNCOV
650

×
UNCOV
651
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
×
UNCOV
652
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
653

UNCOV
654
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
×
UNCOV
655
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
×
UNCOV
656
                if err != nil {
×
657
                        return err
×
658
                }
×
UNCOV
659

×
UNCOV
660
                s.htlcSwitch.UpdateLinkAliases(link)
×
UNCOV
661

×
UNCOV
662
                return nil
×
UNCOV
663
        }
×
UNCOV
664

×
UNCOV
665
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
×
UNCOV
666
        if err != nil {
×
667
                return nil, err
×
668
        }
×
UNCOV
669

×
UNCOV
670
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
×
UNCOV
671
                DB:                   dbs.ChanStateDB,
×
672
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
UNCOV
673
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
×
UNCOV
674
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
×
UNCOV
675
                LocalChannelClose: func(pubKey []byte,
×
676
                        request *htlcswitch.ChanClose) {
677

UNCOV
678
                        peer, err := s.FindPeerByPubStr(string(pubKey))
×
UNCOV
679
                        if err != nil {
×
680
                                srvrLog.Errorf("unable to close channel, peer"+
×
681
                                        " with %v id can't be found: %v",
×
682
                                        pubKey, err,
683
                                )
×
684
                                return
×
685
                        }
×
UNCOV
686

×
UNCOV
687
                        peer.HandleLocalCloseChanReqs(request)
×
UNCOV
688
                },
×
UNCOV
689
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
×
UNCOV
690
                SwitchPackager:         channeldb.NewSwitchPackager(),
×
UNCOV
691
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
×
UNCOV
692
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
×
UNCOV
693
                Notifier:               s.cc.ChainNotifier,
×
UNCOV
694
                HtlcNotifier:           s.htlcNotifier,
×
UNCOV
695
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
×
UNCOV
696
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
×
UNCOV
697
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
×
UNCOV
698
                AllowCircularRoute:     cfg.AllowCircularRoute,
×
699
                RejectHTLC:             cfg.RejectHTLC,
UNCOV
700
                Clock:                  clock.NewDefaultClock(),
×
701
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
702
                MaxFeeExposure:         thresholdMSats,
703
                SignAliasUpdate:        s.signAliasUpdate,
704
                IsAlias:                aliasmgr.IsAlias,
705
        }, uint32(currentHeight))
706
        if err != nil {
707
                return nil, err
708
        }
709
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
710
                &htlcswitch.InterceptableSwitchConfig{
711
                        Switch:             s.htlcSwitch,
712
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
713
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
714
                        RequireInterceptor: s.cfg.RequireInterceptor,
715
                        Notifier:           s.cc.ChainNotifier,
716
                },
717
        )
718
        if err != nil {
719
                return nil, err
×
720
        }
×
UNCOV
721

×
UNCOV
722
        s.witnessBeacon = newPreimageBeacon(
×
UNCOV
723
                dbs.ChanStateDB.NewWitnessCache(),
×
UNCOV
724
                s.interceptableSwitch.ForwardPacket,
×
UNCOV
725
        )
×
UNCOV
726

×
UNCOV
727
        chanStatusMgrCfg := &netann.ChanStatusConfig{
×
UNCOV
728
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
×
UNCOV
729
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
×
UNCOV
730
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
×
UNCOV
731
                OurPubKey:                nodeKeyDesc.PubKey,
×
UNCOV
732
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
×
UNCOV
733
                MessageSigner:            s.nodeSigner,
×
734
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
UNCOV
735
                ApplyChannelUpdate:       s.applyChannelUpdate,
×
UNCOV
736
                DB:                       s.chanStateDB,
×
UNCOV
737
                Graph:                    dbs.GraphDB.ChannelGraph(),
×
UNCOV
738
        }
×
UNCOV
739

×
UNCOV
740
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
×
UNCOV
741
        if err != nil {
×
742
                return nil, err
×
743
        }
×
UNCOV
744
        s.chanStatusMgr = chanStatusMgr
×
UNCOV
745

×
UNCOV
746
        // If enabled, use either UPnP or NAT-PMP to automatically configure
×
UNCOV
747
        // port forwarding for users behind a NAT.
×
UNCOV
748
        if cfg.NAT {
×
749
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
750

×
751
                discoveryTimeout := time.Duration(10 * time.Second)
×
752

×
753
                ctx, cancel := context.WithTimeout(
×
754
                        context.Background(), discoveryTimeout,
×
755
                )
×
756
                defer cancel()
×
757
                upnp, err := nat.DiscoverUPnP(ctx)
×
758
                if err == nil {
×
759
                        s.natTraversal = upnp
×
760
                } else {
×
761
                        // If we were not able to discover a UPnP enabled device
×
762
                        // on the local network, we'll fall back to attempting
×
763
                        // to discover a NAT-PMP enabled device.
×
764
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
765
                                "device on the local network: %v", err)
×
766

×
767
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
768
                                "enabled device")
×
769

×
770
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
771
                        if err != nil {
×
772
                                err := fmt.Errorf("unable to discover a "+
×
773
                                        "NAT-PMP enabled device on the local "+
×
774
                                        "network: %v", err)
×
775
                                srvrLog.Error(err)
×
776
                                return nil, err
×
777
                        }
×
UNCOV
778

×
779
                        s.natTraversal = pmp
×
UNCOV
780
                }
×
UNCOV
781
        }
×
UNCOV
782

×
UNCOV
783
        // If we were requested to automatically configure port forwarding,
×
UNCOV
784
        // we'll use the ports that the server will be listening on.
×
UNCOV
785
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
×
UNCOV
786
        for idx, ip := range cfg.ExternalIPs {
×
UNCOV
787
                externalIPStrings[idx] = ip.String()
×
UNCOV
788
        }
×
UNCOV
789
        if s.natTraversal != nil {
×
790
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
791
                for _, listenAddr := range listenAddrs {
792
                        // At this point, the listen addresses should have
×
793
                        // already been normalized, so it's safe to ignore the
794
                        // errors.
795
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
796
                        port, _ := strconv.Atoi(portStr)
797

798
                        listenPorts = append(listenPorts, uint16(port))
×
799
                }
×
UNCOV
800

×
801
                ips, err := s.configurePortForwarding(listenPorts...)
×
802
                if err != nil {
×
803
                        srvrLog.Errorf("Unable to automatically set up port "+
×
804
                                "forwarding using %s: %v",
×
805
                                s.natTraversal.Name(), err)
×
806
                } else {
×
807
                        srvrLog.Infof("Automatically set up port forwarding "+
×
808
                                "using %s to advertise external IP",
×
809
                                s.natTraversal.Name())
×
810
                        externalIPStrings = append(externalIPStrings, ips...)
×
811
                }
×
UNCOV
812
        }
×
813

UNCOV
814
        // If external IP addresses have been specified, add those to the list
×
UNCOV
815
        // of this server's addresses.
×
UNCOV
816
        externalIPs, err := lncfg.NormalizeAddresses(
×
UNCOV
817
                externalIPStrings, strconv.Itoa(defaultPeerPort),
×
UNCOV
818
                cfg.net.ResolveTCPAddr,
×
UNCOV
819
        )
×
UNCOV
820
        if err != nil {
×
821
                return nil, err
×
822
        }
×
UNCOV
823

×
UNCOV
824
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
×
825
        selfAddrs = append(selfAddrs, externalIPs...)
826

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

×
UNCOV
831
        // We'll now reconstruct a node announcement based on our current
×
UNCOV
832
        // configuration so we can send it out as a sort of heart beat within
×
UNCOV
833
        // the network.
×
UNCOV
834
        //
×
UNCOV
835
        // We'll start by parsing the node color from configuration.
×
836
        color, err := lncfg.ParseHexColor(cfg.Color)
UNCOV
837
        if err != nil {
×
838
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
839
                return nil, err
×
840
        }
×
UNCOV
841

×
UNCOV
842
        // If no alias is provided, default to first 10 characters of public
×
UNCOV
843
        // key.
×
UNCOV
844
        alias := cfg.Alias
×
UNCOV
845
        if alias == "" {
×
UNCOV
846
                alias = hex.EncodeToString(serializedPubKey[:10])
×
UNCOV
847
        }
×
UNCOV
848
        nodeAlias, err := lnwire.NewNodeAlias(alias)
×
UNCOV
849
        if err != nil {
×
850
                return nil, err
×
851
        }
×
UNCOV
852
        selfNode := &channeldb.LightningNode{
×
UNCOV
853
                HaveNodeAnnouncement: true,
×
854
                LastUpdate:           time.Now(),
855
                Addresses:            selfAddrs,
856
                Alias:                nodeAlias.String(),
UNCOV
857
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
×
UNCOV
858
                Color:                color,
×
UNCOV
859
        }
×
UNCOV
860
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
×
UNCOV
861

×
UNCOV
862
        // Based on the disk representation of the node announcement generated
×
UNCOV
863
        // above, we'll generate a node announcement that can go out on the
×
UNCOV
864
        // network so we can properly sign it.
×
UNCOV
865
        nodeAnn, err := selfNode.NodeAnnouncement(false)
×
UNCOV
866
        if err != nil {
×
867
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
868
        }
×
UNCOV
869

×
UNCOV
870
        // With the announcement generated, we'll sign it to properly
×
UNCOV
871
        // authenticate the message on the network.
×
UNCOV
872
        authSig, err := netann.SignAnnouncement(
×
UNCOV
873
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
×
UNCOV
874
        )
×
UNCOV
875
        if err != nil {
×
876
                return nil, fmt.Errorf("unable to generate signature for "+
×
877
                        "self node announcement: %v", err)
×
878
        }
×
UNCOV
879
        selfNode.AuthSigBytes = authSig.Serialize()
×
UNCOV
880
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
×
UNCOV
881
                selfNode.AuthSigBytes,
×
882
        )
883
        if err != nil {
884
                return nil, err
885
        }
×
UNCOV
886

×
UNCOV
887
        // Finally, we'll update the representation on disk, and update our
×
UNCOV
888
        // cached in-memory version as well.
×
UNCOV
889
        if err := chanGraph.SetSourceNode(selfNode); err != nil {
×
890
                return nil, fmt.Errorf("can't set self node: %w", err)
×
891
        }
×
UNCOV
892
        s.currentNodeAnn = nodeAnn
×
UNCOV
893

×
UNCOV
894
        // The router will get access to the payment ID sequencer, such that it
×
UNCOV
895
        // can generate unique payment IDs.
×
UNCOV
896
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
×
UNCOV
897
        if err != nil {
×
898
                return nil, err
×
899
        }
900

901
        // Instantiate mission control with config from the sub server.
UNCOV
902
        //
×
UNCOV
903
        // TODO(joostjager): When we are further in the process of moving to sub
×
UNCOV
904
        // servers, the mission control instance itself can be moved there too.
×
UNCOV
905
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
×
UNCOV
906

×
UNCOV
907
        // We only initialize a probability estimator if there's no custom one.
×
UNCOV
908
        var estimator routing.Estimator
×
UNCOV
909
        if cfg.Estimator != nil {
×
910
                estimator = cfg.Estimator
×
UNCOV
911
        } else {
×
UNCOV
912
                switch routingConfig.ProbabilityEstimatorType {
×
913
                case routing.AprioriEstimatorName:
914
                        aCfg := routingConfig.AprioriConfig
915
                        aprioriConfig := routing.AprioriConfig{
916
                                AprioriHopProbability: aCfg.HopProbability,
917
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
UNCOV
918
                                AprioriWeight:         aCfg.Weight,
×
UNCOV
919
                                CapacityFraction:      aCfg.CapacityFraction,
×
UNCOV
920
                        }
×
UNCOV
921

×
UNCOV
922
                        estimator, err = routing.NewAprioriEstimator(
×
UNCOV
923
                                aprioriConfig,
×
UNCOV
924
                        )
×
UNCOV
925
                        if err != nil {
×
926
                                return nil, err
×
927
                        }
×
UNCOV
928

×
929
                case routing.BimodalEstimatorName:
×
930
                        bCfg := routingConfig.BimodalConfig
×
931
                        bimodalConfig := routing.BimodalConfig{
×
932
                                BimodalNodeWeight: bCfg.NodeWeight,
×
933
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
934
                                        bCfg.Scale,
×
935
                                ),
×
936
                                BimodalDecayTime: bCfg.DecayTime,
×
937
                        }
×
938

×
939
                        estimator, err = routing.NewBimodalEstimator(
×
940
                                bimodalConfig,
×
941
                        )
942
                        if err != nil {
×
943
                                return nil, err
×
944
                        }
×
UNCOV
945

×
946
                default:
×
947
                        return nil, fmt.Errorf("unknown estimator type %v",
×
948
                                routingConfig.ProbabilityEstimatorType)
×
UNCOV
949
                }
×
UNCOV
950
        }
×
UNCOV
951

×
UNCOV
952
        mcCfg := &routing.MissionControlConfig{
×
UNCOV
953
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
×
UNCOV
954
                Estimator:               estimator,
×
UNCOV
955
                MaxMcHistory:            routingConfig.MaxMcHistory,
×
UNCOV
956
                McFlushInterval:         routingConfig.McFlushInterval,
×
UNCOV
957
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
×
958
        }
UNCOV
959

×
UNCOV
960
        s.missionController, err = routing.NewMissionController(
×
UNCOV
961
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
×
962
        )
963
        if err != nil {
964
                return nil, fmt.Errorf("can't create mission control "+
965
                        "manager: %w", err)
×
966
        }
×
UNCOV
967
        s.defaultMC, err = s.missionController.GetNamespacedStore(
×
UNCOV
968
                routing.DefaultMissionControlNamespace,
×
UNCOV
969
        )
×
UNCOV
970
        if err != nil {
×
971
                return nil, fmt.Errorf("can't create mission control in the "+
×
972
                        "default namespace: %w", err)
×
973
        }
×
UNCOV
974

×
UNCOV
975
        srvrLog.Debugf("Instantiating payment session source with config: "+
×
UNCOV
976
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
×
UNCOV
977
                int64(routingConfig.AttemptCost),
×
UNCOV
978
                float64(routingConfig.AttemptCostPPM)/10000,
×
UNCOV
979
                routingConfig.MinRouteProbability)
×
UNCOV
980

×
UNCOV
981
        pathFindingConfig := routing.PathFindingConfig{
×
UNCOV
982
                AttemptCost: lnwire.NewMSatFromSatoshis(
×
UNCOV
983
                        routingConfig.AttemptCost,
×
UNCOV
984
                ),
×
UNCOV
985
                AttemptCostPPM: routingConfig.AttemptCostPPM,
×
UNCOV
986
                MinProbability: routingConfig.MinRouteProbability,
×
987
        }
UNCOV
988

×
UNCOV
989
        sourceNode, err := chanGraph.SourceNode()
×
UNCOV
990
        if err != nil {
×
991
                return nil, fmt.Errorf("error getting source node: %w", err)
×
992
        }
×
UNCOV
993
        paymentSessionSource := &routing.SessionSource{
×
UNCOV
994
                GraphSessionFactory: graphsession.NewGraphSessionFactory(
×
UNCOV
995
                        chanGraph,
×
UNCOV
996
                ),
×
UNCOV
997
                SourceNode:        sourceNode,
×
UNCOV
998
                MissionControl:    s.defaultMC,
×
UNCOV
999
                GetLink:           s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1000
                PathFindingConfig: pathFindingConfig,
×
UNCOV
1001
        }
×
UNCOV
1002

×
UNCOV
1003
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
×
UNCOV
1004

×
UNCOV
1005
        s.controlTower = routing.NewControlTower(paymentControl)
×
UNCOV
1006

×
UNCOV
1007
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
×
UNCOV
1008
                cfg.Routing.StrictZombiePruning
×
UNCOV
1009

×
UNCOV
1010
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
×
UNCOV
1011
                SelfNode:            selfNode.PubKeyBytes,
×
UNCOV
1012
                Graph:               chanGraph,
×
UNCOV
1013
                Chain:               cc.ChainIO,
×
UNCOV
1014
                ChainView:           cc.ChainView,
×
UNCOV
1015
                Notifier:            cc.ChainNotifier,
×
UNCOV
1016
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
×
UNCOV
1017
                GraphPruneInterval:  time.Hour,
×
UNCOV
1018
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
×
UNCOV
1019
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
×
UNCOV
1020
                StrictZombiePruning: strictPruning,
×
UNCOV
1021
                IsAlias:             aliasmgr.IsAlias,
×
UNCOV
1022
        })
×
UNCOV
1023
        if err != nil {
×
1024
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1025
        }
×
UNCOV
1026

×
UNCOV
1027
        s.chanRouter, err = routing.New(routing.Config{
×
UNCOV
1028
                SelfNode:           selfNode.PubKeyBytes,
×
UNCOV
1029
                RoutingGraph:       graphsession.NewRoutingGraph(chanGraph),
×
UNCOV
1030
                Chain:              cc.ChainIO,
×
UNCOV
1031
                Payer:              s.htlcSwitch,
×
UNCOV
1032
                Control:            s.controlTower,
×
UNCOV
1033
                MissionControl:     s.defaultMC,
×
UNCOV
1034
                SessionSource:      paymentSessionSource,
×
UNCOV
1035
                GetLink:            s.htlcSwitch.GetLinkByShortID,
×
UNCOV
1036
                NextPaymentID:      sequencer.NextID,
×
UNCOV
1037
                PathFindingConfig:  pathFindingConfig,
×
UNCOV
1038
                Clock:              clock.NewDefaultClock(),
×
1039
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
UNCOV
1040
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
×
UNCOV
1041
                TrafficShaper:      implCfg.TrafficShaper,
×
UNCOV
1042
        })
×
UNCOV
1043
        if err != nil {
×
1044
                return nil, fmt.Errorf("can't create router: %w", err)
×
1045
        }
×
UNCOV
1046

×
UNCOV
1047
        chanSeries := discovery.NewChanSeries(s.graphDB)
×
UNCOV
1048
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
×
UNCOV
1049
        if err != nil {
×
1050
                return nil, err
×
1051
        }
×
UNCOV
1052
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
×
UNCOV
1053
        if err != nil {
×
1054
                return nil, err
×
1055
        }
×
UNCOV
1056

×
UNCOV
1057
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
×
UNCOV
1058

×
1059
        s.authGossiper = discovery.New(discovery.Config{
UNCOV
1060
                Graph:                 s.graphBuilder,
×
UNCOV
1061
                ChainIO:               s.cc.ChainIO,
×
UNCOV
1062
                Notifier:              s.cc.ChainNotifier,
×
UNCOV
1063
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1064
                Broadcast:             s.BroadcastMessage,
×
UNCOV
1065
                ChanSeries:            chanSeries,
×
UNCOV
1066
                NotifyWhenOnline:      s.NotifyWhenOnline,
×
UNCOV
1067
                NotifyWhenOffline:     s.NotifyWhenOffline,
×
UNCOV
1068
                FetchSelfAnnouncement: s.getNodeAnnouncement,
×
1069
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
UNCOV
1070
                        error) {
×
1071

×
1072
                        return s.genNodeAnnouncement(nil)
×
1073
                },
×
UNCOV
1074
                ProofMatureDelta:        0,
×
UNCOV
1075
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
×
UNCOV
1076
                RetransmitTicker:        ticker.New(time.Minute * 30),
×
UNCOV
1077
                RebroadcastInterval:     time.Hour * 24,
×
UNCOV
1078
                WaitingProofStore:       waitingProofStore,
×
UNCOV
1079
                MessageStore:            gossipMessageStore,
×
UNCOV
1080
                AnnSigner:               s.nodeSigner,
×
UNCOV
1081
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
×
UNCOV
1082
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
×
UNCOV
1083
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
×
UNCOV
1084
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:lll
×
UNCOV
1085
                MinimumBatchSize:        10,
×
UNCOV
1086
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
×
1087
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1088
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1089
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1090
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1091
                IsAlias:                 aliasmgr.IsAlias,
1092
                SignAliasUpdate:         s.signAliasUpdate,
1093
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1094
                GetAlias:                s.aliasMgr.GetPeerAlias,
1095
                FindChannel:             s.findChannel,
1096
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1097
                ScidCloser:              scidCloserMan,
1098
        }, nodeKeyDesc)
1099

1100
        //nolint:lll
1101
        s.localChanMgr = &localchans.Manager{
1102
                ForAllOutgoingChannels:    s.graphBuilder.ForAllOutgoingChannels,
1103
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1104
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1105
                FetchChannel:              s.chanStateDB.FetchChannel,
1106
        }
1107

1108
        utxnStore, err := contractcourt.NewNurseryStore(
1109
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
1110
        )
1111
        if err != nil {
1112
                srvrLog.Errorf("unable to create nursery store: %v", err)
1113
                return nil, err
1114
        }
×
UNCOV
1115

×
UNCOV
1116
        sweeperStore, err := sweep.NewSweeperStore(
×
UNCOV
1117
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1118
        )
×
UNCOV
1119
        if err != nil {
×
1120
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1121
                return nil, err
×
1122
        }
×
UNCOV
1123

×
UNCOV
1124
        aggregator := sweep.NewBudgetAggregator(
×
UNCOV
1125
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
×
UNCOV
1126
        )
×
UNCOV
1127

×
1128
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
UNCOV
1129
                Signer:    cc.Wallet.Cfg.Signer,
×
UNCOV
1130
                Wallet:    cc.Wallet,
×
UNCOV
1131
                Estimator: cc.FeeEstimator,
×
UNCOV
1132
                Notifier:  cc.ChainNotifier,
×
UNCOV
1133
        })
×
UNCOV
1134

×
UNCOV
1135
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
×
1136
                FeeEstimator:         cc.FeeEstimator,
UNCOV
1137
                GenSweepScript:       newSweepPkScriptGen(cc.Wallet),
×
UNCOV
1138
                Signer:               cc.Wallet.Cfg.Signer,
×
UNCOV
1139
                Wallet:               newSweeperWallet(cc.Wallet),
×
UNCOV
1140
                Mempool:              cc.MempoolNotifier,
×
UNCOV
1141
                Notifier:             cc.ChainNotifier,
×
UNCOV
1142
                Store:                sweeperStore,
×
UNCOV
1143
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
×
UNCOV
1144
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
×
UNCOV
1145
                Aggregator:           aggregator,
×
UNCOV
1146
                Publisher:            s.txPublisher,
×
UNCOV
1147
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
×
UNCOV
1148
        })
×
UNCOV
1149

×
UNCOV
1150
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
×
UNCOV
1151
                ChainIO:             cc.ChainIO,
×
UNCOV
1152
                ConfDepth:           1,
×
UNCOV
1153
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
×
UNCOV
1154
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
×
UNCOV
1155
                Notifier:            cc.ChainNotifier,
×
UNCOV
1156
                PublishTransaction:  cc.Wallet.PublishTransaction,
×
UNCOV
1157
                Store:               utxnStore,
×
UNCOV
1158
                SweepInput:          s.sweeper.SweepInput,
×
UNCOV
1159
                Budget:              s.cfg.Sweeper.Budget,
×
UNCOV
1160
        })
×
UNCOV
1161

×
UNCOV
1162
        // Construct a closure that wraps the htlcswitch's CloseLink method.
×
UNCOV
1163
        closeLink := func(chanPoint *wire.OutPoint,
×
UNCOV
1164
                closureType contractcourt.ChannelCloseType) {
×
UNCOV
1165
                // TODO(conner): Properly respect the update and error channels
×
UNCOV
1166
                // returned by CloseLink.
×
UNCOV
1167

×
UNCOV
1168
                // Instruct the switch to close the channel.  Provide no close out
×
UNCOV
1169
                // delivery script or target fee per kw because user input is not
×
UNCOV
1170
                // available when the remote peer closes the channel.
×
UNCOV
1171
                s.htlcSwitch.CloseLink(chanPoint, closureType, 0, 0, nil)
×
UNCOV
1172
        }
×
UNCOV
1173

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

×
UNCOV
1178
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
×
UNCOV
1179
                &contractcourt.BreachConfig{
×
UNCOV
1180
                        CloseLink:          closeLink,
×
UNCOV
1181
                        DB:                 s.chanStateDB,
×
UNCOV
1182
                        Estimator:          s.cc.FeeEstimator,
×
UNCOV
1183
                        GenSweepScript:     newSweepPkScriptGen(cc.Wallet),
×
UNCOV
1184
                        Notifier:           cc.ChainNotifier,
×
UNCOV
1185
                        PublishTransaction: cc.Wallet.PublishTransaction,
×
UNCOV
1186
                        ContractBreaches:   contractBreaches,
×
UNCOV
1187
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1188
                        Store: contractcourt.NewRetributionStore(
×
UNCOV
1189
                                dbs.ChanStateDB,
×
1190
                        ),
1191
                },
1192
        )
UNCOV
1193

×
UNCOV
1194
        //nolint:lll
×
UNCOV
1195
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
×
UNCOV
1196
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
×
UNCOV
1197
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
×
UNCOV
1198
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
×
UNCOV
1199
                NewSweepAddr:           newSweepPkScriptGen(cc.Wallet),
×
UNCOV
1200
                PublishTx:              cc.Wallet.PublishTransaction,
×
UNCOV
1201
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
×
UNCOV
1202
                        for _, msg := range msgs {
×
UNCOV
1203
                                err := s.htlcSwitch.ProcessContractResolution(msg)
×
UNCOV
1204
                                if err != nil {
×
1205
                                        return err
×
1206
                                }
×
UNCOV
1207
                        }
×
UNCOV
1208
                        return nil
×
UNCOV
1209
                },
×
UNCOV
1210
                IncubateOutputs: func(chanPoint wire.OutPoint,
×
UNCOV
1211
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
×
UNCOV
1212
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
×
UNCOV
1213
                        broadcastHeight uint32,
×
UNCOV
1214
                        deadlineHeight fn.Option[int32]) error {
×
UNCOV
1215

×
UNCOV
1216
                        return s.utxoNursery.IncubateOutputs(
×
UNCOV
1217
                                chanPoint, outHtlcRes, inHtlcRes,
×
UNCOV
1218
                                broadcastHeight, deadlineHeight,
×
UNCOV
1219
                        )
×
UNCOV
1220
                },
×
UNCOV
1221
                PreimageDB:   s.witnessBeacon,
×
UNCOV
1222
                Notifier:     cc.ChainNotifier,
×
UNCOV
1223
                Mempool:      cc.MempoolNotifier,
×
UNCOV
1224
                Signer:       cc.Wallet.Cfg.Signer,
×
UNCOV
1225
                FeeEstimator: cc.FeeEstimator,
×
1226
                ChainIO:      cc.ChainIO,
UNCOV
1227
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
×
1228
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
1229
                        s.htlcSwitch.RemoveLink(chanID)
UNCOV
1230
                        return nil
×
UNCOV
1231
                },
×
UNCOV
1232
                IsOurAddress: cc.Wallet.IsOurAddress,
×
UNCOV
1233
                ContractBreach: func(chanPoint wire.OutPoint,
×
UNCOV
1234
                        breachRet *lnwallet.BreachRetribution) error {
×
UNCOV
1235

×
1236
                        // processACK will handle the BreachArbitrator ACKing
UNCOV
1237
                        // the event.
×
1238
                        finalErr := make(chan error, 1)
1239
                        processACK := func(brarErr error) {
1240
                                if brarErr != nil {
1241
                                        finalErr <- brarErr
1242
                                        return
1243
                                }
×
UNCOV
1244

×
UNCOV
1245
                                // If the BreachArbitrator successfully handled
×
UNCOV
1246
                                // the event, we can signal that the handoff
×
UNCOV
1247
                                // was successful.
×
UNCOV
1248
                                finalErr <- nil
×
UNCOV
1249
                        }
×
1250

1251
                        event := &contractcourt.ContractBreachEvent{
1252
                                ChanPoint:         chanPoint,
1253
                                ProcessACK:        processACK,
1254
                                BreachRetribution: breachRet,
1255
                        }
UNCOV
1256

×
UNCOV
1257
                        // Send the contract breach event to the
×
UNCOV
1258
                        // BreachArbitrator.
×
UNCOV
1259
                        select {
×
UNCOV
1260
                        case contractBreaches <- event:
×
1261
                        case <-s.quit:
1262
                                return ErrServerShuttingDown
UNCOV
1263
                        }
×
UNCOV
1264

×
UNCOV
1265
                        // We'll wait for a final error to be available from
×
UNCOV
1266
                        // the BreachArbitrator.
×
UNCOV
1267
                        select {
×
UNCOV
1268
                        case err := <-finalErr:
×
UNCOV
1269
                                return err
×
1270
                        case <-s.quit:
×
1271
                                return ErrServerShuttingDown
×
UNCOV
1272
                        }
×
1273
                },
1274
                DisableChannel: func(chanPoint wire.OutPoint) error {
1275
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
1276
                },
UNCOV
1277
                Sweeper:                       s.sweeper,
×
1278
                Registry:                      s.invoices,
1279
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
UNCOV
1280
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
×
UNCOV
1281
                OnionProcessor:                s.sphinx,
×
UNCOV
1282
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
×
UNCOV
1283
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
×
UNCOV
1284
                Clock:                         clock.NewDefaultClock(),
×
UNCOV
1285
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
×
UNCOV
1286
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
×
UNCOV
1287
                HtlcNotifier:                  s.htlcNotifier,
×
UNCOV
1288
                Budget:                        *s.cfg.Sweeper.Budget,
×
UNCOV
1289

×
UNCOV
1290
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
×
UNCOV
1291
                QueryIncomingCircuit: func(
×
1292
                        circuit models.CircuitKey) *models.CircuitKey {
1293

1294
                        // Get the circuit map.
1295
                        circuits := s.htlcSwitch.CircuitLookup()
UNCOV
1296

×
UNCOV
1297
                        // Lookup the outgoing circuit.
×
UNCOV
1298
                        pc := circuits.LookupOpenCircuit(circuit)
×
UNCOV
1299
                        if pc == nil {
×
UNCOV
1300
                                return nil
×
1301
                        }
1302

UNCOV
1303
                        return &pc.Incoming
×
UNCOV
1304
                },
×
UNCOV
1305
                AuxLeafStore: implCfg.AuxLeafStore,
×
1306
                AuxSigner:    implCfg.AuxSigner,
1307
        }, dbs.ChanStateDB)
1308

1309
        // Select the configuration and funding parameters for Bitcoin.
1310
        chainCfg := cfg.Bitcoin
1311
        minRemoteDelay := funding.MinBtcRemoteDelay
1312
        maxRemoteDelay := funding.MaxBtcRemoteDelay
1313

1314
        var chanIDSeed [32]byte
1315
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
1316
                return nil, err
1317
        }
1318

1319
        // Wrap the DeleteChannelEdges method so that the funding manager can
1320
        // use it without depending on several layers of indirection.
UNCOV
1321
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
×
UNCOV
1322
                *models.ChannelEdgePolicy, error) {
×
UNCOV
1323

×
UNCOV
1324
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
×
UNCOV
1325
                        scid.ToUint64(),
×
UNCOV
1326
                )
×
UNCOV
1327
                if errors.Is(err, channeldb.ErrEdgeNotFound) {
×
1328
                        // This is unlikely but there is a slim chance of this
×
1329
                        // being hit if lnd was killed via SIGKILL and the
×
1330
                        // funding manager was stepping through the delete
×
1331
                        // alias edge logic.
1332
                        return nil, nil
×
1333
                } else if err != nil {
1334
                        return nil, err
1335
                }
1336

1337
                // Grab our key to find our policy.
1338
                var ourKey [33]byte
1339
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
UNCOV
1340

×
UNCOV
1341
                var ourPolicy *models.ChannelEdgePolicy
×
UNCOV
1342
                if info != nil && info.NodeKey1Bytes == ourKey {
×
UNCOV
1343
                        ourPolicy = e1
×
UNCOV
1344
                } else {
×
UNCOV
1345
                        ourPolicy = e2
×
UNCOV
1346
                }
×
UNCOV
1347

×
1348
                if ourPolicy == nil {
1349
                        // Something is wrong, so return an error.
1350
                        return nil, fmt.Errorf("we don't have an edge")
1351
                }
×
UNCOV
1352

×
UNCOV
1353
                err = s.graphDB.DeleteChannelEdges(
×
UNCOV
1354
                        false, false, scid.ToUint64(),
×
UNCOV
1355
                )
×
UNCOV
1356
                return ourPolicy, err
×
UNCOV
1357
        }
×
UNCOV
1358

×
UNCOV
1359
        // For the reservationTimeout and the zombieSweeperInterval different
×
UNCOV
1360
        // values are set in case we are in a dev environment so enhance test
×
UNCOV
1361
        // capacilities.
×
UNCOV
1362
        reservationTimeout := chanfunding.DefaultReservationTimeout
×
UNCOV
1363
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
×
UNCOV
1364

×
UNCOV
1365
        // Get the development config for funding manager. If we are not in
×
1366
        // development mode, this would be nil.
1367
        var devCfg *funding.DevConfig
UNCOV
1368
        if lncfg.IsDevBuild() {
×
UNCOV
1369
                devCfg = &funding.DevConfig{
×
UNCOV
1370
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
×
UNCOV
1371
                }
×
UNCOV
1372

×
UNCOV
1373
                reservationTimeout = cfg.Dev.GetReservationTimeout()
×
UNCOV
1374
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
×
UNCOV
1375

×
UNCOV
1376
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
×
1377
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
UNCOV
1378
                        devCfg, reservationTimeout, zombieSweeperInterval)
×
UNCOV
1379
        }
×
UNCOV
1380

×
UNCOV
1381
        //nolint:lll
×
1382
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
UNCOV
1383
                Dev:                devCfg,
×
UNCOV
1384
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
×
UNCOV
1385
                IDKey:              nodeKeyDesc.PubKey,
×
UNCOV
1386
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
×
1387
                Wallet:             cc.Wallet,
1388
                PublishTransaction: cc.Wallet.PublishTransaction,
1389
                UpdateLabel: func(hash chainhash.Hash, label string) error {
1390
                        return cc.Wallet.LabelTransaction(hash, label, true)
1391
                },
UNCOV
1392
                Notifier:     cc.ChainNotifier,
×
UNCOV
1393
                ChannelDB:    s.chanStateDB,
×
UNCOV
1394
                FeeEstimator: cc.FeeEstimator,
×
UNCOV
1395
                SignMessage:  cc.MsgSigner.SignMessage,
×
UNCOV
1396
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
×
UNCOV
1397
                        error) {
×
UNCOV
1398

×
UNCOV
1399
                        return s.genNodeAnnouncement(nil)
×
UNCOV
1400
                },
×
UNCOV
1401
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
×
UNCOV
1402
                NotifyWhenOnline:     s.NotifyWhenOnline,
×
UNCOV
1403
                TempChanIDSeed:       chanIDSeed,
×
UNCOV
1404
                FindChannel:          s.findChannel,
×
UNCOV
1405
                DefaultRoutingPolicy: cc.RoutingPolicy,
×
UNCOV
1406
                DefaultMinHtlcIn:     cc.MinHtlcIn,
×
UNCOV
1407
                NumRequiredConfs: func(chanAmt btcutil.Amount,
×
UNCOV
1408
                        pushAmt lnwire.MilliSatoshi) uint16 {
×
UNCOV
1409
                        // For large channels we increase the number
×
1410
                        // of confirmations we require for the
1411
                        // channel to be considered open. As it is
UNCOV
1412
                        // always the responder that gets to choose
×
UNCOV
1413
                        // value, the pushAmt is value being pushed
×
UNCOV
1414
                        // to us. This means we have more to lose
×
UNCOV
1415
                        // in the case this gets re-orged out, and
×
UNCOV
1416
                        // we will require more confirmations before
×
UNCOV
1417
                        // we consider it open.
×
UNCOV
1418

×
UNCOV
1419
                        // In case the user has explicitly specified
×
UNCOV
1420
                        // a default value for the number of
×
UNCOV
1421
                        // confirmations, we use it.
×
1422
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
1423
                        if defaultConf != 0 {
1424
                                return defaultConf
1425
                        }
1426

1427
                        minConf := uint64(3)
×
1428
                        maxConf := uint64(6)
×
1429

×
1430
                        // If this is a wumbo channel, then we'll require the
×
1431
                        // max amount of confirmations.
1432
                        if chanAmt > MaxFundingAmount {
1433
                                return uint16(maxConf)
1434
                        }
1435

1436
                        // If not we return a value scaled linearly
1437
                        // between 3 and 6, depending on channel size.
UNCOV
1438
                        // TODO(halseth): Use 1 as minimum?
×
1439
                        maxChannelSize := uint64(
×
1440
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1441
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1442
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1443
                        if conf < minConf {
×
1444
                                conf = minConf
×
1445
                        }
×
1446
                        if conf > maxConf {
×
1447
                                conf = maxConf
×
1448
                        }
×
1449
                        return uint16(conf)
×
UNCOV
1450
                },
×
UNCOV
1451
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1452
                        // We scale the remote CSV delay (the time the
×
UNCOV
1453
                        // remote have to claim funds in case of a unilateral
×
UNCOV
1454
                        // close) linearly from minRemoteDelay blocks
×
UNCOV
1455
                        // for small channels, to maxRemoteDelay blocks
×
1456
                        // for channels of size MaxFundingAmount.
UNCOV
1457

×
UNCOV
1458
                        // In case the user has explicitly specified
×
UNCOV
1459
                        // a default value for the remote delay, we
×
UNCOV
1460
                        // use it.
×
UNCOV
1461
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
UNCOV
1462
                        if defaultDelay > 0 {
×
UNCOV
1463
                                return defaultDelay
×
UNCOV
1464
                        }
×
1465

1466
                        // If this is a wumbo channel, then we'll require the
1467
                        // max value.
1468
                        if chanAmt > MaxFundingAmount {
1469
                                return maxRemoteDelay
×
1470
                        }
×
UNCOV
1471

×
UNCOV
1472
                        // If not we scale according to channel size.
×
1473
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1474
                                chanAmt / MaxFundingAmount)
×
1475
                        if delay < minRemoteDelay {
×
1476
                                delay = minRemoteDelay
×
1477
                        }
×
1478
                        if delay > maxRemoteDelay {
×
1479
                                delay = maxRemoteDelay
×
1480
                        }
1481
                        return delay
×
UNCOV
1482
                },
×
UNCOV
1483
                WatchNewChannel: func(channel *channeldb.OpenChannel,
×
UNCOV
1484
                        peerKey *btcec.PublicKey) error {
×
UNCOV
1485

×
UNCOV
1486
                        // First, we'll mark this new peer as a persistent peer
×
UNCOV
1487
                        // for re-connection purposes. If the peer is not yet
×
UNCOV
1488
                        // tracked or the user hasn't requested it to be perm,
×
UNCOV
1489
                        // we'll set false to prevent the server from continuing
×
UNCOV
1490
                        // to connect to this peer even if the number of
×
UNCOV
1491
                        // channels with this peer is zero.
×
UNCOV
1492
                        s.mu.Lock()
×
UNCOV
1493
                        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
1494
                        if _, ok := s.persistentPeers[pubStr]; !ok {
×
1495
                                s.persistentPeers[pubStr] = false
1496
                        }
1497
                        s.mu.Unlock()
UNCOV
1498

×
UNCOV
1499
                        // With that taken care of, we'll send this channel to
×
UNCOV
1500
                        // the chain arb so it can react to on-chain events.
×
1501
                        return s.chainArb.WatchNewChannel(channel)
1502
                },
UNCOV
1503
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
×
UNCOV
1504
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
×
UNCOV
1505
                        return s.htlcSwitch.UpdateShortChanID(cid)
×
UNCOV
1506
                },
×
UNCOV
1507
                RequiredRemoteChanReserve: func(chanAmt,
×
UNCOV
1508
                        dustLimit btcutil.Amount) btcutil.Amount {
×
UNCOV
1509

×
UNCOV
1510
                        // By default, we'll require the remote peer to maintain
×
UNCOV
1511
                        // at least 1% of the total channel capacity at all
×
1512
                        // times. If this value ends up dipping below the dust
1513
                        // limit, then we'll use the dust limit itself as the
UNCOV
1514
                        // reserve as required by BOLT #2.
×
UNCOV
1515
                        reserve := chanAmt / 100
×
UNCOV
1516
                        if reserve < dustLimit {
×
UNCOV
1517
                                reserve = dustLimit
×
UNCOV
1518
                        }
×
UNCOV
1519

×
UNCOV
1520
                        return reserve
×
UNCOV
1521
                },
×
UNCOV
1522
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
×
UNCOV
1523
                        // By default, we'll allow the remote peer to fully
×
UNCOV
1524
                        // utilize the full bandwidth of the channel, minus our
×
UNCOV
1525
                        // required reserve.
×
UNCOV
1526
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
×
UNCOV
1527
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
×
UNCOV
1528
                },
×
UNCOV
1529
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
×
UNCOV
1530
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
×
UNCOV
1531
                                return cfg.DefaultRemoteMaxHtlcs
×
1532
                        }
UNCOV
1533

×
UNCOV
1534
                        // By default, we'll permit them to utilize the full
×
UNCOV
1535
                        // channel bandwidth.
×
1536
                        return uint16(input.MaxHTLCNumber / 2)
×
1537
                },
UNCOV
1538
                ZombieSweeperInterval:         zombieSweeperInterval,
×
UNCOV
1539
                ReservationTimeout:            reservationTimeout,
×
UNCOV
1540
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
×
UNCOV
1541
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
×
UNCOV
1542
                MaxPendingChannels:            cfg.MaxPendingChannels,
×
UNCOV
1543
                RejectPush:                    cfg.RejectPush,
×
UNCOV
1544
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
×
UNCOV
1545
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
×
UNCOV
1546
                OpenChannelPredicate:          chanPredicate,
×
UNCOV
1547
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
×
UNCOV
1548
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
×
1549
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
UNCOV
1550
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
×
1551
                DeleteAliasEdge:      deleteAliasEdge,
UNCOV
1552
                AliasManager:         s.aliasMgr,
×
UNCOV
1553
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
×
UNCOV
1554
                AuxFundingController: implCfg.AuxFundingController,
×
UNCOV
1555
                AuxSigner:            implCfg.AuxSigner,
×
UNCOV
1556
        })
×
UNCOV
1557
        if err != nil {
×
1558
                return nil, err
×
1559
        }
×
UNCOV
1560

×
UNCOV
1561
        // Next, we'll assemble the sub-system that will maintain an on-disk
×
UNCOV
1562
        // static backup of the latest channel state.
×
1563
        chanNotifier := &channelNotifier{
1564
                chanNotifier: s.channelNotifier,
1565
                addrs:        dbs.ChanStateDB,
UNCOV
1566
        }
×
1567
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
1568
        startingChans, err := chanbackup.FetchStaticChanBackups(
1569
                s.chanStateDB, s.addrSource,
1570
        )
1571
        if err != nil {
1572
                return nil, err
1573
        }
1574
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
1575
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
1576
        )
1577
        if err != nil {
1578
                return nil, err
1579
        }
1580

1581
        // Assemble a peer notifier which will provide clients with subscriptions
1582
        // to peer online and offline events.
1583
        s.peerNotifier = peernotifier.New()
1584

1585
        // Create a channel event store which monitors all open channels.
1586
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
1587
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
UNCOV
1588
                        return s.channelNotifier.SubscribeChannelEvents()
×
UNCOV
1589
                },
×
UNCOV
1590
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
×
1591
                        return s.peerNotifier.SubscribePeerEvents()
1592
                },
1593
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
UNCOV
1594
                Clock:           clock.NewDefaultClock(),
×
UNCOV
1595
                ReadFlapCount:   s.miscDB.ReadFlapCount,
×
UNCOV
1596
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
×
UNCOV
1597
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
×
UNCOV
1598
        })
×
UNCOV
1599

×
UNCOV
1600
        if cfg.WtClient.Active {
×
UNCOV
1601
                policy := wtpolicy.DefaultPolicy()
×
UNCOV
1602
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
×
UNCOV
1603

×
UNCOV
1604
                // We expose the sweep fee rate in sat/vbyte, but the tower
×
UNCOV
1605
                // protocol operations on sat/kw.
×
UNCOV
1606
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
×
UNCOV
1607
                        1000 * cfg.WtClient.SweepFeeRate,
×
UNCOV
1608
                )
×
UNCOV
1609

×
UNCOV
1610
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
×
1611

1612
                if err := policy.Validate(); err != nil {
1613
                        return nil, err
1614
                }
×
UNCOV
1615

×
UNCOV
1616
                // authDial is the wrapper around the btrontide.Dial for the
×
UNCOV
1617
                // watchtower.
×
UNCOV
1618
                authDial := func(localKey keychain.SingleKeyECDH,
×
UNCOV
1619
                        netAddr *lnwire.NetAddress,
×
UNCOV
1620
                        dialer tor.DialFunc) (wtserver.Peer, error) {
×
UNCOV
1621

×
UNCOV
1622
                        return brontide.Dial(
×
UNCOV
1623
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
×
1624
                        )
1625
                }
1626

1627
                // buildBreachRetribution is a call-back that can be used to
1628
                // query the BreachRetribution info and channel type given a
1629
                // channel ID and commitment height.
1630
                buildBreachRetribution := func(chanID lnwire.ChannelID,
UNCOV
1631
                        commitHeight uint64) (*lnwallet.BreachRetribution,
×
UNCOV
1632
                        channeldb.ChannelType, error) {
×
UNCOV
1633

×
UNCOV
1634
                        channel, err := s.chanStateDB.FetchChannelByID(
×
UNCOV
1635
                                nil, chanID,
×
UNCOV
1636
                        )
×
UNCOV
1637
                        if err != nil {
×
1638
                                return nil, 0, err
×
1639
                        }
×
UNCOV
1640

×
UNCOV
1641
                        br, err := lnwallet.NewBreachRetribution(
×
UNCOV
1642
                                channel, commitHeight, 0, nil,
×
UNCOV
1643
                                implCfg.AuxLeafStore,
×
UNCOV
1644
                        )
×
UNCOV
1645
                        if err != nil {
×
1646
                                return nil, 0, err
1647
                        }
1648

UNCOV
1649
                        return br, channel.ChanType, nil
×
UNCOV
1650
                }
×
UNCOV
1651

×
UNCOV
1652
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
×
UNCOV
1653

×
UNCOV
1654
                // Copy the policy for legacy channels and set the blob flag
×
UNCOV
1655
                // signalling support for anchor channels.
×
UNCOV
1656
                anchorPolicy := policy
×
1657
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
1658

1659
                // Copy the policy for legacy channels and set the blob flag
1660
                // signalling support for taproot channels.
UNCOV
1661
                taprootPolicy := policy
×
UNCOV
1662
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
×
UNCOV
1663
                        blob.FlagTaprootChannel,
×
UNCOV
1664
                )
×
UNCOV
1665

×
UNCOV
1666
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
UNCOV
1667
                        FetchClosedChannel:     fetchClosedChannel,
×
UNCOV
1668
                        BuildBreachRetribution: buildBreachRetribution,
×
UNCOV
1669
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
×
UNCOV
1670
                        ChainNotifier:          s.cc.ChainNotifier,
×
1671
                        SubscribeChannelEvents: func() (subscribe.Subscription,
UNCOV
1672
                                error) {
×
UNCOV
1673

×
UNCOV
1674
                                return s.channelNotifier.
×
UNCOV
1675
                                        SubscribeChannelEvents()
×
UNCOV
1676
                        },
×
UNCOV
1677
                        Signer:             cc.Wallet.Cfg.Signer,
×
UNCOV
1678
                        NewAddress:         newSweepPkScriptGen(cc.Wallet),
×
UNCOV
1679
                        SecretKeyRing:      s.cc.KeyRing,
×
1680
                        Dial:               cfg.net.Dial,
UNCOV
1681
                        AuthDial:           authDial,
×
1682
                        DB:                 dbs.TowerClientDB,
1683
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
UNCOV
1684
                        MinBackoff:         10 * time.Second,
×
UNCOV
1685
                        MaxBackoff:         5 * time.Minute,
×
UNCOV
1686
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
×
UNCOV
1687
                }, policy, anchorPolicy, taprootPolicy)
×
UNCOV
1688
                if err != nil {
×
1689
                        return nil, err
×
1690
                }
×
UNCOV
1691
        }
×
UNCOV
1692

×
UNCOV
1693
        if len(cfg.ExternalHosts) != 0 {
×
1694
                advertisedIPs := make(map[string]struct{})
×
1695
                for _, addr := range s.currentNodeAnn.Addresses {
×
1696
                        advertisedIPs[addr.String()] = struct{}{}
×
1697
                }
×
UNCOV
1698

×
1699
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1700
                        Hosts:         cfg.ExternalHosts,
×
1701
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1702
                        LookupHost: func(host string) (net.Addr, error) {
×
1703
                                return lncfg.ParseAddressString(
×
1704
                                        host, strconv.Itoa(defaultPeerPort),
×
1705
                                        cfg.net.ResolveTCPAddr,
×
1706
                                )
×
1707
                        },
×
UNCOV
1708
                        AdvertisedIPs: advertisedIPs,
×
1709
                        AnnounceNewIPs: netann.IPAnnouncer(
UNCOV
1710
                                func(modifier ...netann.NodeAnnModifier) (
×
1711
                                        lnwire.NodeAnnouncement, error) {
×
1712

×
1713
                                        return s.genNodeAnnouncement(
×
1714
                                                nil, modifier...,
×
1715
                                        )
×
1716
                                }),
×
1717
                })
UNCOV
1718
        }
×
1719

1720
        // Create liveness monitor.
1721
        s.createLivenessMonitor(cfg, cc, leaderElector)
1722

1723
        // Create the connection manager which will be responsible for
1724
        // maintaining persistent outbound connections and also accepting new
1725
        // incoming connections
1726
        cmgr, err := connmgr.New(&connmgr.Config{
1727
                Listeners:      listeners,
1728
                OnAccept:       s.InboundPeerConnected,
UNCOV
1729
                RetryDuration:  time.Second * 5,
×
UNCOV
1730
                TargetOutbound: 100,
×
UNCOV
1731
                Dial: noiseDial(
×
1732
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
1733
                ),
UNCOV
1734
                OnConnection: s.OutboundPeerConnected,
×
UNCOV
1735
        })
×
UNCOV
1736
        if err != nil {
×
1737
                return nil, err
×
1738
        }
×
1739
        s.connMgr = cmgr
UNCOV
1740

×
UNCOV
1741
        return s, nil
×
UNCOV
1742
}
×
UNCOV
1743

×
UNCOV
1744
// UpdateRoutingConfig is a callback function to update the routing config
×
UNCOV
1745
// values in the main cfg.
×
UNCOV
1746
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
×
UNCOV
1747
        routerCfg := s.cfg.SubRPCServers.RouterRPC
×
UNCOV
1748

×
1749
        switch c := cfg.Estimator.Config().(type) {
1750
        case routing.AprioriConfig:
1751
                routerCfg.ProbabilityEstimatorType =
UNCOV
1752
                        routing.AprioriEstimatorName
×
UNCOV
1753

×
UNCOV
1754
                targetCfg := routerCfg.AprioriConfig
×
UNCOV
1755
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
×
UNCOV
1756
                targetCfg.Weight = c.AprioriWeight
×
UNCOV
1757
                targetCfg.CapacityFraction = c.CapacityFraction
×
1758
                targetCfg.HopProbability = c.AprioriHopProbability
1759

1760
        case routing.BimodalConfig:
1761
                routerCfg.ProbabilityEstimatorType =
UNCOV
1762
                        routing.BimodalEstimatorName
×
UNCOV
1763

×
UNCOV
1764
                targetCfg := routerCfg.BimodalConfig
×
UNCOV
1765
                targetCfg.Scale = int64(c.BimodalScaleMsat)
×
UNCOV
1766
                targetCfg.NodeWeight = c.BimodalNodeWeight
×
UNCOV
1767
                targetCfg.DecayTime = c.BimodalDecayTime
×
UNCOV
1768
        }
×
UNCOV
1769

×
UNCOV
1770
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
×
UNCOV
1771
}
×
UNCOV
1772

×
UNCOV
1773
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
×
UNCOV
1774
// used for option_scid_alias channels where the ChannelUpdate to be sent back
×
UNCOV
1775
// may differ from what is on disk.
×
UNCOV
1776
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
×
UNCOV
1777
        error) {
×
UNCOV
1778

×
UNCOV
1779
        data, err := u.DataToSign()
×
UNCOV
1780
        if err != nil {
×
1781
                return nil, err
×
1782
        }
×
1783

1784
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
1785
}
1786

UNCOV
1787
// createLivenessMonitor creates a set of health checks using our configured
×
UNCOV
1788
// values and uses these checks to create a liveness monitor. Available
×
UNCOV
1789
// health checks,
×
UNCOV
1790
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
×
UNCOV
1791
//   - diskCheck
×
UNCOV
1792
//   - tlsHealthCheck
×
UNCOV
1793
//   - torController, only created when tor is enabled.
×
UNCOV
1794
//
×
UNCOV
1795
// If a health check has been disabled by setting attempts to 0, our monitor
×
UNCOV
1796
// will not run it.
×
UNCOV
1797
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
×
UNCOV
1798
        leaderElector cluster.LeaderElector) {
×
UNCOV
1799

×
1800
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
UNCOV
1801
        if cfg.Bitcoin.Node == "nochainbackend" {
×
1802
                srvrLog.Info("Disabling chain backend checks for " +
×
1803
                        "nochainbackend mode")
×
1804

×
1805
                chainBackendAttempts = 0
×
1806
        }
×
UNCOV
1807

×
UNCOV
1808
        chainHealthCheck := healthcheck.NewObservation(
×
1809
                "chain backend",
1810
                cc.HealthCheck,
UNCOV
1811
                cfg.HealthChecks.ChainCheck.Interval,
×
1812
                cfg.HealthChecks.ChainCheck.Timeout,
1813
                cfg.HealthChecks.ChainCheck.Backoff,
1814
                chainBackendAttempts,
1815
        )
1816

1817
        diskCheck := healthcheck.NewObservation(
UNCOV
1818
                "disk space",
×
UNCOV
1819
                func() error {
×
1820
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1821
                                cfg.LndDir,
×
1822
                        )
×
1823
                        if err != nil {
×
1824
                                return err
1825
                        }
×
1826

1827
                        // If we have more free space than we require,
1828
                        // we return a nil error.
1829
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
1830
                                return nil
1831
                        }
1832

1833
                        return fmt.Errorf("require: %v free space, got: %v",
1834
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
1835
                                free)
1836
                },
1837
                cfg.HealthChecks.DiskCheck.Interval,
1838
                cfg.HealthChecks.DiskCheck.Timeout,
UNCOV
1839
                cfg.HealthChecks.DiskCheck.Backoff,
×
UNCOV
1840
                cfg.HealthChecks.DiskCheck.Attempts,
×
UNCOV
1841
        )
×
UNCOV
1842

×
UNCOV
1843
        tlsHealthCheck := healthcheck.NewObservation(
×
UNCOV
1844
                "tls",
×
UNCOV
1845
                func() error {
×
1846
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1847
                                s.cc.KeyRing,
×
1848
                        )
1849
                        if err != nil {
×
1850
                                return err
×
1851
                        }
×
1852
                        if expired {
×
1853
                                return fmt.Errorf("TLS certificate is "+
×
1854
                                        "expired as of %v", expTime)
×
1855
                        }
×
UNCOV
1856

×
UNCOV
1857
                        // If the certificate is not outdated, no error needs
×
UNCOV
1858
                        // to be returned
×
1859
                        return nil
×
UNCOV
1860
                },
×
UNCOV
1861
                cfg.HealthChecks.TLSCheck.Interval,
×
UNCOV
1862
                cfg.HealthChecks.TLSCheck.Timeout,
×
UNCOV
1863
                cfg.HealthChecks.TLSCheck.Backoff,
×
UNCOV
1864
                cfg.HealthChecks.TLSCheck.Attempts,
×
UNCOV
1865
        )
×
UNCOV
1866

×
1867
        checks := []*healthcheck.Observation{
1868
                chainHealthCheck, diskCheck, tlsHealthCheck,
1869
        }
UNCOV
1870

×
UNCOV
1871
        // If Tor is enabled, add the healthcheck for tor connection.
×
UNCOV
1872
        if s.torController != nil {
×
1873
                torConnectionCheck := healthcheck.NewObservation(
1874
                        "tor connection",
×
1875
                        func() error {
×
1876
                                return healthcheck.CheckTorServiceStatus(
×
1877
                                        s.torController,
1878
                                        s.createNewHiddenService,
1879
                                )
1880
                        },
1881
                        cfg.HealthChecks.TorConnection.Interval,
1882
                        cfg.HealthChecks.TorConnection.Timeout,
1883
                        cfg.HealthChecks.TorConnection.Backoff,
UNCOV
1884
                        cfg.HealthChecks.TorConnection.Attempts,
×
UNCOV
1885
                )
×
1886
                checks = append(checks, torConnectionCheck)
×
UNCOV
1887
        }
×
UNCOV
1888

×
UNCOV
1889
        // If remote signing is enabled, add the healthcheck for the remote
×
UNCOV
1890
        // signing RPC interface.
×
UNCOV
1891
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
×
UNCOV
1892
                // Because we have two cascading timeouts here, we need to add
×
UNCOV
1893
                // some slack to the "outer" one of them in case the "inner"
×
UNCOV
1894
                // returns exactly on time.
×
UNCOV
1895
                overhead := time.Millisecond * 10
×
UNCOV
1896

×
1897
                remoteSignerConnectionCheck := healthcheck.NewObservation(
1898
                        "remote signer connection",
1899
                        rpcwallet.HealthCheck(
UNCOV
1900
                                s.cfg.RemoteSigner,
×
1901

1902
                                // For the health check we might to be even
1903
                                // stricter than the initial/normal connect, so
1904
                                // we use the health check timeout here.
1905
                                cfg.HealthChecks.RemoteSigner.Timeout,
1906
                        ),
1907
                        cfg.HealthChecks.RemoteSigner.Interval,
UNCOV
1908
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
×
UNCOV
1909
                        cfg.HealthChecks.RemoteSigner.Backoff,
×
UNCOV
1910
                        cfg.HealthChecks.RemoteSigner.Attempts,
×
UNCOV
1911
                )
×
UNCOV
1912
                checks = append(checks, remoteSignerConnectionCheck)
×
UNCOV
1913
        }
×
UNCOV
1914

×
UNCOV
1915
        // If we have a leader elector, we add a health check to ensure we are
×
UNCOV
1916
        // still the leader. During normal operation, we should always be the
×
UNCOV
1917
        // leader, but there are circumstances where this may change, such as
×
UNCOV
1918
        // when we lose network connectivity for long enough expiring out lease.
×
UNCOV
1919
        if leaderElector != nil {
×
1920
                leaderCheck := healthcheck.NewObservation(
×
1921
                        "leader status",
×
1922
                        func() error {
1923
                                // Check if we are still the leader. Note that
1924
                                // we don't need to use a timeout context here
1925
                                // as the healthcheck observer will handle the
1926
                                // timeout case for us.
1927
                                timeoutCtx, cancel := context.WithTimeout(
×
1928
                                        context.Background(),
1929
                                        cfg.HealthChecks.LeaderCheck.Timeout,
1930
                                )
1931
                                defer cancel()
1932

×
1933
                                leader, err := leaderElector.IsLeader(
×
1934
                                        timeoutCtx,
×
1935
                                )
×
1936
                                if err != nil {
×
1937
                                        return fmt.Errorf("unable to check if "+
×
1938
                                                "still leader: %v", err)
×
1939
                                }
×
UNCOV
1940

×
1941
                                if !leader {
×
1942
                                        srvrLog.Debug("Not the current leader")
×
1943
                                        return fmt.Errorf("not the current " +
×
1944
                                                "leader")
×
1945
                                }
×
UNCOV
1946

×
1947
                                return nil
×
UNCOV
1948
                        },
×
UNCOV
1949
                        cfg.HealthChecks.LeaderCheck.Interval,
×
UNCOV
1950
                        cfg.HealthChecks.LeaderCheck.Timeout,
×
UNCOV
1951
                        cfg.HealthChecks.LeaderCheck.Backoff,
×
UNCOV
1952
                        cfg.HealthChecks.LeaderCheck.Attempts,
×
UNCOV
1953
                )
×
UNCOV
1954

×
1955
                checks = append(checks, leaderCheck)
1956
        }
1957

1958
        // If we have not disabled all of our health checks, we create a
1959
        // liveness monitor with our configured checks.
UNCOV
1960
        s.livenessMonitor = healthcheck.NewMonitor(
×
UNCOV
1961
                &healthcheck.Config{
×
UNCOV
1962
                        Checks:   checks,
×
UNCOV
1963
                        Shutdown: srvrLog.Criticalf,
×
UNCOV
1964
                },
×
UNCOV
1965
        )
×
UNCOV
1966
}
×
UNCOV
1967

×
UNCOV
1968
// Started returns true if the server has been started, and false otherwise.
×
UNCOV
1969
// NOTE: This function is safe for concurrent access.
×
UNCOV
1970
func (s *server) Started() bool {
×
UNCOV
1971
        return atomic.LoadInt32(&s.active) != 0
×
UNCOV
1972
}
×
UNCOV
1973

×
UNCOV
1974
// cleaner is used to aggregate "cleanup" functions during an operation that
×
UNCOV
1975
// starts several subsystems. In case one of the subsystem fails to start
×
UNCOV
1976
// and a proper resource cleanup is required, the "run" method achieves this
×
UNCOV
1977
// by running all these added "cleanup" functions.
×
UNCOV
1978
type cleaner []func() error
×
UNCOV
1979

×
UNCOV
1980
// add is used to add a cleanup function to be called when
×
1981
// the run function is executed.
UNCOV
1982
func (c cleaner) add(cleanup func() error) cleaner {
×
UNCOV
1983
        return append(c, cleanup)
×
UNCOV
1984
}
×
UNCOV
1985

×
UNCOV
1986
// run is used to run all the previousely added cleanup functions.
×
1987
func (c cleaner) run() {
1988
        for i := len(c) - 1; i >= 0; i-- {
×
1989
                if err := c[i](); err != nil {
1990
                        srvrLog.Infof("Cleanup failed: %v", err)
1991
                }
1992
        }
1993
}
1994

1995
// Start starts the main daemon server, all requested listeners, and any helper
UNCOV
1996
// goroutines.
×
1997
// NOTE: This function is safe for concurrent access.
1998
//
1999
//nolint:funlen
2000
func (s *server) Start() error {
UNCOV
2001
        var startErr error
×
UNCOV
2002

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

2008
        s.start.Do(func() {
2009
                cleanup = cleanup.add(s.customMessageServer.Stop)
2010
                if err := s.customMessageServer.Start(); err != nil {
2011
                        startErr = err
×
2012
                        return
×
2013
                }
×
2014

2015
                if s.hostAnn != nil {
2016
                        cleanup = cleanup.add(s.hostAnn.Stop)
2017
                        if err := s.hostAnn.Start(); err != nil {
2018
                                startErr = err
2019
                                return
2020
                        }
2021
                }
2022

UNCOV
2023
                if s.livenessMonitor != nil {
×
UNCOV
2024
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
×
UNCOV
2025
                        if err := s.livenessMonitor.Start(); err != nil {
×
2026
                                startErr = err
2027
                                return
2028
                        }
×
UNCOV
2029
                }
×
UNCOV
2030

×
UNCOV
2031
                // Start the notification server. This is used so channel
×
UNCOV
2032
                // management goroutines can be notified when a funding
×
2033
                // transaction reaches a sufficient number of confirmations, or
2034
                // when the input for the funding transaction is spent in an
2035
                // attempt at an uncooperative close by the counterparty.
2036
                cleanup = cleanup.add(s.sigPool.Stop)
2037
                if err := s.sigPool.Start(); err != nil {
2038
                        startErr = err
2039
                        return
2040
                }
UNCOV
2041

×
UNCOV
2042
                cleanup = cleanup.add(s.writePool.Stop)
×
UNCOV
2043
                if err := s.writePool.Start(); err != nil {
×
2044
                        startErr = err
×
2045
                        return
×
2046
                }
×
UNCOV
2047

×
UNCOV
2048
                cleanup = cleanup.add(s.readPool.Stop)
×
UNCOV
2049
                if err := s.readPool.Start(); err != nil {
×
2050
                        startErr = err
×
2051
                        return
×
2052
                }
×
UNCOV
2053

×
UNCOV
2054
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
×
2055
                if err := s.cc.ChainNotifier.Start(); err != nil {
2056
                        startErr = err
×
2057
                        return
×
2058
                }
×
UNCOV
2059

×
UNCOV
2060
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
×
UNCOV
2061
                if err := s.cc.BestBlockTracker.Start(); err != nil {
×
2062
                        startErr = err
2063
                        return
2064
                }
×
UNCOV
2065

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

2072
                cleanup = cleanup.add(func() error {
2073
                        return s.peerNotifier.Stop()
2074
                })
2075
                if err := s.peerNotifier.Start(); err != nil {
2076
                        startErr = err
2077
                        return
×
2078
                }
×
UNCOV
2079

×
UNCOV
2080
                cleanup = cleanup.add(s.htlcNotifier.Stop)
×
UNCOV
2081
                if err := s.htlcNotifier.Start(); err != nil {
×
2082
                        startErr = err
2083
                        return
×
2084
                }
×
UNCOV
2085

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

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

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

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

×
2112
                cleanup = cleanup.add(s.breachArbitrator.Stop)
UNCOV
2113
                if err := s.breachArbitrator.Start(); err != nil {
×
2114
                        startErr = err
×
2115
                        return
×
2116
                }
×
UNCOV
2117

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

×
UNCOV
2124
                // htlcSwitch must be started before chainArb since the latter
×
UNCOV
2125
                // relies on htlcSwitch to deliver resolution message upon
×
2126
                // start.
UNCOV
2127
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
UNCOV
2128
                if err := s.htlcSwitch.Start(); err != nil {
×
2129
                        startErr = err
×
2130
                        return
×
2131
                }
×
UNCOV
2132

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

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

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

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

×
UNCOV
2157
                cleanup = cleanup.add(s.chanRouter.Stop)
×
2158
                if err := s.chanRouter.Start(); err != nil {
2159
                        startErr = err
×
2160
                        return
×
2161
                }
×
UNCOV
2162
                // The authGossiper depends on the chanRouter and therefore
×
UNCOV
2163
                // should be started after it.
×
2164
                cleanup = cleanup.add(s.authGossiper.Stop)
2165
                if err := s.authGossiper.Start(); err != nil {
2166
                        startErr = err
2167
                        return
2168
                }
×
UNCOV
2169

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

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

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

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

×
UNCOV
2194
                cleanup.add(func() error {
×
2195
                        s.missionController.StopStoreTickers()
×
2196
                        return nil
×
2197
                })
UNCOV
2198
                s.missionController.RunStoreTickers()
×
UNCOV
2199

×
UNCOV
2200
                // Before we start the connMgr, we'll check to see if we have
×
UNCOV
2201
                // any backups to recover. We do this now as we want to ensure
×
UNCOV
2202
                // that have all the information we need to handle channel
×
2203
                // recovery _before_ we even accept connections from any peers.
2204
                chanRestorer := &chanDBRestorer{
UNCOV
2205
                        db:         s.chanStateDB,
×
UNCOV
2206
                        secretKeys: s.cc.KeyRing,
×
UNCOV
2207
                        chainArb:   s.chainArb,
×
UNCOV
2208
                }
×
UNCOV
2209
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
×
2210
                        err := chanbackup.UnpackAndRecoverSingles(
2211
                                s.chansToRestore.PackedSingleChanBackups,
×
2212
                                s.cc.KeyRing, chanRestorer, s,
×
2213
                        )
×
2214
                        if err != nil {
×
2215
                                startErr = fmt.Errorf("unable to unpack single "+
×
2216
                                        "backups: %v", err)
2217
                                return
×
2218
                        }
×
UNCOV
2219
                }
×
UNCOV
2220
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
×
UNCOV
2221
                        err := chanbackup.UnpackAndRecoverMulti(
×
2222
                                s.chansToRestore.PackedMultiChanBackup,
UNCOV
2223
                                s.cc.KeyRing, chanRestorer, s,
×
UNCOV
2224
                        )
×
UNCOV
2225
                        if err != nil {
×
2226
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2227
                                        "backup: %v", err)
×
2228
                                return
2229
                        }
×
UNCOV
2230
                }
×
UNCOV
2231

×
UNCOV
2232
                // chanSubSwapper must be started after the `channelNotifier`
×
UNCOV
2233
                // because it depends on channel events as a synchronization
×
2234
                // point.
UNCOV
2235
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
×
UNCOV
2236
                if err := s.chanSubSwapper.Start(); err != nil {
×
2237
                        startErr = err
×
2238
                        return
×
2239
                }
×
UNCOV
2240

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

×
UNCOV
2249
                if s.natTraversal != nil {
×
2250
                        s.wg.Add(1)
×
2251
                        go s.watchExternalIP()
×
2252
                }
×
UNCOV
2253

×
UNCOV
2254
                // Start connmgr last to prevent connections before init.
×
UNCOV
2255
                cleanup = cleanup.add(func() error {
×
2256
                        s.connMgr.Stop()
×
2257
                        return nil
×
2258
                })
×
UNCOV
2259
                s.connMgr.Start()
×
2260

UNCOV
2261
                // If peers are specified as a config option, we'll add those
×
UNCOV
2262
                // peers first.
×
UNCOV
2263
                for _, peerAddrCfg := range s.cfg.AddPeers {
×
UNCOV
2264
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
×
UNCOV
2265
                                peerAddrCfg,
×
UNCOV
2266
                        )
×
UNCOV
2267
                        if err != nil {
×
2268
                                startErr = fmt.Errorf("unable to parse peer "+
×
2269
                                        "pubkey from config: %v", err)
×
2270
                                return
×
2271
                        }
2272
                        addr, err := parseAddr(parsedHost, s.cfg.net)
2273
                        if err != nil {
2274
                                startErr = fmt.Errorf("unable to parse peer "+
2275
                                        "address provided as a config option: "+
2276
                                        "%v", err)
×
2277
                                return
×
2278
                        }
×
UNCOV
2279

×
UNCOV
2280
                        peerAddr := &lnwire.NetAddress{
×
2281
                                IdentityKey: parsedPubkey,
UNCOV
2282
                                Address:     addr,
×
UNCOV
2283
                                ChainNet:    s.cfg.ActiveNetParams.Net,
×
UNCOV
2284
                        }
×
UNCOV
2285

×
UNCOV
2286
                        err = s.ConnectToPeer(
×
UNCOV
2287
                                peerAddr, true,
×
2288
                                s.cfg.ConnectionTimeout,
2289
                        )
UNCOV
2290
                        if err != nil {
×
2291
                                startErr = fmt.Errorf("unable to connect to "+
×
2292
                                        "peer address provided as a config "+
×
2293
                                        "option: %v", err)
×
2294
                                return
2295
                        }
UNCOV
2296
                }
×
UNCOV
2297

×
UNCOV
2298
                // Subscribe to NodeAnnouncements that advertise new addresses
×
UNCOV
2299
                // our persistent peers.
×
UNCOV
2300
                if err := s.updatePersistentPeerAddrs(); err != nil {
×
2301
                        startErr = err
×
2302
                        return
×
2303
                }
×
UNCOV
2304

×
UNCOV
2305
                // With all the relevant sub-systems started, we'll now attempt
×
UNCOV
2306
                // to establish persistent connections to our direct channel
×
UNCOV
2307
                // collaborators within the network. Before doing so however,
×
UNCOV
2308
                // we'll prune our set of link nodes found within the database
×
UNCOV
2309
                // to ensure we don't reconnect to any nodes we no longer have
×
UNCOV
2310
                // open channels with.
×
UNCOV
2311
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
×
2312
                        startErr = err
×
2313
                        return
×
2314
                }
×
UNCOV
2315
                if err := s.establishPersistentConnections(); err != nil {
×
2316
                        startErr = err
×
2317
                        return
×
2318
                }
×
UNCOV
2319

×
2320
                // setSeedList is a helper function that turns multiple DNS seed
UNCOV
2321
                // server tuples from the command line or config file into the
×
UNCOV
2322
                // data structure we need and does a basic formal sanity check
×
UNCOV
2323
                // in the process.
×
UNCOV
2324
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
×
2325
                        if len(tuples) == 0 {
×
2326
                                return
×
2327
                        }
×
UNCOV
2328

×
2329
                        result := make([][2]string, len(tuples))
×
2330
                        for idx, tuple := range tuples {
×
2331
                                tuple = strings.TrimSpace(tuple)
×
2332
                                if len(tuple) == 0 {
×
2333
                                        return
×
2334
                                }
×
UNCOV
2335

×
2336
                                servers := strings.Split(tuple, ",")
×
2337
                                if len(servers) > 2 || len(servers) == 0 {
2338
                                        srvrLog.Warnf("Ignoring invalid DNS "+
2339
                                                "seed tuple: %v", servers)
2340
                                        return
2341
                                }
×
UNCOV
2342

×
2343
                                copy(result[idx][:], servers)
×
UNCOV
2344
                        }
×
2345

2346
                        chainreg.ChainDNSSeeds[genesisHash] = result
2347
                }
2348

2349
                // Let users overwrite the DNS seed nodes. We only allow them
2350
                // for bitcoin mainnet/testnet/signet.
2351
                if s.cfg.Bitcoin.MainNet {
2352
                        setSeedList(
×
2353
                                s.cfg.Bitcoin.DNSSeeds,
×
2354
                                chainreg.BitcoinMainnetGenesis,
×
2355
                        )
×
2356
                }
×
UNCOV
2357
                if s.cfg.Bitcoin.TestNet3 {
×
2358
                        setSeedList(
×
2359
                                s.cfg.Bitcoin.DNSSeeds,
×
2360
                                chainreg.BitcoinTestnetGenesis,
2361
                        )
2362
                }
2363
                if s.cfg.Bitcoin.SigNet {
2364
                        setSeedList(
2365
                                s.cfg.Bitcoin.DNSSeeds,
×
2366
                                chainreg.BitcoinSignetGenesis,
×
2367
                        )
×
2368
                }
×
2369

UNCOV
2370
                // If network bootstrapping hasn't been disabled, then we'll
×
UNCOV
2371
                // configure the set of active bootstrappers, and launch a
×
UNCOV
2372
                // dedicated goroutine to maintain a set of persistent
×
UNCOV
2373
                // connections.
×
UNCOV
2374
                if shouldPeerBootstrap(s.cfg) {
×
2375
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2376
                        if err != nil {
2377
                                startErr = err
×
2378
                                return
×
2379
                        }
×
UNCOV
2380

×
2381
                        s.wg.Add(1)
×
2382
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2383
                } else {
UNCOV
2384
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
×
2385
                }
2386

UNCOV
2387
                // Set the active flag now that we've completed the full
×
2388
                // startup.
2389
                atomic.StoreInt32(&s.active, 1)
2390
        })
2391

UNCOV
2392
        if startErr != nil {
×
2393
                cleanup.run()
×
2394
        }
×
UNCOV
2395
        return startErr
×
UNCOV
2396
}
×
UNCOV
2397

×
UNCOV
2398
// Stop gracefully shutsdown the main daemon server. This function will signal
×
UNCOV
2399
// any active goroutines, or helper objects to exit, then blocks until they've
×
UNCOV
2400
// all successfully exited. Additionally, any/all listeners are closed.
×
UNCOV
2401
// NOTE: This function is safe for concurrent access.
×
UNCOV
2402
func (s *server) Stop() error {
×
UNCOV
2403
        s.stop.Do(func() {
×
UNCOV
2404
                atomic.StoreInt32(&s.stopping, 1)
×
UNCOV
2405

×
UNCOV
2406
                close(s.quit)
×
UNCOV
2407

×
UNCOV
2408
                // Shutdown connMgr first to prevent conns during shutdown.
×
UNCOV
2409
                s.connMgr.Stop()
×
2410

2411
                // Shutdown the wallet, funding manager, and the rpc server.
2412
                if err := s.chanStatusMgr.Stop(); err != nil {
2413
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
2414
                }
UNCOV
2415
                if err := s.htlcSwitch.Stop(); err != nil {
×
2416
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2417
                }
×
UNCOV
2418
                if err := s.sphinx.Stop(); err != nil {
×
2419
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2420
                }
×
2421
                if err := s.invoices.Stop(); err != nil {
2422
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2423
                }
×
UNCOV
2424
                if err := s.interceptableSwitch.Stop(); err != nil {
×
2425
                        srvrLog.Warnf("failed to stop interceptable "+
×
2426
                                "switch: %v", err)
×
2427
                }
2428
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
2429
                        srvrLog.Warnf("failed to stop htlc invoices "+
2430
                                "modifier: %v", err)
×
2431
                }
2432
                if err := s.chanRouter.Stop(); err != nil {
2433
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2434
                }
×
UNCOV
2435
                if err := s.chainArb.Stop(); err != nil {
×
2436
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2437
                }
2438
                if err := s.fundingMgr.Stop(); err != nil {
2439
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
2440
                }
2441
                if err := s.breachArbitrator.Stop(); err != nil {
2442
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
2443
                                err)
×
2444
                }
×
UNCOV
2445
                if err := s.utxoNursery.Stop(); err != nil {
×
2446
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2447
                }
×
UNCOV
2448
                if err := s.authGossiper.Stop(); err != nil {
×
2449
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2450
                }
×
UNCOV
2451
                if err := s.sweeper.Stop(); err != nil {
×
2452
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2453
                }
×
UNCOV
2454
                if err := s.txPublisher.Stop(); err != nil {
×
2455
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2456
                }
×
UNCOV
2457
                if err := s.channelNotifier.Stop(); err != nil {
×
2458
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2459
                }
×
UNCOV
2460
                if err := s.peerNotifier.Stop(); err != nil {
×
2461
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2462
                }
×
UNCOV
2463
                if err := s.htlcNotifier.Stop(); err != nil {
×
2464
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2465
                }
×
UNCOV
2466
                if err := s.chanSubSwapper.Stop(); err != nil {
×
2467
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2468
                }
×
UNCOV
2469
                if err := s.cc.ChainNotifier.Stop(); err != nil {
×
2470
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2471
                }
×
UNCOV
2472
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2473
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2474
                                err)
×
2475
                }
×
UNCOV
2476
                if err := s.chanEventStore.Stop(); err != nil {
×
2477
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2478
                                err)
×
2479
                }
×
UNCOV
2480
                s.missionController.StopStoreTickers()
×
UNCOV
2481

×
UNCOV
2482
                // Disconnect from each active peers to ensure that
×
UNCOV
2483
                // peerTerminationWatchers signal completion to each peer.
×
UNCOV
2484
                for _, peer := range s.Peers() {
×
UNCOV
2485
                        err := s.DisconnectPeer(peer.IdentityKey())
×
UNCOV
2486
                        if err != nil {
×
2487
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2488
                                        "received error: %v", peer.IdentityKey(),
×
2489
                                        err,
×
2490
                                )
×
2491
                        }
×
UNCOV
2492
                }
×
UNCOV
2493

×
UNCOV
2494
                // Now that all connections have been torn down, stop the tower
×
UNCOV
2495
                // client which will reliably flush all queued states to the
×
UNCOV
2496
                // tower. If this is halted for any reason, the force quit timer
×
UNCOV
2497
                // will kick in and abort to allow this method to return.
×
UNCOV
2498
                if s.towerClientMgr != nil {
×
UNCOV
2499
                        if err := s.towerClientMgr.Stop(); err != nil {
×
2500
                                srvrLog.Warnf("Unable to shut down tower "+
×
2501
                                        "client manager: %v", err)
×
2502
                        }
×
UNCOV
2503
                }
×
UNCOV
2504

×
UNCOV
2505
                if s.hostAnn != nil {
×
2506
                        if err := s.hostAnn.Stop(); err != nil {
×
2507
                                srvrLog.Warnf("unable to shut down host "+
×
2508
                                        "annoucner: %v", err)
×
2509
                        }
×
UNCOV
2510
                }
×
UNCOV
2511

×
UNCOV
2512
                if s.livenessMonitor != nil {
×
UNCOV
2513
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2514
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2515
                                        "monitor: %v", err)
×
2516
                        }
×
UNCOV
2517
                }
×
UNCOV
2518

×
UNCOV
2519
                // Wait for all lingering goroutines to quit.
×
UNCOV
2520
                srvrLog.Debug("Waiting for server to shutdown...")
×
UNCOV
2521
                s.wg.Wait()
×
UNCOV
2522

×
UNCOV
2523
                srvrLog.Debug("Stopping buffer pools...")
×
UNCOV
2524
                s.sigPool.Stop()
×
UNCOV
2525
                s.writePool.Stop()
×
UNCOV
2526
                s.readPool.Stop()
×
UNCOV
2527
        })
×
UNCOV
2528

×
UNCOV
2529
        return nil
×
UNCOV
2530
}
×
UNCOV
2531

×
UNCOV
2532
// Stopped returns true if the server has been instructed to shutdown.
×
2533
// NOTE: This function is safe for concurrent access.
2534
func (s *server) Stopped() bool {
2535
        return atomic.LoadInt32(&s.stopping) != 0
2536
}
2537

2538
// configurePortForwarding attempts to set up port forwarding for the different
UNCOV
2539
// ports that the server will be listening on.
×
UNCOV
2540
//
×
UNCOV
2541
// NOTE: This should only be used when using some kind of NAT traversal to
×
UNCOV
2542
// automatically set up forwarding rules.
×
2543
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2544
        ip, err := s.natTraversal.ExternalIP()
2545
        if err != nil {
2546
                return nil, err
×
2547
        }
×
2548
        s.lastDetectedIP = ip
×
2549

×
2550
        externalIPs := make([]string, 0, len(ports))
×
2551
        for _, port := range ports {
2552
                if err := s.natTraversal.AddPortMapping(port); err != nil {
2553
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2554
                        continue
×
UNCOV
2555
                }
×
UNCOV
2556

×
2557
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2558
                externalIPs = append(externalIPs, hostIP)
2559
        }
2560

2561
        return externalIPs, nil
×
UNCOV
2562
}
×
UNCOV
2563

×
UNCOV
2564
// removePortForwarding attempts to clear the forwarding rules for the different
×
UNCOV
2565
// ports the server is currently listening on.
×
UNCOV
2566
//
×
UNCOV
2567
// NOTE: This should only be used when using some kind of NAT traversal to
×
2568
// automatically set up forwarding rules.
2569
func (s *server) removePortForwarding() {
2570
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2571
        for _, port := range forwardedPorts {
2572
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
2573
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
2574
                                "port %d: %v", port, err)
2575
                }
×
UNCOV
2576
        }
×
UNCOV
2577
}
×
2578

2579
// watchExternalIP continuously checks for an updated external IP address every
2580
// 15 minutes. Once a new IP address has been detected, it will automatically
2581
// handle port forwarding rules and send updated node announcements to the
2582
// currently connected peers.
2583
//
UNCOV
2584
// NOTE: This MUST be run as a goroutine.
×
2585
func (s *server) watchExternalIP() {
×
2586
        defer s.wg.Done()
×
2587

×
2588
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2589
        // up by the server.
×
2590
        defer s.removePortForwarding()
×
2591

×
2592
        // Keep track of the external IPs set by the user to avoid replacing
×
2593
        // them when detecting a new IP.
×
2594
        ipsSetByUser := make(map[string]struct{})
×
2595
        for _, ip := range s.cfg.ExternalIPs {
×
2596
                ipsSetByUser[ip.String()] = struct{}{}
2597
        }
UNCOV
2598

×
2599
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2600

2601
        ticker := time.NewTicker(15 * time.Minute)
2602
        defer ticker.Stop()
×
2603
out:
2604
        for {
2605
                select {
2606
                case <-ticker.C:
2607
                        // We'll start off by making sure a new IP address has
2608
                        // been detected.
2609
                        ip, err := s.natTraversal.ExternalIP()
2610
                        if err != nil {
×
2611
                                srvrLog.Debugf("Unable to retrieve the "+
×
2612
                                        "external IP address: %v", err)
×
2613
                                continue
×
UNCOV
2614
                        }
×
UNCOV
2615

×
UNCOV
2616
                        // Periodically renew the NAT port forwarding.
×
2617
                        for _, port := range forwardedPorts {
2618
                                err := s.natTraversal.AddPortMapping(port)
2619
                                if err != nil {
2620
                                        srvrLog.Warnf("Unable to automatically "+
2621
                                                "re-create port forwarding using %s: %v",
2622
                                                s.natTraversal.Name(), err)
2623
                                } else {
2624
                                        srvrLog.Debugf("Automatically re-created "+
2625
                                                "forwarding for port %d using %s to "+
2626
                                                "advertise external IP",
×
2627
                                                port, s.natTraversal.Name())
×
2628
                                }
×
UNCOV
2629
                        }
×
UNCOV
2630

×
2631
                        if ip.Equal(s.lastDetectedIP) {
×
2632
                                continue
×
UNCOV
2633
                        }
×
UNCOV
2634

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

×
2637
                        // Next, we'll craft the new addresses that will be
×
2638
                        // included in the new node announcement and advertised
×
2639
                        // to the network. Each address will consist of the new
2640
                        // IP detected and one of the currently advertised
×
2641
                        // ports.
×
2642
                        var newAddrs []net.Addr
×
2643
                        for _, port := range forwardedPorts {
×
2644
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2645
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2646
                                if err != nil {
×
2647
                                        srvrLog.Debugf("Unable to resolve "+
×
2648
                                                "host %v: %v", addr, err)
×
2649
                                        continue
×
UNCOV
2650
                                }
×
UNCOV
2651

×
2652
                                newAddrs = append(newAddrs, addr)
×
UNCOV
2653
                        }
×
UNCOV
2654

×
2655
                        // Skip the update if we weren't able to resolve any of
2656
                        // the new addresses.
2657
                        if len(newAddrs) == 0 {
2658
                                srvrLog.Debug("Skipping node announcement " +
×
2659
                                        "update due to not being able to " +
×
2660
                                        "resolve any new addresses")
×
2661
                                continue
×
UNCOV
2662
                        }
×
UNCOV
2663

×
UNCOV
2664
                        // Now, we'll need to update the addresses in our node's
×
UNCOV
2665
                        // announcement in order to propagate the update
×
UNCOV
2666
                        // throughout the network. We'll only include addresses
×
UNCOV
2667
                        // that have a different IP from the previous one, as
×
UNCOV
2668
                        // the previous IP is no longer valid.
×
2669
                        currentNodeAnn := s.getNodeAnnouncement()
×
2670

2671
                        for _, addr := range currentNodeAnn.Addresses {
2672
                                host, _, err := net.SplitHostPort(addr.String())
×
2673
                                if err != nil {
×
2674
                                        srvrLog.Debugf("Unable to determine "+
2675
                                                "host from address %v: %v",
2676
                                                addr, err)
×
2677
                                        continue
×
UNCOV
2678
                                }
×
UNCOV
2679

×
UNCOV
2680
                                // We'll also make sure to include external IPs
×
UNCOV
2681
                                // set manually by the user.
×
2682
                                _, setByUser := ipsSetByUser[addr.String()]
×
2683
                                if setByUser || host != s.lastDetectedIP.String() {
×
2684
                                        newAddrs = append(newAddrs, addr)
×
2685
                                }
×
UNCOV
2686
                        }
×
UNCOV
2687

×
UNCOV
2688
                        // Then, we'll generate a new timestamped node
×
UNCOV
2689
                        // announcement with the updated addresses and broadcast
×
UNCOV
2690
                        // it to our peers.
×
2691
                        newNodeAnn, err := s.genNodeAnnouncement(
2692
                                nil, netann.NodeAnnSetAddrs(newAddrs),
2693
                        )
×
2694
                        if err != nil {
2695
                                srvrLog.Debugf("Unable to generate new node "+
2696
                                        "announcement: %v", err)
2697
                                continue
UNCOV
2698
                        }
×
UNCOV
2699

×
2700
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2701
                        if err != nil {
×
2702
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2703
                                        "announcement to peers: %v", err)
2704
                                continue
2705
                        }
2706

2707
                        // Finally, update the last IP seen to the current one.
2708
                        s.lastDetectedIP = ip
2709
                case <-s.quit:
2710
                        break out
×
UNCOV
2711
                }
×
UNCOV
2712
        }
×
UNCOV
2713
}
×
UNCOV
2714

×
UNCOV
2715
// initNetworkBootstrappers initializes a set of network peer bootstrappers
×
UNCOV
2716
// based on the server, and currently active bootstrap mechanisms as defined
×
UNCOV
2717
// within the current configuration.
×
2718
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2719
        srvrLog.Infof("Initializing peer network bootstrappers!")
2720

2721
        var bootStrappers []discovery.NetworkPeerBootstrapper
2722

2723
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
2724
        // this can be used by default if we've already partially seeded the
×
2725
        // network.
×
2726
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
2727
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
2728
        if err != nil {
2729
                return nil, err
2730
        }
2731
        bootStrappers = append(bootStrappers, graphBootstrapper)
2732

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

×
2738
                // If we have a set of DNS seeds for this chain, then we'll add
×
2739
                // it as an additional bootstrapping source.
2740
                if ok {
2741
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
2742
                                "seeds: %v", dnsSeeds)
×
2743

×
2744
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2745
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2746
                        )
2747
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
2748
                }
UNCOV
2749
        }
×
UNCOV
2750

×
2751
        return bootStrappers, nil
×
2752
}
2753

2754
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
2755
// needs to ignore, which is made of three parts,
2756
//   - the node itself needs to be skipped as it doesn't make sense to connect
2757
//     to itself.
2758
//   - the peers that already have connections with, as in s.peersByPub.
UNCOV
2759
//   - the peers that we are attempting to connect, as in s.persistentPeers.
×
2760
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
2761
        s.mu.RLock()
×
2762
        defer s.mu.RUnlock()
×
2763

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

×
2766
        // We should ignore ourselves from bootstrapping.
×
2767
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2768
        ignore[selfKey] = struct{}{}
×
2769

×
2770
        // Ignore all connected peers.
×
2771
        for _, peer := range s.peersByPub {
×
2772
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2773
                ignore[nID] = struct{}{}
×
2774
        }
×
UNCOV
2775

×
UNCOV
2776
        // Ignore all persistent peers as they have a dedicated reconnecting
×
UNCOV
2777
        // process.
×
2778
        for pubKeyStr := range s.persistentPeers {
×
2779
                var nID autopilot.NodeID
×
2780
                copy(nID[:], []byte(pubKeyStr))
×
2781
                ignore[nID] = struct{}{}
×
2782
        }
×
UNCOV
2783

×
2784
        return ignore
×
UNCOV
2785
}
×
UNCOV
2786

×
UNCOV
2787
// peerBootstrapper is a goroutine which is tasked with attempting to establish
×
UNCOV
2788
// and maintain a target minimum number of outbound connections. With this
×
UNCOV
2789
// invariant, we ensure that our node is connected to a diverse set of peers
×
2790
// and that nodes newly joining the network receive an up to date network view
2791
// as soon as possible.
UNCOV
2792
func (s *server) peerBootstrapper(numTargetPeers uint32,
×
2793
        bootstrappers []discovery.NetworkPeerBootstrapper) {
2794

2795
        defer s.wg.Done()
2796

2797
        // Before we continue, init the ignore peers map.
2798
        ignoreList := s.createBootstrapIgnorePeers()
2799

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

×
2804
        // Once done, we'll attempt to maintain our target minimum number of
×
2805
        // peers.
×
2806
        //
×
2807
        // We'll use a 15 second backoff, and double the time every time an
×
2808
        // epoch fails up to a ceiling.
×
2809
        backOff := time.Second * 15
×
2810

×
2811
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2812
        // see if we've reached our minimum number of peers.
×
2813
        sampleTicker := time.NewTicker(backOff)
×
2814
        defer sampleTicker.Stop()
×
2815

×
2816
        // We'll use the number of attempts and errors to determine if we need
2817
        // to increase the time between discovery epochs.
2818
        var epochErrors uint32 // To be used atomically.
2819
        var epochAttempts uint32
×
2820

×
2821
        for {
×
2822
                select {
×
UNCOV
2823
                // The ticker has just woken us up, so we'll need to check if
×
2824
                // we need to attempt to connect our to any more peers.
2825
                case <-sampleTicker.C:
×
2826
                        // Obtain the current number of peers, so we can gauge
2827
                        // if we need to sample more peers or not.
2828
                        s.mu.RLock()
2829
                        numActivePeers := uint32(len(s.peersByPub))
2830
                        s.mu.RUnlock()
2831

2832
                        // If we have enough peers, then we can loop back
2833
                        // around to the next round as we're done here.
2834
                        if numActivePeers >= numTargetPeers {
×
2835
                                continue
×
UNCOV
2836
                        }
×
UNCOV
2837

×
UNCOV
2838
                        // If all of our attempts failed during this last back
×
UNCOV
2839
                        // off period, then will increase our backoff to 5
×
UNCOV
2840
                        // minute ceiling to avoid an excessive number of
×
UNCOV
2841
                        // queries
×
UNCOV
2842
                        //
×
UNCOV
2843
                        // TODO(roasbeef): add reverse policy too?
×
UNCOV
2844

×
2845
                        if epochAttempts > 0 &&
×
2846
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2847

×
2848
                                sampleTicker.Stop()
×
2849

×
2850
                                backOff *= 2
×
2851
                                if backOff > bootstrapBackOffCeiling {
×
2852
                                        backOff = bootstrapBackOffCeiling
×
2853
                                }
×
UNCOV
2854

×
2855
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2856
                                        "%v", backOff)
×
2857
                                sampleTicker = time.NewTicker(backOff)
×
2858
                                continue
×
UNCOV
2859
                        }
×
UNCOV
2860

×
2861
                        atomic.StoreUint32(&epochErrors, 0)
×
2862
                        epochAttempts = 0
×
2863

×
2864
                        // Since we know need more peers, we'll compute the
2865
                        // exact number we need to reach our threshold.
2866
                        numNeeded := numTargetPeers - numActivePeers
×
2867

×
2868
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2869
                                "peers", numNeeded)
×
2870

×
2871
                        // With the number of peers we need calculated, we'll
×
2872
                        // query the network bootstrappers to sample a set of
×
2873
                        // random addrs for us.
×
2874
                        //
×
2875
                        // Before we continue, get a copy of the ignore peers
×
2876
                        // map.
×
2877
                        ignoreList = s.createBootstrapIgnorePeers()
2878

2879
                        peerAddrs, err := discovery.MultiSourceBootstrap(
2880
                                ignoreList, numNeeded*2, bootstrappers...,
2881
                        )
2882
                        if err != nil {
2883
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
2884
                                        "peers: %v", err)
2885
                                continue
UNCOV
2886
                        }
×
UNCOV
2887

×
UNCOV
2888
                        // Finally, we'll launch a new goroutine for each
×
UNCOV
2889
                        // prospective peer candidates.
×
2890
                        for _, addr := range peerAddrs {
×
2891
                                epochAttempts++
×
2892

×
2893
                                go func(a *lnwire.NetAddress) {
×
2894
                                        // TODO(roasbeef): can do AS, subnet,
×
2895
                                        // country diversity, etc
2896
                                        errChan := make(chan error, 1)
×
2897
                                        s.connectToPeer(
×
2898
                                                a, errChan,
×
2899
                                                s.cfg.ConnectionTimeout,
×
2900
                                        )
2901
                                        select {
2902
                                        case err := <-errChan:
×
2903
                                                if err == nil {
×
2904
                                                        return
×
2905
                                                }
×
UNCOV
2906

×
2907
                                                srvrLog.Errorf("Unable to "+
×
2908
                                                        "connect to %v: %v",
×
2909
                                                        a, err)
×
2910
                                                atomic.AddUint32(&epochErrors, 1)
×
2911
                                        case <-s.quit:
×
UNCOV
2912
                                        }
×
UNCOV
2913
                                }(addr)
×
UNCOV
2914
                        }
×
2915
                case <-s.quit:
×
2916
                        return
×
UNCOV
2917
                }
×
UNCOV
2918
        }
×
UNCOV
2919
}
×
UNCOV
2920

×
UNCOV
2921
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
×
UNCOV
2922
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
×
UNCOV
2923
// query back off each time we encounter a failure.
×
UNCOV
2924
const bootstrapBackOffCeiling = time.Minute * 5
×
UNCOV
2925

×
UNCOV
2926
// initialPeerBootstrap attempts to continuously connect to peers on startup
×
2927
// until the target number of peers has been reached. This ensures that nodes
2928
// receive an up to date network view as soon as possible.
2929
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
2930
        numTargetPeers uint32,
2931
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
2932

×
2933
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
2934
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
2935

×
2936
        // We'll start off by waiting 2 seconds between failed attempts, then
×
2937
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
2938
        var delaySignal <-chan time.Time
×
2939
        delayTime := time.Second * 2
×
2940

×
2941
        // As want to be more aggressive, we'll use a lower back off celling
×
2942
        // then the main peer bootstrap logic.
×
2943
        backOffCeiling := bootstrapBackOffCeiling / 5
×
2944

×
2945
        for attempts := 0; ; attempts++ {
×
2946
                // Check if the server has been requested to shut down in order
×
2947
                // to prevent blocking.
2948
                if s.Stopped() {
×
2949
                        return
×
2950
                }
×
UNCOV
2951

×
UNCOV
2952
                // We can exit our aggressive initial peer bootstrapping stage
×
2953
                // if we've reached out target number of peers.
2954
                s.mu.RLock()
2955
                numActivePeers := uint32(len(s.peersByPub))
2956
                s.mu.RUnlock()
×
2957

×
2958
                if numActivePeers >= numTargetPeers {
2959
                        return
2960
                }
2961

2962
                if attempts > 0 {
2963
                        srvrLog.Debugf("Waiting %v before trying to locate "+
2964
                                "bootstrap peers (attempt #%v)", delayTime,
2965
                                attempts)
2966

2967
                        // We've completed at least one iterating and haven't
2968
                        // finished, so we'll start to insert a delay period
2969
                        // between each attempt.
2970
                        delaySignal = time.After(delayTime)
2971
                        select {
2972
                        case <-delaySignal:
×
2973
                        case <-s.quit:
×
2974
                                return
×
UNCOV
2975
                        }
×
UNCOV
2976

×
UNCOV
2977
                        // After our delay, we'll double the time we wait up to
×
UNCOV
2978
                        // the max back off period.
×
2979
                        delayTime *= 2
×
2980
                        if delayTime > backOffCeiling {
×
2981
                                delayTime = backOffCeiling
×
2982
                        }
×
UNCOV
2983
                }
×
UNCOV
2984

×
UNCOV
2985
                // Otherwise, we'll request for the remaining number of peers
×
UNCOV
2986
                // in order to reach our target.
×
2987
                peersNeeded := numTargetPeers - numActivePeers
×
2988
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
2989
                        ignore, peersNeeded, bootstrappers...,
×
2990
                )
×
2991
                if err != nil {
×
2992
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
2993
                                "peers: %v", err)
2994
                        continue
UNCOV
2995
                }
×
UNCOV
2996

×
UNCOV
2997
                // Then, we'll attempt to establish a connection to the
×
UNCOV
2998
                // different peer addresses retrieved by our bootstrappers.
×
2999
                var wg sync.WaitGroup
×
3000
                for _, bootstrapAddr := range bootstrapAddrs {
×
3001
                        wg.Add(1)
×
3002
                        go func(addr *lnwire.NetAddress) {
3003
                                defer wg.Done()
×
3004

×
3005
                                errChan := make(chan error, 1)
×
3006
                                go s.connectToPeer(
×
3007
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3008
                                )
×
3009

×
3010
                                // We'll only allow this connection attempt to
×
3011
                                // take up to 3 seconds. This allows us to move
×
3012
                                // quickly by discarding peers that are slowing
×
3013
                                // us down.
×
3014
                                select {
×
3015
                                case err := <-errChan:
×
3016
                                        if err == nil {
3017
                                                return
3018
                                        }
3019
                                        srvrLog.Errorf("Unable to connect to "+
3020
                                                "%v: %v", addr, err)
×
UNCOV
3021
                                // TODO: tune timeout? 3 seconds might be *too*
×
UNCOV
3022
                                // aggressive but works well.
×
3023
                                case <-time.After(3 * time.Second):
×
3024
                                        srvrLog.Tracef("Skipping peer %v due "+
3025
                                                "to not establishing a "+
3026
                                                "connection within 3 seconds",
3027
                                                addr)
3028
                                case <-s.quit:
×
UNCOV
3029
                                }
×
UNCOV
3030
                        }(bootstrapAddr)
×
UNCOV
3031
                }
×
UNCOV
3032

×
3033
                wg.Wait()
×
UNCOV
3034
        }
×
UNCOV
3035
}
×
3036

3037
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3038
// order to listen for inbound connections over Tor.
3039
func (s *server) createNewHiddenService() error {
3040
        // Determine the different ports the server is listening on. The onion
×
3041
        // service's virtual port will map to these ports and one will be picked
×
3042
        // at random when the onion service is being accessed.
×
3043
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3044
        for _, listenAddr := range s.listenAddrs {
×
3045
                port := listenAddr.(*net.TCPAddr).Port
×
3046
                listenPorts = append(listenPorts, port)
×
3047
        }
×
UNCOV
3048

×
3049
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3050
        if err != nil {
×
3051
                return err
×
3052
        }
×
UNCOV
3053

×
UNCOV
3054
        // Once the port mapping has been set, we can go ahead and automatically
×
UNCOV
3055
        // create our onion service. The service's private key will be saved to
×
UNCOV
3056
        // disk in order to regain access to this service when restarting `lnd`.
×
3057
        onionCfg := tor.AddOnionConfig{
×
3058
                VirtualPort: defaultPeerPort,
×
3059
                TargetPorts: listenPorts,
×
3060
                Store: tor.NewOnionFile(
×
3061
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3062
                        encrypter,
3063
                ),
3064
        }
×
3065

×
3066
        switch {
×
3067
        case s.cfg.Tor.V2:
×
3068
                onionCfg.Type = tor.V2
×
3069
        case s.cfg.Tor.V3:
×
3070
                onionCfg.Type = tor.V3
3071
        }
3072

3073
        addr, err := s.torController.AddOnion(onionCfg)
3074
        if err != nil {
×
3075
                return err
3076
        }
3077

3078
        // Now that the onion service has been created, we'll add the onion
3079
        // address it can be reached at to our list of advertised addresses.
3080
        newNodeAnn, err := s.genNodeAnnouncement(
×
3081
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3082
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3083
                },
×
UNCOV
3084
        )
×
3085
        if err != nil {
×
3086
                return fmt.Errorf("unable to generate new node "+
×
3087
                        "announcement: %v", err)
×
3088
        }
×
3089

UNCOV
3090
        // Finally, we'll update the on-disk version of our announcement so it
×
UNCOV
3091
        // will eventually propagate to nodes in the network.
×
3092
        selfNode := &channeldb.LightningNode{
×
3093
                HaveNodeAnnouncement: true,
×
3094
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
3095
                Addresses:            newNodeAnn.Addresses,
3096
                Alias:                newNodeAnn.Alias.String(),
3097
                Features: lnwire.NewFeatureVector(
3098
                        newNodeAnn.Features, lnwire.Features,
×
3099
                ),
×
3100
                Color:        newNodeAnn.RGBColor,
×
3101
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3102
        }
×
3103
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3104
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3105
                return fmt.Errorf("can't set self node: %w", err)
×
3106
        }
×
UNCOV
3107

×
3108
        return nil
×
UNCOV
3109
}
×
UNCOV
3110

×
UNCOV
3111
// findChannel finds a channel given a public key and ChannelID. It is an
×
3112
// optimization that is quicker than seeking for a channel given only the
3113
// ChannelID.
UNCOV
3114
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
×
UNCOV
3115
        *channeldb.OpenChannel, error) {
×
UNCOV
3116

×
UNCOV
3117
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3118
        if err != nil {
3119
                return nil, err
3120
        }
UNCOV
3121

×
UNCOV
3122
        for _, channel := range nodeChans {
×
UNCOV
3123
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
UNCOV
3124
                        return channel, nil
×
3125
                }
UNCOV
3126
        }
×
UNCOV
3127

×
UNCOV
3128
        return nil, fmt.Errorf("unable to find channel")
×
UNCOV
3129
}
×
3130

3131
// getNodeAnnouncement fetches the current, fully signed node announcement.
3132
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
UNCOV
3133
        s.mu.Lock()
×
UNCOV
3134
        defer s.mu.Unlock()
×
UNCOV
3135

×
UNCOV
3136
        return *s.currentNodeAnn
×
UNCOV
3137
}
×
UNCOV
3138

×
UNCOV
3139
// genNodeAnnouncement generates and returns the current fully signed node
×
UNCOV
3140
// announcement. The time stamp of the announcement will be updated in order
×
UNCOV
3141
// to ensure it propagates through the network.
×
UNCOV
3142
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
×
UNCOV
3143
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
×
UNCOV
3144

×
UNCOV
3145
        s.mu.Lock()
×
UNCOV
3146
        defer s.mu.Unlock()
×
UNCOV
3147

×
3148
        // First, try to update our feature manager with the updated set of
UNCOV
3149
        // features.
×
3150
        if features != nil {
3151
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3152
                        feature.SetNodeAnn: features,
3153
                }
3154
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3155
                if err != nil {
UNCOV
3156
                        return lnwire.NodeAnnouncement{}, err
×
UNCOV
3157
                }
×
UNCOV
3158

×
UNCOV
3159
                // If we could successfully update our feature manager, add
×
UNCOV
3160
                // an update modifier to include these new features to our
×
UNCOV
3161
                // set.
×
3162
                modifiers = append(
UNCOV
3163
                        modifiers, netann.NodeAnnSetFeatures(features),
×
UNCOV
3164
                )
×
UNCOV
3165
        }
×
UNCOV
3166

×
3167
        // Always update the timestamp when refreshing to ensure the update
3168
        // propagates.
UNCOV
3169
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
×
3170

3171
        // Apply the requested changes to the node announcement.
3172
        for _, modifier := range modifiers {
UNCOV
3173
                modifier(s.currentNodeAnn)
×
UNCOV
3174
        }
×
UNCOV
3175

×
UNCOV
3176
        // Sign a new update after applying all of the passed modifiers.
×
UNCOV
3177
        err := netann.SignNodeAnnouncement(
×
UNCOV
3178
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
3179
        )
3180
        if err != nil {
3181
                return lnwire.NodeAnnouncement{}, err
3182
        }
3183

UNCOV
3184
        return *s.currentNodeAnn, nil
×
UNCOV
3185
}
×
UNCOV
3186

×
UNCOV
3187
// updateAndBrodcastSelfNode generates a new node announcement
×
UNCOV
3188
// applying the giving modifiers and updating the time stamp
×
UNCOV
3189
// to ensure it propagates through the network. Then it brodcasts
×
UNCOV
3190
// it to the network.
×
UNCOV
3191
func (s *server) updateAndBrodcastSelfNode(features *lnwire.RawFeatureVector,
×
UNCOV
3192
        modifiers ...netann.NodeAnnModifier) error {
×
UNCOV
3193

×
UNCOV
3194
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
×
UNCOV
3195
        if err != nil {
×
UNCOV
3196
                return fmt.Errorf("unable to generate new node "+
×
UNCOV
3197
                        "announcement: %v", err)
×
UNCOV
3198
        }
×
3199

3200
        // Update the on-disk version of our announcement.
3201
        // Load and modify self node istead of creating anew instance so we
3202
        // don't risk overwriting any existing values.
UNCOV
3203
        selfNode, err := s.graphDB.SourceNode()
×
UNCOV
3204
        if err != nil {
×
3205
                return fmt.Errorf("unable to get current source node: %w", err)
×
3206
        }
3207

3208
        selfNode.HaveNodeAnnouncement = true
3209
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
UNCOV
3210
        selfNode.Addresses = newNodeAnn.Addresses
×
UNCOV
3211
        selfNode.Alias = newNodeAnn.Alias.String()
×
UNCOV
3212
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
×
UNCOV
3213
        selfNode.Color = newNodeAnn.RGBColor
×
UNCOV
3214
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
×
UNCOV
3215

×
3216
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3217

UNCOV
3218
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3219
                return fmt.Errorf("can't set self node: %w", err)
×
3220
        }
×
UNCOV
3221

×
UNCOV
3222
        // Finally, propagate it to the nodes in the network.
×
UNCOV
3223
        err = s.BroadcastMessage(nil, &newNodeAnn)
×
3224
        if err != nil {
3225
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3226
                        "announcement to peers: %v", err)
3227
                return err
3228
        }
3229

3230
        return nil
3231
}
3232

UNCOV
3233
type nodeAddresses struct {
×
UNCOV
3234
        pubKey    *btcec.PublicKey
×
UNCOV
3235
        addresses []net.Addr
×
UNCOV
3236
}
×
UNCOV
3237

×
UNCOV
3238
// establishPersistentConnections attempts to establish persistent connections
×
UNCOV
3239
// to all our direct channel collaborators. In order to promote liveness of our
×
3240
// active channels, we instruct the connection manager to attempt to establish
3241
// and maintain persistent connections to all our direct channel counterparties.
3242
func (s *server) establishPersistentConnections() error {
3243
        // nodeAddrsMap stores the combination of node public keys and addresses
UNCOV
3244
        // that we'll attempt to reconnect to. PubKey strings are used as keys
×
UNCOV
3245
        // since other PubKey forms can't be compared.
×
UNCOV
3246
        nodeAddrsMap := map[string]*nodeAddresses{}
×
UNCOV
3247

×
3248
        // Iterate through the list of LinkNodes to find addresses we should
UNCOV
3249
        // attempt to connect to based on our set of previous connections. Set
×
UNCOV
3250
        // the reconnection port to the default peer port.
×
UNCOV
3251
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
×
UNCOV
3252
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
×
3253
                return err
×
3254
        }
×
UNCOV
3255
        for _, node := range linkNodes {
×
UNCOV
3256
                pubStr := string(node.IdentityPub.SerializeCompressed())
×
UNCOV
3257
                nodeAddrs := &nodeAddresses{
×
UNCOV
3258
                        pubKey:    node.IdentityPub,
×
UNCOV
3259
                        addresses: node.Addresses,
×
UNCOV
3260
                }
×
UNCOV
3261
                nodeAddrsMap[pubStr] = nodeAddrs
×
3262
        }
3263

UNCOV
3264
        // After checking our previous connections for addresses to connect to,
×
UNCOV
3265
        // iterate through the nodes in our channel graph to find addresses
×
UNCOV
3266
        // that have been added via NodeAnnouncement messages.
×
UNCOV
3267
        sourceNode, err := s.graphDB.SourceNode()
×
UNCOV
3268
        if err != nil {
×
3269
                return err
×
3270
        }
UNCOV
3271

×
3272
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3273
        // each of the nodes.
3274
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3275
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3276
                tx kvdb.RTx,
3277
                chanInfo *models.ChannelEdgeInfo,
3278
                policy, _ *models.ChannelEdgePolicy) error {
3279

3280
                // If the remote party has announced the channel to us, but we
3281
                // haven't yet, then we won't have a policy. However, we don't
3282
                // need this to connect to the peer, so we'll log it and move on.
UNCOV
3283
                if policy == nil {
×
3284
                        srvrLog.Warnf("No channel policy found for "+
×
3285
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3286
                }
×
UNCOV
3287

×
UNCOV
3288
                // We'll now fetch the peer opposite from us within this
×
UNCOV
3289
                // channel so we can queue up a direct connection to them.
×
UNCOV
3290
                channelPeer, err := s.graphDB.FetchOtherNode(
×
UNCOV
3291
                        tx, chanInfo, selfPub,
×
UNCOV
3292
                )
×
UNCOV
3293
                if err != nil {
×
3294
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3295
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3296
                                err)
×
3297
                }
×
UNCOV
3298

×
UNCOV
3299
                pubStr := string(channelPeer.PubKeyBytes[:])
×
UNCOV
3300

×
UNCOV
3301
                // Add all unique addresses from channel
×
UNCOV
3302
                // graph/NodeAnnouncements to the list of addresses we'll
×
UNCOV
3303
                // connect to for this peer.
×
3304
                addrSet := make(map[string]net.Addr)
3305
                for _, addr := range channelPeer.Addresses {
3306
                        switch addr.(type) {
3307
                        case *net.TCPAddr:
UNCOV
3308
                                addrSet[addr.String()] = addr
×
UNCOV
3309

×
UNCOV
3310
                        // We'll only attempt to connect to Tor addresses if Tor
×
UNCOV
3311
                        // outbound support is enabled.
×
3312
                        case *tor.OnionAddr:
3313
                                if s.cfg.Tor.Active {
3314
                                        addrSet[addr.String()] = addr
3315
                                }
×
UNCOV
3316
                        }
×
UNCOV
3317
                }
×
UNCOV
3318

×
UNCOV
3319
                // If this peer is also recorded as a link node, we'll add any
×
UNCOV
3320
                // additional addresses that have not already been selected.
×
UNCOV
3321
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
×
UNCOV
3322
                if ok {
×
UNCOV
3323
                        for _, lnAddress := range linkNodeAddrs.addresses {
×
UNCOV
3324
                                switch lnAddress.(type) {
×
UNCOV
3325
                                case *net.TCPAddr:
×
UNCOV
3326
                                        addrSet[lnAddress.String()] = lnAddress
×
UNCOV
3327

×
3328
                                // We'll only attempt to connect to Tor
3329
                                // addresses if Tor outbound support is enabled.
3330
                                case *tor.OnionAddr:
3331
                                        if s.cfg.Tor.Active {
×
3332
                                                addrSet[lnAddress.String()] = lnAddress
×
3333
                                        }
×
UNCOV
3334
                                }
×
UNCOV
3335
                        }
×
UNCOV
3336
                }
×
UNCOV
3337

×
UNCOV
3338
                // Construct a slice of the deduped addresses.
×
3339
                var addrs []net.Addr
UNCOV
3340
                for _, addr := range addrSet {
×
UNCOV
3341
                        addrs = append(addrs, addr)
×
UNCOV
3342
                }
×
UNCOV
3343

×
UNCOV
3344
                n := &nodeAddresses{
×
UNCOV
3345
                        addresses: addrs,
×
UNCOV
3346
                }
×
UNCOV
3347
                n.pubKey, err = channelPeer.PubKey()
×
UNCOV
3348
                if err != nil {
×
3349
                        return err
×
3350
                }
3351

3352
                nodeAddrsMap[pubStr] = n
UNCOV
3353
                return nil
×
UNCOV
3354
        })
×
UNCOV
3355
        if err != nil && err != channeldb.ErrGraphNoEdgesFound {
×
3356
                return err
×
3357
        }
3358

3359
        srvrLog.Debugf("Establishing %v persistent connections on start",
3360
                len(nodeAddrsMap))
3361

UNCOV
3362
        // Acquire and hold server lock until all persistent connection requests
×
UNCOV
3363
        // have been recorded and sent to the connection manager.
×
UNCOV
3364
        s.mu.Lock()
×
UNCOV
3365
        defer s.mu.Unlock()
×
UNCOV
3366

×
UNCOV
3367
        // Iterate through the combined list of addresses from prior links and
×
3368
        // node announcements and attempt to reconnect to each node.
3369
        var numOutboundConns int
3370
        for pubStr, nodeAddr := range nodeAddrsMap {
UNCOV
3371
                // Add this peer to the set of peers we should maintain a
×
UNCOV
3372
                // persistent connection with. We set the value to false to
×
UNCOV
3373
                // indicate that we should not continue to reconnect if the
×
UNCOV
3374
                // number of channels returns to zero, since this peer has not
×
3375
                // been requested as perm by the user.
3376
                s.persistentPeers[pubStr] = false
3377
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
3378
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3379
                }
UNCOV
3380

×
UNCOV
3381
                for _, address := range nodeAddr.addresses {
×
UNCOV
3382
                        // Create a wrapper address which couples the IP and
×
UNCOV
3383
                        // the pubkey so the brontide authenticated connection
×
3384
                        // can be established.
UNCOV
3385
                        lnAddr := &lnwire.NetAddress{
×
UNCOV
3386
                                IdentityKey: nodeAddr.pubKey,
×
UNCOV
3387
                                Address:     address,
×
UNCOV
3388
                        }
×
UNCOV
3389

×
UNCOV
3390
                        s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
3391
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3392
                }
UNCOV
3393

×
UNCOV
3394
                // We'll connect to the first 10 peers immediately, then
×
3395
                // randomly stagger any remaining connections if the
UNCOV
3396
                // stagger initial reconnect flag is set. This ensures
×
UNCOV
3397
                // that mobile nodes or nodes with a small number of
×
UNCOV
3398
                // channels obtain connectivity quickly, but larger
×
3399
                // nodes are able to disperse the costs of connecting to
UNCOV
3400
                // all peers at once.
×
UNCOV
3401
                if numOutboundConns < numInstantInitReconnect ||
×
UNCOV
3402
                        !s.cfg.StaggerInitialReconnect {
×
UNCOV
3403

×
UNCOV
3404
                        go s.connectToPersistentPeer(pubStr)
×
UNCOV
3405
                } else {
×
3406
                        go s.delayInitialReconnect(pubStr)
×
3407
                }
×
UNCOV
3408

×
UNCOV
3409
                numOutboundConns++
×
UNCOV
3410
        }
×
UNCOV
3411

×
UNCOV
3412
        return nil
×
UNCOV
3413
}
×
UNCOV
3414

×
UNCOV
3415
// delayInitialReconnect will attempt a reconnection to the given peer after
×
UNCOV
3416
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
×
UNCOV
3417
//
×
UNCOV
3418
// NOTE: This method MUST be run as a goroutine.
×
3419
func (s *server) delayInitialReconnect(pubStr string) {
×
3420
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3421
        select {
3422
        case <-time.After(delay):
×
3423
                s.connectToPersistentPeer(pubStr)
×
3424
        case <-s.quit:
×
UNCOV
3425
        }
×
UNCOV
3426
}
×
UNCOV
3427

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

×
3434
        s.mu.Lock()
3435
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
3436
                delete(s.persistentPeers, pubKeyStr)
3437
                delete(s.persistentPeersBackoff, pubKeyStr)
3438
                delete(s.persistentPeerAddrs, pubKeyStr)
3439
                s.cancelConnReqs(pubKeyStr, nil)
3440
                s.mu.Unlock()
3441

UNCOV
3442
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
×
UNCOV
3443
                        "peer has no open channels", compressedPubKey)
×
UNCOV
3444

×
UNCOV
3445
                return
×
UNCOV
3446
        }
×
UNCOV
3447
        s.mu.Unlock()
×
UNCOV
3448
}
×
3449

UNCOV
3450
// BroadcastMessage sends a request to the server to broadcast a set of
×
3451
// messages to all peers other than the one specified by the `skips` parameter.
3452
// All messages sent via BroadcastMessage will be queued for lazy delivery to
UNCOV
3453
// the target peers.
×
3454
//
3455
// NOTE: This function is safe for concurrent access.
3456
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3457
        msgs ...lnwire.Message) error {
3458

3459
        // Filter out peers found in the skips map. We synchronize access to
UNCOV
3460
        // peersByPub throughout this process to ensure we deliver messages to
×
UNCOV
3461
        // exact set of peers present at the time of invocation.
×
UNCOV
3462
        s.mu.RLock()
×
UNCOV
3463
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
3464
        for pubStr, sPeer := range s.peersByPub {
×
UNCOV
3465
                if skips != nil {
×
3466
                        if _, ok := skips[sPeer.PubKey()]; ok {
3467
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3468
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3469
                                continue
3470
                        }
3471
                }
UNCOV
3472

×
UNCOV
3473
                peers = append(peers, sPeer)
×
UNCOV
3474
        }
×
UNCOV
3475
        s.mu.RUnlock()
×
UNCOV
3476

×
UNCOV
3477
        // Iterate over all known peers, dispatching a go routine to enqueue
×
UNCOV
3478
        // all messages to each of peers.
×
UNCOV
3479
        var wg sync.WaitGroup
×
UNCOV
3480
        for _, sPeer := range peers {
×
UNCOV
3481
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
×
UNCOV
3482
                        sPeer.PubKey())
×
UNCOV
3483

×
UNCOV
3484
                // Dispatch a go routine to enqueue all messages to this peer.
×
UNCOV
3485
                wg.Add(1)
×
UNCOV
3486
                s.wg.Add(1)
×
UNCOV
3487
                go func(p lnpeer.Peer) {
×
UNCOV
3488
                        defer s.wg.Done()
×
3489
                        defer wg.Done()
3490

3491
                        p.SendMessageLazy(false, msgs...)
3492
                }(sPeer)
3493
        }
3494

3495
        // Wait for all messages to have been dispatched before returning to
3496
        // caller.
3497
        wg.Wait()
UNCOV
3498

×
UNCOV
3499
        return nil
×
UNCOV
3500
}
×
UNCOV
3501

×
UNCOV
3502
// NotifyWhenOnline can be called by other subsystems to get notified when a
×
UNCOV
3503
// particular peer comes online. The peer itself is sent across the peerChan.
×
UNCOV
3504
//
×
UNCOV
3505
// NOTE: This function is safe for concurrent access.
×
UNCOV
3506
func (s *server) NotifyWhenOnline(peerKey [33]byte,
×
UNCOV
3507
        peerChan chan<- lnpeer.Peer) {
×
UNCOV
3508

×
UNCOV
3509
        s.mu.Lock()
×
UNCOV
3510

×
3511
        // Compute the target peer's identifier.
3512
        pubStr := string(peerKey[:])
3513

UNCOV
3514
        // Check if peer is connected.
×
3515
        peer, ok := s.peersByPub[pubStr]
UNCOV
3516
        if ok {
×
UNCOV
3517
                // Unlock here so that the mutex isn't held while we are
×
UNCOV
3518
                // waiting for the peer to become active.
×
UNCOV
3519
                s.mu.Unlock()
×
UNCOV
3520

×
UNCOV
3521
                // Wait until the peer signals that it is actually active
×
UNCOV
3522
                // rather than only in the server's maps.
×
UNCOV
3523
                select {
×
UNCOV
3524
                case <-peer.ActiveSignal():
×
3525
                case <-peer.QuitSignal():
×
3526
                        // The peer quit, so we'll add the channel to the slice
×
3527
                        // and return.
×
3528
                        s.mu.Lock()
×
3529
                        s.peerConnectedListeners[pubStr] = append(
×
3530
                                s.peerConnectedListeners[pubStr], peerChan,
×
3531
                        )
×
3532
                        s.mu.Unlock()
×
3533
                        return
×
3534
                }
3535

3536
                // Connected, can return early.
3537
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
UNCOV
3538

×
UNCOV
3539
                select {
×
UNCOV
3540
                case peerChan <- peer:
×
3541
                case <-s.quit:
3542
                }
3543

3544
                return
3545
        }
3546

3547
        // Not connected, store this listener such that it can be notified when
UNCOV
3548
        // the peer comes online.
×
UNCOV
3549
        s.peerConnectedListeners[pubStr] = append(
×
UNCOV
3550
                s.peerConnectedListeners[pubStr], peerChan,
×
UNCOV
3551
        )
×
UNCOV
3552
        s.mu.Unlock()
×
UNCOV
3553
}
×
UNCOV
3554

×
UNCOV
3555
// NotifyWhenOffline delivers a notification to the caller of when the peer with
×
UNCOV
3556
// the given public key has been disconnected. The notification is signaled by
×
UNCOV
3557
// closing the channel returned.
×
UNCOV
3558
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
×
UNCOV
3559
        s.mu.Lock()
×
UNCOV
3560
        defer s.mu.Unlock()
×
UNCOV
3561

×
UNCOV
3562
        c := make(chan struct{})
×
UNCOV
3563

×
UNCOV
3564
        // If the peer is already offline, we can immediately trigger the
×
UNCOV
3565
        // notification.
×
UNCOV
3566
        peerPubKeyStr := string(peerPubKey[:])
×
UNCOV
3567
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
×
3568
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3569
                close(c)
×
3570
                return c
×
3571
        }
×
UNCOV
3572

×
UNCOV
3573
        // Otherwise, the peer is online, so we'll keep track of the channel to
×
UNCOV
3574
        // trigger the notification once the server detects the peer
×
3575
        // disconnects.
3576
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3577
                s.peerDisconnectedListeners[peerPubKeyStr], c,
UNCOV
3578
        )
×
UNCOV
3579

×
UNCOV
3580
        return c
×
UNCOV
3581
}
×
UNCOV
3582

×
3583
// FindPeer will return the peer that corresponds to the passed in public key.
3584
// This function is used by the funding manager, allowing it to update the
UNCOV
3585
// daemon's local representation of the remote peer.
×
3586
//
3587
// NOTE: This function is safe for concurrent access.
3588
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3589
        s.mu.RLock()
UNCOV
3590
        defer s.mu.RUnlock()
×
UNCOV
3591

×
UNCOV
3592
        pubStr := string(peerKey.SerializeCompressed())
×
UNCOV
3593

×
3594
        return s.findPeerByPubStr(pubStr)
3595
}
3596

3597
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3598
// which should be a string representation of the peer's serialized, compressed
UNCOV
3599
// public key.
×
UNCOV
3600
//
×
UNCOV
3601
// NOTE: This function is safe for concurrent access.
×
UNCOV
3602
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3603
        s.mu.RLock()
×
UNCOV
3604
        defer s.mu.RUnlock()
×
UNCOV
3605

×
UNCOV
3606
        return s.findPeerByPubStr(pubStr)
×
UNCOV
3607
}
×
UNCOV
3608

×
UNCOV
3609
// findPeerByPubStr is an internal method that retrieves the specified peer from
×
UNCOV
3610
// the server's internal state using.
×
UNCOV
3611
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
UNCOV
3612
        peer, ok := s.peersByPub[pubStr]
×
3613
        if !ok {
3614
                return nil, ErrPeerNotConnected
3615
        }
3616

UNCOV
3617
        return peer, nil
×
UNCOV
3618
}
×
UNCOV
3619

×
UNCOV
3620
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
×
UNCOV
3621
// exponential backoff. If no previous backoff was known, the default is
×
3622
// returned.
3623
func (s *server) nextPeerBackoff(pubStr string,
3624
        startTime time.Time) time.Duration {
3625

3626
        // Now, determine the appropriate backoff to use for the retry.
3627
        backoff, ok := s.persistentPeersBackoff[pubStr]
3628
        if !ok {
UNCOV
3629
                // If an existing backoff was unknown, use the default.
×
UNCOV
3630
                return s.cfg.MinBackoff
×
UNCOV
3631
        }
×
UNCOV
3632

×
UNCOV
3633
        // If the peer failed to start properly, we'll just use the previous
×
UNCOV
3634
        // backoff to compute the subsequent randomized exponential backoff
×
UNCOV
3635
        // duration. This will roughly double on average.
×
UNCOV
3636
        if startTime.IsZero() {
×
3637
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3638
        }
3639

3640
        // The peer succeeded in starting. If the connection didn't last long
3641
        // enough to be considered stable, we'll continue to back off retries
3642
        // with this peer.
UNCOV
3643
        connDuration := time.Since(startTime)
×
UNCOV
3644
        if connDuration < defaultStableConnDuration {
×
UNCOV
3645
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
UNCOV
3646
        }
×
UNCOV
3647

×
UNCOV
3648
        // The peer succeed in starting and this was stable peer, so we'll
×
3649
        // reduce the timeout duration by the length of the connection after
3650
        // applying randomized exponential backoff. We'll only apply this in the
3651
        // case that:
UNCOV
3652
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
×
3653
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3654
        if relaxedBackoff > s.cfg.MinBackoff {
×
3655
                return relaxedBackoff
×
3656
        }
×
3657

UNCOV
3658
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
×
3659
        // the stable connection lasted much longer than our previous backoff.
3660
        // To reward such good behavior, we'll reconnect after the default
3661
        // timeout.
3662
        return s.cfg.MinBackoff
3663
}
3664

UNCOV
3665
// shouldDropLocalConnection determines if our local connection to a remote peer
×
UNCOV
3666
// should be dropped in the case of concurrent connection establishment. In
×
UNCOV
3667
// order to deterministically decide which connection should be dropped, we'll
×
UNCOV
3668
// utilize the ordering of the local and remote public key. If we didn't use
×
UNCOV
3669
// such a tie breaker, then we risk _both_ connections erroneously being
×
UNCOV
3670
// dropped.
×
3671
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3672
        localPubBytes := local.SerializeCompressed()
×
3673
        remotePubPbytes := remote.SerializeCompressed()
3674

3675
        // The connection that comes from the node with a "smaller" pubkey
3676
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
3677
        // should drop our established connection.
×
3678
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3679
}
×
3680

3681
// InboundPeerConnected initializes a new peer in response to a new inbound
3682
// connection.
3683
//
UNCOV
3684
// NOTE: This function is safe for concurrent access.
×
UNCOV
3685
func (s *server) InboundPeerConnected(conn net.Conn) {
×
UNCOV
3686
        // Exit early if we have already been instructed to shutdown, this
×
UNCOV
3687
        // prevents any delayed callbacks from accidentally registering peers.
×
3688
        if s.Stopped() {
3689
                return
3690
        }
3691

3692
        nodePub := conn.(*brontide.Conn).RemotePub()
3693
        pubSer := nodePub.SerializeCompressed()
UNCOV
3694
        pubStr := string(pubSer)
×
UNCOV
3695

×
UNCOV
3696
        var pubBytes [33]byte
×
UNCOV
3697
        copy(pubBytes[:], pubSer)
×
3698

3699
        s.mu.Lock()
3700
        defer s.mu.Unlock()
3701

3702
        // If the remote node's public key is banned, drop the connection.
UNCOV
3703
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
3704
        if dcErr != nil {
3705
                srvrLog.Errorf("Unable to check if we should disconnect "+
3706
                        "peer: %v", dcErr)
3707
                conn.Close()
3708

3709
                return
3710
        }
3711

UNCOV
3712
        if shouldDc {
×
3713
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3714
                        "banned.", pubSer)
×
3715

×
3716
                conn.Close()
×
3717

×
3718
                return
×
3719
        }
×
UNCOV
3720

×
3721
        // If we already have an outbound connection to this peer, then ignore
3722
        // this new connection.
3723
        if p, ok := s.outboundPeers[pubStr]; ok {
3724
                srvrLog.Debugf("Already have outbound connection for %v, "+
3725
                        "ignoring inbound connection from local=%v, remote=%v",
UNCOV
3726
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3727

×
UNCOV
3728
                conn.Close()
×
UNCOV
3729
                return
×
UNCOV
3730
        }
×
UNCOV
3731

×
3732
        // If we already have a valid connection that is scheduled to take
UNCOV
3733
        // precedence once the prior peer has finished disconnecting, we'll
×
UNCOV
3734
        // ignore this connection.
×
UNCOV
3735
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3736
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
3737
                        "scheduled", conn.RemoteAddr(), p)
×
3738
                conn.Close()
×
3739
                return
×
3740
        }
×
UNCOV
3741

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

×
UNCOV
3744
        // Check to see if we already have a connection with this peer. If so,
×
UNCOV
3745
        // we may need to drop our existing connection. This prevents us from
×
UNCOV
3746
        // having duplicate connections to the same peer. We forgo adding a
×
UNCOV
3747
        // default case as we expect these to be the only error values returned
×
UNCOV
3748
        // from findPeerByPubStr.
×
UNCOV
3749
        connectedPeer, err := s.findPeerByPubStr(pubStr)
×
UNCOV
3750
        switch err {
×
UNCOV
3751
        case ErrPeerNotConnected:
×
3752
                // We were unable to locate an existing connection with the
UNCOV
3753
                // target peer, proceed to connect.
×
UNCOV
3754
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3755
                s.peerConnected(conn, nil, true)
×
UNCOV
3756

×
3757
        case nil:
×
3758
                // We already have a connection with the incoming peer. If the
×
3759
                // connection we've already established should be kept and is
×
3760
                // not of the same type of the new connection (inbound), then
×
3761
                // we'll close out the new connection s.t there's only a single
3762
                // connection between us.
3763
                localPub := s.identityECDH.PubKey()
3764
                if !connectedPeer.Inbound() &&
×
3765
                        !shouldDropLocalConnection(localPub, nodePub) {
×
3766

×
3767
                        srvrLog.Warnf("Received inbound connection from "+
×
3768
                                "peer %v, but already have outbound "+
×
3769
                                "connection, dropping conn", connectedPeer)
×
3770
                        conn.Close()
×
3771
                        return
×
3772
                }
3773

3774
                // Otherwise, if we should drop the connection, then we'll
3775
                // disconnect our already connected peer.
3776
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3777
                        connectedPeer)
×
3778

×
3779
                s.cancelConnReqs(pubStr, nil)
×
3780

×
3781
                // Remove the current peer from the server's internal state and
×
3782
                // signal that the peer termination watcher does not need to
3783
                // execute for this peer.
×
3784
                s.removePeer(connectedPeer)
×
3785
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
3786
                s.scheduledPeerConnection[pubStr] = func() {
×
3787
                        s.peerConnected(conn, nil, true)
×
3788
                }
×
UNCOV
3789
        }
×
UNCOV
3790
}
×
UNCOV
3791

×
UNCOV
3792
// OutboundPeerConnected initializes a new peer in response to a new outbound
×
UNCOV
3793
// connection.
×
UNCOV
3794
// NOTE: This function is safe for concurrent access.
×
UNCOV
3795
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
×
UNCOV
3796
        // Exit early if we have already been instructed to shutdown, this
×
3797
        // prevents any delayed callbacks from accidentally registering peers.
UNCOV
3798
        if s.Stopped() {
×
3799
                return
×
3800
        }
×
UNCOV
3801

×
UNCOV
3802
        nodePub := conn.(*brontide.Conn).RemotePub()
×
UNCOV
3803
        pubSer := nodePub.SerializeCompressed()
×
UNCOV
3804
        pubStr := string(pubSer)
×
UNCOV
3805

×
UNCOV
3806
        var pubBytes [33]byte
×
UNCOV
3807
        copy(pubBytes[:], pubSer)
×
UNCOV
3808

×
UNCOV
3809
        s.mu.Lock()
×
UNCOV
3810
        defer s.mu.Unlock()
×
UNCOV
3811

×
UNCOV
3812
        // If the remote node's public key is banned, drop the connection.
×
UNCOV
3813
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
×
3814
        if dcErr != nil {
3815
                srvrLog.Errorf("Unable to check if we should disconnect "+
3816
                        "peer: %v", dcErr)
3817
                conn.Close()
×
3818

×
3819
                return
×
3820
        }
×
UNCOV
3821

×
UNCOV
3822
        if shouldDc {
×
3823
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3824
                        "banned.", pubSer)
×
3825

×
3826
                if connReq != nil {
×
3827
                        s.connMgr.Remove(connReq.ID())
×
3828
                }
×
UNCOV
3829

×
3830
                conn.Close()
3831

3832
                return
3833
        }
3834

3835
        // If we already have an inbound connection to this peer, then ignore
UNCOV
3836
        // this new connection.
×
UNCOV
3837
        if p, ok := s.inboundPeers[pubStr]; ok {
×
UNCOV
3838
                srvrLog.Debugf("Already have inbound connection for %v, "+
×
UNCOV
3839
                        "ignoring outbound connection from local=%v, remote=%v",
×
UNCOV
3840
                        p, conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
3841

×
3842
                if connReq != nil {
UNCOV
3843
                        s.connMgr.Remove(connReq.ID())
×
UNCOV
3844
                }
×
UNCOV
3845
                conn.Close()
×
UNCOV
3846
                return
×
UNCOV
3847
        }
×
UNCOV
3848
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
×
3849
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3850
                s.connMgr.Remove(connReq.ID())
×
3851
                conn.Close()
×
3852
                return
×
3853
        }
×
UNCOV
3854

×
UNCOV
3855
        // If we already have a valid connection that is scheduled to take
×
UNCOV
3856
        // precedence once the prior peer has finished disconnecting, we'll
×
UNCOV
3857
        // ignore this connection.
×
UNCOV
3858
        if _, ok := s.scheduledPeerConnection[pubStr]; ok {
×
3859
                srvrLog.Debugf("Ignoring connection, peer already scheduled")
×
3860

×
3861
                if connReq != nil {
×
3862
                        s.connMgr.Remove(connReq.ID())
3863
                }
×
UNCOV
3864

×
3865
                conn.Close()
×
3866
                return
×
UNCOV
3867
        }
×
UNCOV
3868

×
UNCOV
3869
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
×
3870
                conn.RemoteAddr())
UNCOV
3871

×
UNCOV
3872
        if connReq != nil {
×
UNCOV
3873
                // A successful connection was returned by the connmgr.
×
3874
                // Immediately cancel all pending requests, excluding the
3875
                // outbound connection we just established.
3876
                ignore := connReq.ID()
3877
                s.cancelConnReqs(pubStr, &ignore)
UNCOV
3878
        } else {
×
UNCOV
3879
                // This was a successful connection made by some other
×
UNCOV
3880
                // subsystem. Remove all requests being managed by the connmgr.
×
UNCOV
3881
                s.cancelConnReqs(pubStr, nil)
×
UNCOV
3882
        }
×
UNCOV
3883

×
UNCOV
3884
        // If we already have a connection with this peer, decide whether or not
×
UNCOV
3885
        // we need to drop the stale connection. We forgo adding a default case
×
UNCOV
3886
        // as we expect these to be the only error values returned from
×
UNCOV
3887
        // findPeerByPubStr.
×
3888
        connectedPeer, err := s.findPeerByPubStr(pubStr)
UNCOV
3889
        switch err {
×
UNCOV
3890
        case ErrPeerNotConnected:
×
UNCOV
3891
                // We were unable to locate an existing connection with the
×
UNCOV
3892
                // target peer, proceed to connect.
×
UNCOV
3893
                s.peerConnected(conn, connReq, false)
×
UNCOV
3894

×
3895
        case nil:
3896
                // We already have a connection with the incoming peer. If the
3897
                // connection we've already established should be kept and is
3898
                // not of the same type of the new connection (outbound), then
3899
                // we'll close out the new connection s.t there's only a single
×
3900
                // connection between us.
×
3901
                localPub := s.identityECDH.PubKey()
×
3902
                if connectedPeer.Inbound() &&
×
3903
                        shouldDropLocalConnection(localPub, nodePub) {
×
3904

×
3905
                        srvrLog.Warnf("Established outbound connection to "+
3906
                                "peer %v, but already have inbound "+
×
3907
                                "connection, dropping conn", connectedPeer)
×
3908
                        if connReq != nil {
3909
                                s.connMgr.Remove(connReq.ID())
3910
                        }
×
3911
                        conn.Close()
×
3912
                        return
×
UNCOV
3913
                }
×
UNCOV
3914

×
UNCOV
3915
                // Otherwise, _their_ connection should be dropped. So we'll
×
UNCOV
3916
                // disconnect the peer and send the now obsolete peer to the
×
UNCOV
3917
                // server for garbage collection.
×
3918
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3919
                        connectedPeer)
×
3920

×
3921
                // Remove the current peer from the server's internal state and
×
3922
                // signal that the peer termination watcher does not need to
×
3923
                // execute for this peer.
×
3924
                s.removePeer(connectedPeer)
3925
                s.ignorePeerTermination[connectedPeer] = struct{}{}
3926
                s.scheduledPeerConnection[pubStr] = func() {
3927
                        s.peerConnected(conn, connReq, false)
3928
                }
UNCOV
3929
        }
×
UNCOV
3930
}
×
UNCOV
3931

×
UNCOV
3932
// UnassignedConnID is the default connection ID that a request can have before
×
UNCOV
3933
// it actually is submitted to the connmgr.
×
UNCOV
3934
// TODO(conner): move into connmgr package, or better, add connmgr method for
×
3935
// generating atomic IDs
UNCOV
3936
const UnassignedConnID uint64 = 0
×
UNCOV
3937

×
UNCOV
3938
// cancelConnReqs stops all persistent connection requests for a given pubkey.
×
UNCOV
3939
// Any attempts initiated by the peerTerminationWatcher are canceled first.
×
UNCOV
3940
// Afterwards, each connection request removed from the connmgr. The caller can
×
UNCOV
3941
// optionally specify a connection ID to ignore, which prevents us from
×
UNCOV
3942
// canceling a successful request. All persistent connreqs for the provided
×
UNCOV
3943
// pubkey are discarded after the operationjw.
×
UNCOV
3944
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
×
UNCOV
3945
        // First, cancel any lingering persistent retry attempts, which will
×
UNCOV
3946
        // prevent retries for any with backoffs that are still maturing.
×
UNCOV
3947
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
×
UNCOV
3948
                close(cancelChan)
×
UNCOV
3949
                delete(s.persistentRetryCancels, pubStr)
×
UNCOV
3950
        }
×
UNCOV
3951

×
UNCOV
3952
        // Next, check to see if we have any outstanding persistent connection
×
UNCOV
3953
        // requests to this peer. If so, then we'll remove all of these
×
3954
        // connection requests, and also delete the entry from the map.
3955
        connReqs, ok := s.persistentConnReqs[pubStr]
3956
        if !ok {
3957
                return
3958
        }
UNCOV
3959

×
UNCOV
3960
        for _, connReq := range connReqs {
×
UNCOV
3961
                srvrLog.Tracef("Canceling %s:", connReqs)
×
UNCOV
3962

×
UNCOV
3963
                // Atomically capture the current request identifier.
×
UNCOV
3964
                connID := connReq.ID()
×
UNCOV
3965

×
UNCOV
3966
                // Skip any zero IDs, this indicates the request has not
×
UNCOV
3967
                // yet been schedule.
×
UNCOV
3968
                if connID == UnassignedConnID {
×
UNCOV
3969
                        continue
×
3970
                }
3971

3972
                // Skip a particular connection ID if instructed.
3973
                if skip != nil && connID == *skip {
3974
                        continue
3975
                }
3976

3977
                s.connMgr.Remove(connID)
3978
        }
3979

3980
        delete(s.persistentConnReqs, pubStr)
3981
}
3982

3983
// handleCustomMessage dispatches an incoming custom peers message to
3984
// subscribers.
UNCOV
3985
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
×
UNCOV
3986
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
×
UNCOV
3987
                peer, msg.Type)
×
UNCOV
3988

×
UNCOV
3989
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
UNCOV
3990
                Peer: peer,
×
UNCOV
3991
                Msg:  msg,
×
3992
        })
3993
}
3994

3995
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
UNCOV
3996
// messages.
×
UNCOV
3997
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
UNCOV
3998
        return s.customMessageServer.Subscribe()
×
UNCOV
3999
}
×
4000

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

×
UNCOV
4008
        brontideConn := conn.(*brontide.Conn)
×
UNCOV
4009
        addr := conn.RemoteAddr()
×
UNCOV
4010
        pubKey := brontideConn.RemotePub()
×
4011

4012
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4013
                pubKey.SerializeCompressed(), addr, inbound)
UNCOV
4014

×
UNCOV
4015
        peerAddr := &lnwire.NetAddress{
×
4016
                IdentityKey: pubKey,
4017
                Address:     addr,
UNCOV
4018
                ChainNet:    s.cfg.ActiveNetParams.Net,
×
4019
        }
4020

UNCOV
4021
        // With the brontide connection established, we'll now craft the feature
×
4022
        // vectors to advertise to the remote node.
4023
        initFeatures := s.featureMgr.Get(feature.SetInit)
4024
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
4025

UNCOV
4026
        // Lookup past error caches for the peer in the server. If no buffer is
×
UNCOV
4027
        // found, create a fresh buffer.
×
UNCOV
4028
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4029
        errBuffer, ok := s.peerErrors[pkStr]
×
UNCOV
4030
        if !ok {
×
UNCOV
4031
                var err error
×
UNCOV
4032
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
×
UNCOV
4033
                if err != nil {
×
4034
                        srvrLog.Errorf("unable to create peer %v", err)
×
4035
                        return
4036
                }
4037
        }
UNCOV
4038

×
UNCOV
4039
        // If we directly set the peer.Config TowerClient member to the
×
UNCOV
4040
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
×
4041
        // the peer.Config's TowerClient member will not evaluate to nil even
4042
        // though the underlying value is nil. To avoid this gotcha which can
4043
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4044
        // TowerClient if needed.
4045
        var towerClient wtclient.ClientManager
4046
        if s.towerClientMgr != nil {
UNCOV
4047
                towerClient = s.towerClientMgr
×
UNCOV
4048
        }
×
UNCOV
4049

×
UNCOV
4050
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
×
UNCOV
4051
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
×
UNCOV
4052

×
UNCOV
4053
        // Now that we've established a connection, create a peer, and it to the
×
UNCOV
4054
        // set of currently active peers. Configure the peer with the incoming
×
UNCOV
4055
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
×
UNCOV
4056
        // offered that would trigger channel closure. In case of outgoing
×
UNCOV
4057
        // htlcs, an extra block is added to prevent the channel from being
×
UNCOV
4058
        // closed when the htlc is outstanding and a new block comes in.
×
UNCOV
4059
        pCfg := peer.Config{
×
UNCOV
4060
                Conn:                    brontideConn,
×
UNCOV
4061
                ConnReq:                 connReq,
×
UNCOV
4062
                Addr:                    peerAddr,
×
UNCOV
4063
                Inbound:                 inbound,
×
UNCOV
4064
                Features:                initFeatures,
×
UNCOV
4065
                LegacyFeatures:          legacyFeatures,
×
UNCOV
4066
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
×
UNCOV
4067
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
×
UNCOV
4068
                ErrorBuffer:             errBuffer,
×
UNCOV
4069
                WritePool:               s.writePool,
×
UNCOV
4070
                ReadPool:                s.readPool,
×
UNCOV
4071
                Switch:                  s.htlcSwitch,
×
UNCOV
4072
                InterceptSwitch:         s.interceptableSwitch,
×
UNCOV
4073
                ChannelDB:               s.chanStateDB,
×
UNCOV
4074
                ChannelGraph:            s.graphDB,
×
UNCOV
4075
                ChainArb:                s.chainArb,
×
UNCOV
4076
                AuthGossiper:            s.authGossiper,
×
UNCOV
4077
                ChanStatusMgr:           s.chanStatusMgr,
×
4078
                ChainIO:                 s.cc.ChainIO,
4079
                FeeEstimator:            s.cc.FeeEstimator,
4080
                Signer:                  s.cc.Wallet.Cfg.Signer,
4081
                SigPool:                 s.sigPool,
4082
                Wallet:                  s.cc.Wallet,
4083
                ChainNotifier:           s.cc.ChainNotifier,
4084
                BestBlockView:           s.cc.BestBlockTracker,
4085
                RoutingPolicy:           s.cc.RoutingPolicy,
UNCOV
4086
                Sphinx:                  s.sphinx,
×
UNCOV
4087
                WitnessBeacon:           s.witnessBeacon,
×
UNCOV
4088
                Invoices:                s.invoices,
×
UNCOV
4089
                ChannelNotifier:         s.channelNotifier,
×
4090
                HtlcNotifier:            s.htlcNotifier,
UNCOV
4091
                TowerClient:             towerClient,
×
UNCOV
4092
                DisconnectPeer:          s.DisconnectPeer,
×
UNCOV
4093
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
×
UNCOV
4094
                        lnwire.NodeAnnouncement, error) {
×
UNCOV
4095

×
UNCOV
4096
                        return s.genNodeAnnouncement(nil)
×
UNCOV
4097
                },
×
UNCOV
4098

×
UNCOV
4099
                PongBuf: s.pongBuf,
×
UNCOV
4100

×
UNCOV
4101
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
×
UNCOV
4102

×
UNCOV
4103
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
×
UNCOV
4104

×
UNCOV
4105
                FundingManager: s.fundingMgr,
×
UNCOV
4106

×
UNCOV
4107
                Hodl:                    s.cfg.Hodl,
×
UNCOV
4108
                UnsafeReplay:            s.cfg.UnsafeReplay,
×
UNCOV
4109
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
×
UNCOV
4110
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
×
UNCOV
4111
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
×
UNCOV
4112
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
×
UNCOV
4113
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
×
UNCOV
4114
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
×
UNCOV
4115
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
×
UNCOV
4116
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
×
UNCOV
4117
                HandleCustomMessage:    s.handleCustomMessage,
×
UNCOV
4118
                GetAliases:             s.aliasMgr.GetAliases,
×
UNCOV
4119
                RequestAlias:           s.aliasMgr.RequestAlias,
×
UNCOV
4120
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
×
UNCOV
4121
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
×
UNCOV
4122
                MaxFeeExposure:         thresholdMSats,
×
UNCOV
4123
                Quit:                   s.quit,
×
UNCOV
4124
                AuxLeafStore:           s.implCfg.AuxLeafStore,
×
UNCOV
4125
                AuxSigner:              s.implCfg.AuxSigner,
×
UNCOV
4126
                MsgRouter:              s.implCfg.MsgRouter,
×
UNCOV
4127
                AuxChanCloser:          s.implCfg.AuxChanCloser,
×
UNCOV
4128
        }
×
UNCOV
4129

×
UNCOV
4130
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
×
UNCOV
4131
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
×
UNCOV
4132

×
UNCOV
4133
        p := peer.NewBrontide(pCfg)
×
UNCOV
4134

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

×
UNCOV
4138
        s.addPeer(p)
×
4139

4140
        // Once we have successfully added the peer to the server, we can
4141
        // delete the previous error buffer from the server's map of error
4142
        // buffers.
4143
        delete(s.peerErrors, pkStr)
4144

4145
        // Dispatch a goroutine to asynchronously start the peer. This process
4146
        // includes sending and receiving Init messages, which would be a DOS
4147
        // vector if we held the server's mutex throughout the procedure.
4148
        s.wg.Add(1)
4149
        go s.peerInitializer(p)
4150
}
4151

4152
// addPeer adds the passed peer to the server's global state of all active
4153
// peers.
4154
func (s *server) addPeer(p *peer.Brontide) {
4155
        if p == nil {
4156
                return
4157
        }
4158

4159
        // Ignore new peers if we're shutting down.
4160
        if s.Stopped() {
4161
                p.Disconnect(ErrServerShuttingDown)
4162
                return
4163
        }
4164

4165
        // Track the new peer in our indexes so we can quickly look it up either
4166
        // according to its public key, or its peer ID.
4167
        // TODO(roasbeef): pipe all requests through to the
4168
        // queryHandler/peerManager
4169

4170
        pubSer := p.IdentityKey().SerializeCompressed()
4171
        pubStr := string(pubSer)
UNCOV
4172

×
UNCOV
4173
        s.peersByPub[pubStr] = p
×
UNCOV
4174

×
UNCOV
4175
        if p.Inbound() {
×
UNCOV
4176
                s.inboundPeers[pubStr] = p
×
UNCOV
4177
        } else {
×
UNCOV
4178
                s.outboundPeers[pubStr] = p
×
UNCOV
4179
        }
×
UNCOV
4180

×
UNCOV
4181
        // Inform the peer notifier of a peer online event so that it can be reported
×
UNCOV
4182
        // to clients listening for peer events.
×
UNCOV
4183
        var pubKey [33]byte
×
UNCOV
4184
        copy(pubKey[:], pubSer)
×
UNCOV
4185

×
UNCOV
4186
        s.peerNotifier.NotifyPeerOnline(pubKey)
×
UNCOV
4187
}
×
UNCOV
4188

×
UNCOV
4189
// peerInitializer asynchronously starts a newly connected peer after it has
×
UNCOV
4190
// been added to the server's peer map. This method sets up a
×
UNCOV
4191
// peerTerminationWatcher for the given peer, and ensures that it executes even
×
4192
// if the peer failed to start. In the event of a successful connection, this
4193
// method reads the negotiated, local feature-bits and spawns the appropriate
4194
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4195
// be signaled of the new peer once the method returns.
UNCOV
4196
//
×
UNCOV
4197
// NOTE: This MUST be launched as a goroutine.
×
UNCOV
4198
func (s *server) peerInitializer(p *peer.Brontide) {
×
UNCOV
4199
        defer s.wg.Done()
×
4200

4201
        // Avoid initializing peers while the server is exiting.
UNCOV
4202
        if s.Stopped() {
×
4203
                return
×
4204
        }
×
UNCOV
4205

×
4206
        // Create a channel that will be used to signal a successful start of
4207
        // the link. This prevents the peer termination watcher from beginning
4208
        // its duty too early.
4209
        ready := make(chan struct{})
4210

4211
        // Before starting the peer, launch a goroutine to watch for the
UNCOV
4212
        // unexpected termination of this peer, which will ensure all resources
×
UNCOV
4213
        // are properly cleaned up, and re-establish persistent connections when
×
UNCOV
4214
        // necessary. The peer termination watcher will be short circuited if
×
UNCOV
4215
        // the peer is ever added to the ignorePeerTermination map, indicating
×
UNCOV
4216
        // that the server has already handled the removal of this peer.
×
UNCOV
4217
        s.wg.Add(1)
×
UNCOV
4218
        go s.peerTerminationWatcher(p, ready)
×
UNCOV
4219

×
UNCOV
4220
        pubBytes := p.IdentityKey().SerializeCompressed()
×
UNCOV
4221

×
4222
        // Start the peer! If an error occurs, we Disconnect the peer, which
4223
        // will unblock the peerTerminationWatcher.
4224
        if err := p.Start(); err != nil {
UNCOV
4225
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4226

×
UNCOV
4227
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4228
                return
×
4229
        }
4230

4231
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4232
        // was successful, and to begin watching the peer's wait group.
4233
        close(ready)
4234

4235
        s.mu.Lock()
4236
        defer s.mu.Unlock()
4237

4238
        // Check if there are listeners waiting for this peer to come online.
4239
        srvrLog.Debugf("Notifying that peer %v is online", p)
UNCOV
4240

×
UNCOV
4241
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
×
UNCOV
4242
        // route.Vertex as the key type of peerConnectedListeners.
×
UNCOV
4243
        pubStr := string(pubBytes)
×
UNCOV
4244
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
×
UNCOV
4245
                select {
×
UNCOV
4246
                case peerChan <- p:
×
4247
                case <-s.quit:
4248
                        return
4249
                }
4250
        }
UNCOV
4251
        delete(s.peerConnectedListeners, pubStr)
×
UNCOV
4252
}
×
UNCOV
4253

×
UNCOV
4254
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
×
UNCOV
4255
// and then cleans up all resources allocated to the peer, notifies relevant
×
UNCOV
4256
// sub-systems of its demise, and finally handles re-connecting to the peer if
×
UNCOV
4257
// it's persistent. If the server intentionally disconnects a peer, it should
×
UNCOV
4258
// have a corresponding entry in the ignorePeerTermination map which will cause
×
UNCOV
4259
// the cleanup routine to exit early. The passed `ready` chan is used to
×
UNCOV
4260
// synchronize when WaitForDisconnect should begin watching on the peer's
×
UNCOV
4261
// waitgroup. The ready chan should only be signaled if the peer starts
×
UNCOV
4262
// successfully, otherwise the peer should be disconnected instead.
×
UNCOV
4263
//
×
UNCOV
4264
// NOTE: This MUST be launched as a goroutine.
×
UNCOV
4265
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
×
UNCOV
4266
        defer s.wg.Done()
×
UNCOV
4267

×
UNCOV
4268
        p.WaitForDisconnect(ready)
×
UNCOV
4269

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

×
4272
        // If the server is exiting then we can bail out early ourselves as all
4273
        // the other sub-systems will already be shutting down.
4274
        if s.Stopped() {
UNCOV
4275
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
×
UNCOV
4276
                return
×
UNCOV
4277
        }
×
UNCOV
4278

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

×
UNCOV
4285
        pubKey := p.IdentityKey()
×
UNCOV
4286

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

×
4291
        // Tell the switch to remove all links associated with this peer.
4292
        // Passing nil as the target link indicates that all links associated
UNCOV
4293
        // with this interface should be closed.
×
4294
        //
4295
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
4296
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
4297
        if err != nil && err != htlcswitch.ErrNoLinksFound {
4298
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
4299
        }
4300

4301
        for _, link := range links {
4302
                s.htlcSwitch.RemoveLink(link.ChanID())
4303
        }
4304

4305
        s.mu.Lock()
4306
        defer s.mu.Unlock()
UNCOV
4307

×
UNCOV
4308
        // If there were any notification requests for when this peer
×
UNCOV
4309
        // disconnected, we can trigger them now.
×
UNCOV
4310
        srvrLog.Debugf("Notifying that peer %v is offline", p)
×
UNCOV
4311
        pubStr := string(pubKey.SerializeCompressed())
×
UNCOV
4312
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
×
UNCOV
4313
                close(offlineChan)
×
UNCOV
4314
        }
×
UNCOV
4315
        delete(s.peerDisconnectedListeners, pubStr)
×
UNCOV
4316

×
UNCOV
4317
        // If the server has already removed this peer, we can short circuit the
×
UNCOV
4318
        // peer termination watcher and skip cleanup.
×
UNCOV
4319
        if _, ok := s.ignorePeerTermination[p]; ok {
×
4320
                delete(s.ignorePeerTermination, p)
4321

4322
                pubKey := p.PubKey()
4323
                pubStr := string(pubKey[:])
4324

4325
                // If a connection callback is present, we'll go ahead and
×
4326
                // execute it now that previous peer has fully disconnected. If
×
4327
                // the callback is not present, this likely implies the peer was
×
4328
                // purposefully disconnected via RPC, and that no reconnect
×
4329
                // should be attempted.
×
4330
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4331
                if ok {
×
4332
                        delete(s.scheduledPeerConnection, pubStr)
×
4333
                        connCallback()
×
4334
                }
×
4335
                return
×
UNCOV
4336
        }
×
UNCOV
4337

×
UNCOV
4338
        // First, cleanup any remaining state the server has regarding the peer
×
UNCOV
4339
        // in question.
×
UNCOV
4340
        s.removePeer(p)
×
UNCOV
4341

×
4342
        // Next, check to see if this is a persistent peer or not.
UNCOV
4343
        if _, ok := s.persistentPeers[pubStr]; !ok {
×
UNCOV
4344
                return
×
UNCOV
4345
        }
×
4346

UNCOV
4347
        // Get the last address that we used to connect to the peer.
×
UNCOV
4348
        addrs := []net.Addr{
×
UNCOV
4349
                p.NetAddress().Address,
×
UNCOV
4350
        }
×
UNCOV
4351

×
UNCOV
4352
        // We'll ensure that we locate all the peers advertised addresses for
×
UNCOV
4353
        // reconnection purposes.
×
UNCOV
4354
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
×
UNCOV
4355
        switch {
×
UNCOV
4356
        // We found advertised addresses, so use them.
×
UNCOV
4357
        case err == nil:
×
UNCOV
4358
                addrs = advertisedAddrs
×
UNCOV
4359

×
UNCOV
4360
        // The peer doesn't have an advertised address.
×
UNCOV
4361
        case err == errNoAdvertisedAddr:
×
UNCOV
4362
                // If it is an outbound peer then we fall back to the existing
×
UNCOV
4363
                // peer address.
×
UNCOV
4364
                if !p.Inbound() {
×
UNCOV
4365
                        break
×
UNCOV
4366
                }
×
UNCOV
4367

×
UNCOV
4368
                // Fall back to the existing peer address if
×
UNCOV
4369
                // we're not accepting connections over Tor.
×
UNCOV
4370
                if s.torController == nil {
×
UNCOV
4371
                        break
×
UNCOV
4372
                }
×
UNCOV
4373

×
UNCOV
4374
                // If we are, the peer's address won't be known
×
UNCOV
4375
                // to us (we'll see a private address, which is
×
UNCOV
4376
                // the address used by our onion service to dial
×
UNCOV
4377
                // to lnd), so we don't have enough information
×
4378
                // to attempt a reconnect.
4379
                srvrLog.Debugf("Ignoring reconnection attempt "+
4380
                        "to inbound peer %v without "+
4381
                        "advertised address", p)
4382
                return
×
UNCOV
4383

×
UNCOV
4384
        // We came across an error retrieving an advertised
×
UNCOV
4385
        // address, log it, and fall back to the existing peer
×
UNCOV
4386
        // address.
×
UNCOV
4387
        default:
×
4388
                srvrLog.Errorf("Unable to retrieve advertised "+
4389
                        "address for node %x: %v", p.PubKey(),
UNCOV
4390
                        err)
×
UNCOV
4391
        }
×
UNCOV
4392

×
UNCOV
4393
        // Make an easy lookup map so that we can check if an address
×
UNCOV
4394
        // is already in the address list that we have stored for this peer.
×
UNCOV
4395
        existingAddrs := make(map[string]bool)
×
UNCOV
4396
        for _, addr := range s.persistentPeerAddrs[pubStr] {
×
UNCOV
4397
                existingAddrs[addr.String()] = true
×
4398
        }
UNCOV
4399

×
UNCOV
4400
        // Add any missing addresses for this peer to persistentPeerAddr.
×
4401
        for _, addr := range addrs {
4402
                if existingAddrs[addr.String()] {
4403
                        continue
×
UNCOV
4404
                }
×
UNCOV
4405

×
UNCOV
4406
                s.persistentPeerAddrs[pubStr] = append(
×
UNCOV
4407
                        s.persistentPeerAddrs[pubStr],
×
4408
                        &lnwire.NetAddress{
4409
                                IdentityKey: p.IdentityKey(),
4410
                                Address:     addr,
4411
                                ChainNet:    p.NetAddress().ChainNet,
UNCOV
4412
                        },
×
UNCOV
4413
                )
×
4414
        }
4415

4416
        // Record the computed backoff in the backoff map.
4417
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4418
        s.persistentPeersBackoff[pubStr] = backoff
4419

4420
        // Initialize a retry canceller for this peer if one does not
UNCOV
4421
        // exist.
×
UNCOV
4422
        cancelChan, ok := s.persistentRetryCancels[pubStr]
×
UNCOV
4423
        if !ok {
×
UNCOV
4424
                cancelChan = make(chan struct{})
×
4425
                s.persistentRetryCancels[pubStr] = cancelChan
4426
        }
4427

4428
        // We choose not to wait group this go routine since the Connect
UNCOV
4429
        // call can stall for arbitrarily long if we shutdown while an
×
UNCOV
4430
        // outbound connection attempt is being made.
×
UNCOV
4431
        go func() {
×
UNCOV
4432
                srvrLog.Debugf("Scheduling connection re-establishment to "+
×
4433
                        "persistent peer %x in %s",
4434
                        p.IdentityKey().SerializeCompressed(), backoff)
4435

4436
                select {
UNCOV
4437
                case <-time.After(backoff):
×
UNCOV
4438
                case <-cancelChan:
×
UNCOV
4439
                        return
×
UNCOV
4440
                case <-s.quit:
×
4441
                        return
4442
                }
UNCOV
4443

×
UNCOV
4444
                srvrLog.Debugf("Attempting to re-establish persistent "+
×
UNCOV
4445
                        "connection to peer %x",
×
4446
                        p.IdentityKey().SerializeCompressed())
4447

UNCOV
4448
                s.connectToPersistentPeer(pubStr)
×
UNCOV
4449
        }()
×
UNCOV
4450
}
×
UNCOV
4451

×
UNCOV
4452
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
×
UNCOV
4453
// to connect to the peer. It creates connection requests if there are
×
UNCOV
4454
// currently none for a given address and it removes old connection requests
×
UNCOV
4455
// if the associated address is no longer in the latest address list for the
×
4456
// peer.
4457
func (s *server) connectToPersistentPeer(pubKeyStr string) {
4458
        s.mu.Lock()
UNCOV
4459
        defer s.mu.Unlock()
×
UNCOV
4460

×
UNCOV
4461
        // Create an easy lookup map of the addresses we have stored for the
×
UNCOV
4462
        // peer. We will remove entries from this map if we have existing
×
UNCOV
4463
        // connection requests for the associated address and then any leftover
×
UNCOV
4464
        // entries will indicate which addresses we should create new
×
UNCOV
4465
        // connection requests for.
×
UNCOV
4466
        addrMap := make(map[string]*lnwire.NetAddress)
×
UNCOV
4467
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
×
UNCOV
4468
                addrMap[addr.String()] = addr
×
4469
        }
4470

4471
        // Go through each of the existing connection requests and
4472
        // check if they correspond to the latest set of addresses. If
UNCOV
4473
        // there is a connection requests that does not use one of the latest
×
UNCOV
4474
        // advertised addresses then remove that connection request.
×
UNCOV
4475
        var updatedConnReqs []*connmgr.ConnReq
×
UNCOV
4476
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
×
UNCOV
4477
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
×
UNCOV
4478

×
UNCOV
4479
                switch _, ok := addrMap[lnAddr]; ok {
×
UNCOV
4480
                // If the existing connection request is using one of the
×
UNCOV
4481
                // latest advertised addresses for the peer then we add it to
×
UNCOV
4482
                // updatedConnReqs and remove the associated address from
×
UNCOV
4483
                // addrMap so that we don't recreate this connReq later on.
×
4484
                case true:
4485
                        updatedConnReqs = append(
4486
                                updatedConnReqs, connReq,
×
4487
                        )
×
4488
                        delete(addrMap, lnAddr)
×
UNCOV
4489

×
UNCOV
4490
                // If the existing connection request is using an address that
×
4491
                // is not one of the latest advertised addresses for the peer
4492
                // then we remove the connecting request from the connection
4493
                // manager.
4494
                case false:
4495
                        srvrLog.Info(
4496
                                "Removing conn req:", connReq.Addr.String(),
4497
                        )
4498
                        s.connMgr.Remove(connReq.ID())
UNCOV
4499
                }
×
UNCOV
4500
        }
×
UNCOV
4501

×
UNCOV
4502
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
×
UNCOV
4503

×
UNCOV
4504
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
×
UNCOV
4505
        if !ok {
×
UNCOV
4506
                cancelChan = make(chan struct{})
×
UNCOV
4507
                s.persistentRetryCancels[pubKeyStr] = cancelChan
×
UNCOV
4508
        }
×
UNCOV
4509

×
UNCOV
4510
        // Any addresses left in addrMap are new ones that we have not made
×
UNCOV
4511
        // connection requests for. So create new connection requests for those.
×
4512
        // If there is more than one address in the address map, stagger the
4513
        // creation of the connection requests for those.
4514
        go func() {
4515
                ticker := time.NewTicker(multiAddrConnectionStagger)
4516
                defer ticker.Stop()
UNCOV
4517

×
UNCOV
4518
                for _, addr := range addrMap {
×
UNCOV
4519
                        // Send the persistent connection request to the
×
UNCOV
4520
                        // connection manager, saving the request itself so we
×
UNCOV
4521
                        // can cancel/restart the process as needed.
×
4522
                        connReq := &connmgr.ConnReq{
4523
                                Addr:      addr,
4524
                                Permanent: true,
4525
                        }
UNCOV
4526

×
UNCOV
4527
                        s.mu.Lock()
×
UNCOV
4528
                        s.persistentConnReqs[pubKeyStr] = append(
×
UNCOV
4529
                                s.persistentConnReqs[pubKeyStr], connReq,
×
UNCOV
4530
                        )
×
4531
                        s.mu.Unlock()
4532

4533
                        srvrLog.Debugf("Attempting persistent connection to "+
4534
                                "channel peer %v", addr)
4535

UNCOV
4536
                        go s.connMgr.Connect(connReq)
×
UNCOV
4537

×
UNCOV
4538
                        select {
×
UNCOV
4539
                        case <-s.quit:
×
UNCOV
4540
                                return
×
4541
                        case <-cancelChan:
4542
                                return
4543
                        case <-ticker.C:
UNCOV
4544
                        }
×
UNCOV
4545
                }
×
UNCOV
4546
        }()
×
UNCOV
4547
}
×
UNCOV
4548

×
UNCOV
4549
// removePeer removes the passed peer from the server's state of all active
×
UNCOV
4550
// peers.
×
4551
func (s *server) removePeer(p *peer.Brontide) {
4552
        if p == nil {
4553
                return
4554
        }
4555

UNCOV
4556
        srvrLog.Debugf("removing peer %v", p)
×
UNCOV
4557

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

×
UNCOV
4562
        // If this peer had an active persistent connection request, remove it.
×
UNCOV
4563
        if p.ConnReq() != nil {
×
UNCOV
4564
                s.connMgr.Remove(p.ConnReq().ID())
×
UNCOV
4565
        }
×
UNCOV
4566

×
UNCOV
4567
        // Ignore deleting peers if we're shutting down.
×
UNCOV
4568
        if s.Stopped() {
×
4569
                return
×
4570
        }
×
UNCOV
4571

×
UNCOV
4572
        pKey := p.PubKey()
×
UNCOV
4573
        pubSer := pKey[:]
×
UNCOV
4574
        pubStr := string(pubSer)
×
UNCOV
4575

×
UNCOV
4576
        delete(s.peersByPub, pubStr)
×
UNCOV
4577

×
UNCOV
4578
        if p.Inbound() {
×
UNCOV
4579
                delete(s.inboundPeers, pubStr)
×
UNCOV
4580
        } else {
×
UNCOV
4581
                delete(s.outboundPeers, pubStr)
×
UNCOV
4582
        }
×
UNCOV
4583

×
UNCOV
4584
        // Copy the peer's error buffer across to the server if it has any items
×
UNCOV
4585
        // in it so that we can restore peer errors across connections.
×
4586
        if p.ErrorBuffer().Total() > 0 {
4587
                s.peerErrors[pubStr] = p.ErrorBuffer()
4588
        }
4589

4590
        // Inform the peer notifier of a peer offline event so that it can be
4591
        // reported to clients listening for peer events.
4592
        var pubKey [33]byte
UNCOV
4593
        copy(pubKey[:], pubSer)
×
UNCOV
4594

×
UNCOV
4595
        s.peerNotifier.NotifyPeerOffline(pubKey)
×
UNCOV
4596
}
×
4597

UNCOV
4598
// ConnectToPeer requests that the server connect to a Lightning Network peer
×
UNCOV
4599
// at the specified address. This function will *block* until either a
×
UNCOV
4600
// connection is established, or the initial handshake process fails.
×
UNCOV
4601
//
×
UNCOV
4602
// NOTE: This function is safe for concurrent access.
×
UNCOV
4603
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
×
UNCOV
4604
        perm bool, timeout time.Duration) error {
×
UNCOV
4605

×
UNCOV
4606
        targetPub := string(addr.IdentityKey.SerializeCompressed())
×
UNCOV
4607

×
4608
        // Acquire mutex, but use explicit unlocking instead of defer for
4609
        // better granularity.  In certain conditions, this method requires
UNCOV
4610
        // making an outbound connection to a remote peer, which requires the
×
UNCOV
4611
        // lock to be released, and subsequently reacquired.
×
UNCOV
4612
        s.mu.Lock()
×
4613

UNCOV
4614
        // Ensure we're not already connected to this peer.
×
UNCOV
4615
        peer, err := s.findPeerByPubStr(targetPub)
×
UNCOV
4616
        if err == nil {
×
UNCOV
4617
                s.mu.Unlock()
×
UNCOV
4618
                return &errPeerAlreadyConnected{peer: peer}
×
UNCOV
4619
        }
×
UNCOV
4620

×
UNCOV
4621
        // Peer was not found, continue to pursue connection with peer.
×
UNCOV
4622

×
UNCOV
4623
        // If there's already a pending connection request for this pubkey,
×
UNCOV
4624
        // then we ignore this request to ensure we don't create a redundant
×
4625
        // connection.
4626
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
4627
                srvrLog.Warnf("Already have %d persistent connection "+
UNCOV
4628
                        "requests for %v, connecting anyway.", len(reqs), addr)
×
UNCOV
4629
        }
×
UNCOV
4630

×
4631
        // If there's not already a pending or active connection to this node,
4632
        // then instruct the connection manager to attempt to establish a
4633
        // persistent connection to the peer.
UNCOV
4634
        srvrLog.Debugf("Connecting to %v", addr)
×
UNCOV
4635
        if perm {
×
UNCOV
4636
                connReq := &connmgr.ConnReq{
×
UNCOV
4637
                        Addr:      addr,
×
4638
                        Permanent: true,
4639
                }
4640

4641
                // Since the user requested a permanent connection, we'll set
4642
                // the entry to true which will tell the server to continue
4643
                // reconnecting even if the number of channels with this peer is
4644
                // zero.
4645
                s.persistentPeers[targetPub] = true
UNCOV
4646
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
×
UNCOV
4647
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
×
UNCOV
4648
                }
×
UNCOV
4649
                s.persistentConnReqs[targetPub] = append(
×
UNCOV
4650
                        s.persistentConnReqs[targetPub], connReq,
×
UNCOV
4651
                )
×
UNCOV
4652
                s.mu.Unlock()
×
UNCOV
4653

×
UNCOV
4654
                go s.connMgr.Connect(connReq)
×
UNCOV
4655

×
UNCOV
4656
                return nil
×
UNCOV
4657
        }
×
UNCOV
4658
        s.mu.Unlock()
×
UNCOV
4659

×
UNCOV
4660
        // If we're not making a persistent connection, then we'll attempt to
×
UNCOV
4661
        // connect to the target peer. If the we can't make the connection, or
×
4662
        // the crypto negotiation breaks down, then return an error to the
4663
        // caller.
4664
        errChan := make(chan error, 1)
4665
        s.connectToPeer(addr, errChan, timeout)
4666

4667
        select {
UNCOV
4668
        case err := <-errChan:
×
UNCOV
4669
                return err
×
4670
        case <-s.quit:
×
4671
                return ErrServerShuttingDown
×
4672
        }
4673
}
4674

4675
// connectToPeer establishes a connection to a remote peer. errChan is used to
UNCOV
4676
// notify the caller if the connection attempt has failed. Otherwise, it will be
×
UNCOV
4677
// closed.
×
UNCOV
4678
func (s *server) connectToPeer(addr *lnwire.NetAddress,
×
UNCOV
4679
        errChan chan<- error, timeout time.Duration) {
×
UNCOV
4680

×
UNCOV
4681
        conn, err := brontide.Dial(
×
UNCOV
4682
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
×
UNCOV
4683
        )
×
UNCOV
4684
        if err != nil {
×
UNCOV
4685
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
×
UNCOV
4686
                select {
×
UNCOV
4687
                case errChan <- err:
×
4688
                case <-s.quit:
×
UNCOV
4689
                }
×
UNCOV
4690
                return
×
UNCOV
4691
        }
×
UNCOV
4692

×
UNCOV
4693
        close(errChan)
×
UNCOV
4694

×
UNCOV
4695
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
×
UNCOV
4696
                conn.LocalAddr(), conn.RemoteAddr())
×
UNCOV
4697

×
UNCOV
4698
        s.OutboundPeerConnected(nil, conn)
×
4699
}
UNCOV
4700

×
UNCOV
4701
// DisconnectPeer sends the request to server to close the connection with peer
×
UNCOV
4702
// identified by public key.
×
UNCOV
4703
//
×
UNCOV
4704
// NOTE: This function is safe for concurrent access.
×
UNCOV
4705
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
×
UNCOV
4706
        pubBytes := pubKey.SerializeCompressed()
×
UNCOV
4707
        pubStr := string(pubBytes)
×
UNCOV
4708

×
UNCOV
4709
        s.mu.Lock()
×
UNCOV
4710
        defer s.mu.Unlock()
×
UNCOV
4711

×
UNCOV
4712
        // Check that were actually connected to this peer. If not, then we'll
×
UNCOV
4713
        // exit in an error as we can't disconnect from a peer that we're not
×
4714
        // currently connected to.
4715
        peer, err := s.findPeerByPubStr(pubStr)
4716
        if err == ErrPeerNotConnected {
4717
                return fmt.Errorf("peer %x is not connected", pubBytes)
4718
        }
4719

4720
        srvrLog.Infof("Disconnecting from %v", peer)
UNCOV
4721

×
UNCOV
4722
        s.cancelConnReqs(pubStr, nil)
×
UNCOV
4723

×
UNCOV
4724
        // If this peer was formerly a persistent connection, then we'll remove
×
UNCOV
4725
        // them from this map so we don't attempt to re-connect after we
×
UNCOV
4726
        // disconnect.
×
UNCOV
4727
        delete(s.persistentPeers, pubStr)
×
UNCOV
4728
        delete(s.persistentPeersBackoff, pubStr)
×
UNCOV
4729

×
UNCOV
4730
        // Remove the peer by calling Disconnect. Previously this was done with
×
4731
        // removePeer, which bypassed the peerTerminationWatcher.
UNCOV
4732
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
×
4733

4734
        return nil
UNCOV
4735
}
×
UNCOV
4736

×
UNCOV
4737
// OpenChannel sends a request to the server to open a channel to the specified
×
UNCOV
4738
// peer identified by nodeKey with the passed channel funding parameters.
×
UNCOV
4739
//
×
UNCOV
4740
// NOTE: This function is safe for concurrent access.
×
4741
func (s *server) OpenChannel(
4742
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
4743

4744
        // The updateChan will have a buffer of 2, since we expect a ChanPending
4745
        // + a ChanOpen update, and we want to make sure the funding process is
4746
        // not blocked if the caller is not reading the updates.
UNCOV
4747
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
×
UNCOV
4748
        req.Err = make(chan error, 1)
×
UNCOV
4749

×
UNCOV
4750
        // First attempt to locate the target peer to open a channel with, if
×
UNCOV
4751
        // we're unable to locate the peer then this request will fail.
×
UNCOV
4752
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
×
UNCOV
4753
        s.mu.RLock()
×
UNCOV
4754
        peer, ok := s.peersByPub[string(pubKeyBytes)]
×
UNCOV
4755
        if !ok {
×
4756
                s.mu.RUnlock()
×
4757

×
4758
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4759
                return req.Updates, req.Err
×
4760
        }
×
4761
        req.Peer = peer
UNCOV
4762
        s.mu.RUnlock()
×
UNCOV
4763

×
UNCOV
4764
        // We'll wait until the peer is active before beginning the channel
×
UNCOV
4765
        // opening process.
×
UNCOV
4766
        select {
×
UNCOV
4767
        case <-peer.ActiveSignal():
×
4768
        case <-peer.QuitSignal():
×
4769
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
4770
                return req.Updates, req.Err
×
4771
        case <-s.quit:
×
4772
                req.Err <- ErrServerShuttingDown
×
4773
                return req.Updates, req.Err
×
UNCOV
4774
        }
×
UNCOV
4775

×
UNCOV
4776
        // If the fee rate wasn't specified at this point we fail the funding
×
4777
        // because of the missing fee rate information. The caller of the
4778
        // `OpenChannel` method needs to make sure that default values for the
4779
        // fee rate are set beforehand.
4780
        if req.FundingFeePerKw == 0 {
4781
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
4782
                        "the channel opening transaction")
4783

4784
                return req.Updates, req.Err
×
4785
        }
×
UNCOV
4786

×
UNCOV
4787
        // Spawn a goroutine to send the funding workflow request to the funding
×
UNCOV
4788
        // manager. This allows the server to continue handling queries instead
×
UNCOV
4789
        // of blocking on this request which is exported as a synchronous
×
UNCOV
4790
        // request to the outside world.
×
UNCOV
4791
        go s.fundingMgr.InitFundingWorkflow(req)
×
UNCOV
4792

×
UNCOV
4793
        return req.Updates, req.Err
×
UNCOV
4794
}
×
UNCOV
4795

×
UNCOV
4796
// Peers returns a slice of all active peers.
×
UNCOV
4797
//
×
UNCOV
4798
// NOTE: This function is safe for concurrent access.
×
UNCOV
4799
func (s *server) Peers() []*peer.Brontide {
×
UNCOV
4800
        s.mu.RLock()
×
UNCOV
4801
        defer s.mu.RUnlock()
×
UNCOV
4802

×
UNCOV
4803
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
×
UNCOV
4804
        for _, peer := range s.peersByPub {
×
UNCOV
4805
                peers = append(peers, peer)
×
UNCOV
4806
        }
×
UNCOV
4807

×
UNCOV
4808
        return peers
×
UNCOV
4809
}
×
UNCOV
4810

×
UNCOV
4811
// computeNextBackoff uses a truncated exponential backoff to compute the next
×
UNCOV
4812
// backoff using the value of the exiting backoff. The returned duration is
×
UNCOV
4813
// randomized in either direction by 1/20 to prevent tight loops from
×
UNCOV
4814
// stabilizing.
×
UNCOV
4815
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
×
4816
        // Double the current backoff, truncating if it exceeds our maximum.
4817
        nextBackoff := 2 * currBackoff
4818
        if nextBackoff > maxBackoff {
4819
                nextBackoff = maxBackoff
4820
        }
4821

UNCOV
4822
        // Using 1/10 of our duration as a margin, compute a random offset to
×
UNCOV
4823
        // avoid the nodes entering connection cycles.
×
UNCOV
4824
        margin := nextBackoff / 10
×
UNCOV
4825

×
UNCOV
4826
        var wiggle big.Int
×
UNCOV
4827
        wiggle.SetUint64(uint64(margin))
×
4828
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
4829
                // Randomizing is not mission critical, so we'll just return the
4830
                // current backoff.
4831
                return nextBackoff
4832
        }
UNCOV
4833

×
UNCOV
4834
        // Otherwise add in our wiggle, but subtract out half of the margin so
×
UNCOV
4835
        // that the backoff can tweaked by 1/20 in either direction.
×
4836
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
4837
}
4838

4839
// errNoAdvertisedAddr is an error returned when we attempt to retrieve the
4840
// advertised address of a node, but they don't have one.
UNCOV
4841
var errNoAdvertisedAddr = errors.New("no advertised address found")
×
UNCOV
4842

×
UNCOV
4843
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
×
UNCOV
4844
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
×
UNCOV
4845
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
×
UNCOV
4846
        if err != nil {
×
4847
                return nil, err
×
4848
        }
×
4849

UNCOV
4850
        node, err := s.graphDB.FetchLightningNode(vertex)
×
4851
        if err != nil {
4852
                return nil, err
4853
        }
4854

4855
        if len(node.Addresses) == 0 {
4856
                return nil, errNoAdvertisedAddr
UNCOV
4857
        }
×
UNCOV
4858

×
UNCOV
4859
        return node.Addresses, nil
×
UNCOV
4860
}
×
UNCOV
4861

×
UNCOV
4862
// fetchLastChanUpdate returns a function which is able to retrieve our latest
×
4863
// channel update for a target channel.
4864
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
4865
        *lnwire.ChannelUpdate1, error) {
UNCOV
4866

×
UNCOV
4867
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
×
UNCOV
4868
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
×
UNCOV
4869
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
×
UNCOV
4870
                if err != nil {
×
UNCOV
4871
                        return nil, err
×
UNCOV
4872
                }
×
UNCOV
4873

×
UNCOV
4874
                return netann.ExtractChannelUpdate(
×
4875
                        ourPubKey[:], info, edge1, edge2,
4876
                )
4877
        }
UNCOV
4878
}
×
4879

4880
// applyChannelUpdate applies the channel update to the different sub-systems of
4881
// the server. The useAlias boolean denotes whether or not to send an alias in
4882
// place of the real SCID.
4883
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
4884
        op *wire.OutPoint, useAlias bool) error {
4885

UNCOV
4886
        var (
×
UNCOV
4887
                peerAlias    *lnwire.ShortChannelID
×
UNCOV
4888
                defaultAlias lnwire.ShortChannelID
×
UNCOV
4889
        )
×
UNCOV
4890

×
4891
        chanID := lnwire.NewChanIDFromOutPoint(*op)
UNCOV
4892

×
UNCOV
4893
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
×
UNCOV
4894
        // in the ChannelUpdate if it hasn't been announced yet.
×
UNCOV
4895
        if useAlias {
×
4896
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
UNCOV
4897
                if foundAlias != defaultAlias {
×
UNCOV
4898
                        peerAlias = &foundAlias
×
UNCOV
4899
                }
×
4900
        }
UNCOV
4901

×
4902
        errChan := s.authGossiper.ProcessLocalAnnouncement(
4903
                update, discovery.RemoteAlias(peerAlias),
4904
        )
4905
        select {
4906
        case err := <-errChan:
UNCOV
4907
                return err
×
4908
        case <-s.quit:
×
4909
                return ErrServerShuttingDown
×
UNCOV
4910
        }
×
UNCOV
4911
}
×
UNCOV
4912

×
UNCOV
4913
// SendCustomMessage sends a custom message to the peer with the specified
×
UNCOV
4914
// pubkey.
×
4915
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
UNCOV
4916
        data []byte) error {
×
UNCOV
4917

×
UNCOV
4918
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
×
4919
        if err != nil {
4920
                return err
4921
        }
4922

4923
        // We'll wait until the peer is active.
4924
        select {
4925
        case <-peer.ActiveSignal():
4926
        case <-peer.QuitSignal():
×
4927
                return fmt.Errorf("peer %x disconnected", peerPub)
×
4928
        case <-s.quit:
×
4929
                return ErrServerShuttingDown
×
UNCOV
4930
        }
×
UNCOV
4931

×
UNCOV
4932
        msg, err := lnwire.NewCustom(msgType, data)
×
UNCOV
4933
        if err != nil {
×
UNCOV
4934
                return err
×
UNCOV
4935
        }
×
UNCOV
4936

×
UNCOV
4937
        // Send the message as low-priority. For now we assume that all
×
UNCOV
4938
        // application-defined message are low priority.
×
UNCOV
4939
        return peer.SendMessageLazy(true, msg)
×
UNCOV
4940
}
×
UNCOV
4941

×
4942
// newSweepPkScriptGen creates closure that generates a new public key script
4943
// which should be used to sweep any funds into the on-chain wallet.
UNCOV
4944
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
×
UNCOV
4945
// (p2wkh) output.
×
UNCOV
4946
func newSweepPkScriptGen(
×
UNCOV
4947
        wallet lnwallet.WalletController) func() ([]byte, error) {
×
UNCOV
4948

×
UNCOV
4949
        return func() ([]byte, error) {
×
UNCOV
4950
                sweepAddr, err := wallet.NewAddress(
×
UNCOV
4951
                        lnwallet.TaprootPubkey, false,
×
4952
                        lnwallet.DefaultAccountName,
4953
                )
4954
                if err != nil {
4955
                        return nil, err
4956
                }
4957

UNCOV
4958
                return txscript.PayToAddrScript(sweepAddr)
×
UNCOV
4959
        }
×
UNCOV
4960
}
×
UNCOV
4961

×
UNCOV
4962
// shouldPeerBootstrap returns true if we should attempt to perform peer
×
UNCOV
4963
// bootstrapping to actively seek our peers using the set of active network
×
4964
// bootstrappers.
4965
func shouldPeerBootstrap(cfg *Config) bool {
UNCOV
4966
        isSimnet := cfg.Bitcoin.SimNet
×
UNCOV
4967
        isSignet := cfg.Bitcoin.SigNet
×
UNCOV
4968
        isRegtest := cfg.Bitcoin.RegTest
×
UNCOV
4969
        isDevNetwork := isSimnet || isSignet || isRegtest
×
UNCOV
4970

×
UNCOV
4971
        // TODO(yy): remove the check on simnet/regtest such that the itest is
×
4972
        // covering the bootstrapping process.
4973
        return !cfg.NoNetBootstrap && !isDevNetwork
UNCOV
4974
}
×
UNCOV
4975

×
UNCOV
4976
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
×
UNCOV
4977
// finished.
×
4978
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
4979
        // Get a list of closed channels.
4980
        channels, err := s.chanStateDB.FetchClosedChannels(false)
UNCOV
4981
        if err != nil {
×
4982
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
4983
                return nil
4984
        }
4985

4986
        // Save the SCIDs in a map.
4987
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
4988
        for _, c := range channels {
4989
                // If the channel is not pending, its FC has been finalized.
UNCOV
4990
                if !c.IsPending {
×
UNCOV
4991
                        closedSCIDs[c.ShortChanID] = struct{}{}
×
UNCOV
4992
                }
×
UNCOV
4993
        }
×
UNCOV
4994

×
UNCOV
4995
        // Double check whether the reported closed channel has indeed finished
×
UNCOV
4996
        // closing.
×
UNCOV
4997
        //
×
UNCOV
4998
        // NOTE: There are misalignments regarding when a channel's FC is
×
UNCOV
4999
        // marked as finalized. We double check the pending channels to make
×
5000
        // sure the returned SCIDs are indeed terminated.
UNCOV
5001
        //
×
UNCOV
5002
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
×
UNCOV
5003
        pendings, err := s.chanStateDB.FetchPendingChannels()
×
UNCOV
5004
        if err != nil {
×
5005
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
5006
                return nil
×
5007
        }
×
UNCOV
5008

×
UNCOV
5009
        for _, c := range pendings {
×
UNCOV
5010
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
×
UNCOV
5011
                        continue
×
5012
                }
UNCOV
5013

×
UNCOV
5014
                // If the channel is still reported as pending, remove it from
×
UNCOV
5015
                // the map.
×
5016
                delete(closedSCIDs, c.ShortChannelID)
×
5017

5018
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
5019
                        c.ShortChannelID)
5020
        }
5021

5022
        return closedSCIDs
5023
}
6✔
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