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

lightningnetwork / lnd / 12430728843

20 Dec 2024 11:36AM UTC coverage: 61.336% (+2.6%) from 58.716%
12430728843

Pull #8777

github

ziggie1984
channeldb: fix typo.
Pull Request #8777: multi: make reassignment of alias channel edge atomic

161 of 213 new or added lines in 7 files covered. (75.59%)

70 existing lines in 17 files now uncovered.

23369 of 38100 relevant lines covered (61.34%)

115813.77 hits per line

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

64.18
/server.go
1
package lnd
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

166
        start sync.Once
167
        stop  sync.Once
168

169
        cfg *Config
170

171
        implCfg *ImplementationCfg
172

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

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

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

184
        chanStatusMgr *netann.ChanStatusManager
185

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

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

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

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

206
        mu sync.RWMutex
207

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

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

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

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

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

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

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

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

258
        cc *chainreg.ChainControl
259

260
        fundingMgr *funding.Manager
261

262
        graphDB *graphdb.ChannelGraph
263

264
        chanStateDB *channeldb.ChannelStateDB
265

266
        addrSource channeldb.AddrSource
267

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

272
        invoicesDB invoices.InvoiceDB
273

274
        aliasMgr *aliasmgr.Manager
275

276
        htlcSwitch *htlcswitch.Switch
277

278
        interceptableSwitch *htlcswitch.InterceptableSwitch
279

280
        invoices *invoices.InvoiceRegistry
281

282
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
283

284
        channelNotifier *channelnotifier.ChannelNotifier
285

286
        peerNotifier *peernotifier.PeerNotifier
287

288
        htlcNotifier *htlcswitch.HtlcNotifier
289

290
        witnessBeacon contractcourt.WitnessBeacon
291

292
        breachArbitrator *contractcourt.BreachArbitrator
293

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

297
        graphBuilder *graph.Builder
298

299
        chanRouter *routing.ChannelRouter
300

301
        controlTower routing.ControlTower
302

303
        authGossiper *discovery.AuthenticatedGossiper
304

305
        localChanMgr *localchans.Manager
306

307
        utxoNursery *contractcourt.UtxoNursery
308

309
        sweeper *sweep.UtxoSweeper
310

311
        chainArb *contractcourt.ChainArbitrator
312

313
        sphinx *hop.OnionProcessor
314

315
        towerClientMgr *wtclient.Manager
316

317
        connMgr *connmgr.ConnManager
318

319
        sigPool *lnwallet.SigPool
320

321
        writePool *pool.Write
322

323
        readPool *pool.Read
324

325
        tlsManager *TLSManager
326

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

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

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

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

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

349
        hostAnn *netann.HostAnnouncer
350

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

354
        customMessageServer *subscribe.Server
355

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

359
        quit chan struct{}
360

361
        wg sync.WaitGroup
362
}
363

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

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

8✔
379
                for {
8✔
380
                        select {
4✔
381
                        case <-s.quit:
4✔
382
                                return
4✔
383

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

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

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

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

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

4✔
419
                                        s.mu.Lock()
4✔
420

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

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

4✔
435
                                        s.mu.Unlock()
8✔
436

4✔
437
                                        s.connectToPersistentPeer(pubKeyStr)
4✔
438
                                }
439
                        }
440
                }
4✔
441
        }()
4✔
442

4✔
443
        return nil
444
}
445

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

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

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

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

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

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

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

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

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

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

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

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

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

×
540
        netParams := cfg.ActiveNetParams.Params
541

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

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

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

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

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

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

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

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

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

4✔
610
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
4✔
611

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

4✔
626
                channelNotifier: channelnotifier.New(
4✔
627
                        dbs.ChanStateDB.ChannelStateDB(),
4✔
628
                ),
4✔
629

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

4✔
634
                listenAddrs: listenAddrs,
4✔
635

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

4✔
640
                torController: torController,
4✔
641

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

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

4✔
658
                invoiceHtlcModifier: invoiceHtlcModifier,
4✔
659

4✔
660
                customMessageServer: subscribe.NewServer(),
4✔
661

4✔
662
                tlsManager: tlsManager,
4✔
663

4✔
664
                featureMgr: featureMgr,
4✔
665
                quit:       make(chan struct{}),
4✔
666
        }
4✔
667

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

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

4✔
681
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
4✔
682

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

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

692
                s.htlcSwitch.UpdateLinkAliases(link)
4✔
693

4✔
694
                return nil
4✔
695
        }
4✔
696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
1031
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
4✔
1032

4✔
1033
        s.controlTower = routing.NewControlTower(paymentControl)
4✔
1034

4✔
1035
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
4✔
1036
                cfg.Routing.StrictZombiePruning
4✔
1037

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

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

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

4✔
1085
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
4✔
1086

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1456
                return ourPolicy, err
4✔
1457
        }
4✔
1458

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

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

4✔
1473
                reservationTimeout = cfg.Dev.GetReservationTimeout()
4✔
1474
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
4✔
1475

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
1711
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
4✔
1712

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

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

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

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

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

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

4✔
1751
                        return br, channel.ChanType, nil
4✔
1752
                }
8✔
1753

4✔
1754
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
4✔
1755

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

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

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

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

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

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

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

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

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

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

4✔
1852
        return s, nil
4✔
1853
}
4✔
1854

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

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

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

4✔
1871
        case routing.BimodalConfig:
4✔
1872
                routerCfg.ProbabilityEstimatorType =
4✔
1873
                        routing.BimodalEstimatorName
4✔
1874

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

4✔
1881
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
4✔
1882
}
4✔
1883

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

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

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

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

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

4✔
1916
                chainBackendAttempts = 0
4✔
1917
        }
4✔
1918

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
2066
                checks = append(checks, leaderCheck)
2067
        }
2068

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2517
                close(s.quit)
2518

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

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

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

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

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

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

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

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

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

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

2660
        return nil
2661
}
4✔
2662

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

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

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

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

4✔
2692
        return externalIPs, nil
4✔
2693
}
8✔
2694

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

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

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

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

4✔
2730
        forwardedPorts := s.natTraversal.ForwardedPorts()
4✔
2731

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2852
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2853

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

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

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

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

×
2882
        return bootStrappers, nil
×
2883
}
×
2884

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

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

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

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

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

2915
        return ignore
2916
}
2917

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

2926
        defer s.wg.Done()
2927

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

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

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

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

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

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

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

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

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

×
2979
                                sampleTicker.Stop()
×
2980

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3239
        return nil
3240
}
3241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
3361
        return nil
4✔
3362
}
4✔
3363

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3540
                numOutboundConns++
×
3541
        }
×
3542

×
3543
        return nil
3544
}
3545

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

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

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

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

4✔
3576
                return
4✔
3577
        }
4✔
3578
        s.mu.Unlock()
4✔
3579
}
8✔
3580

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

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

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

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

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

4✔
3622
                        p.SendMessageLazy(false, msgs...)
3623
                }(sPeer)
3624
        }
3625

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

×
3630
        return nil
×
3631
}
×
3632

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

3640
        s.mu.Lock()
4✔
3641

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

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

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

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

4✔
3670
                select {
4✔
3671
                case peerChan <- peer:
4✔
3672
                case <-s.quit:
4✔
3673
                }
8✔
3674

8✔
3675
                return
8✔
3676
        }
4✔
3677

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

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

4✔
3693
        c := make(chan struct{})
4✔
3694

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

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

3711
        return c
3712
}
3713

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

4✔
3723
        pubStr := string(peerKey.SerializeCompressed())
4✔
3724

4✔
3725
        return s.findPeerByPubStr(pubStr)
8✔
3726
}
4✔
3727

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

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

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

4✔
3748
        return peer, nil
4✔
3749
}
4✔
3750

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

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

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

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

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

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

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

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

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

8✔
3823
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3824
        pubSer := nodePub.SerializeCompressed()
4✔
3825
        pubStr := string(pubSer)
3826

4✔
3827
        var pubBytes [33]byte
3828
        copy(pubBytes[:], pubSer)
3829

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

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

4✔
3840
                return
4✔
3841
        }
3842

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

×
3847
                conn.Close()
×
3848

3849
                return
3850
        }
3851

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

3859
                conn.Close()
3860
                return
3861
        }
3862

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

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

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

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

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

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

4✔
3910
                s.cancelConnReqs(pubStr, nil)
4✔
3911

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

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

8✔
3933
        nodePub := conn.(*brontide.Conn).RemotePub()
4✔
3934
        pubSer := nodePub.SerializeCompressed()
4✔
3935
        pubStr := string(pubSer)
4✔
3936

4✔
3937
        var pubBytes [33]byte
4✔
3938
        copy(pubBytes[:], pubSer)
4✔
3939

4✔
3940
        s.mu.Lock()
3941
        defer s.mu.Unlock()
3942

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

×
3950
                return
3951
        }
4✔
3952

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

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

4✔
3961
                conn.Close()
4✔
3962

4✔
3963
                return
4✔
3964
        }
4✔
3965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
4227
                        return s.genNodeAnnouncement(nil)
4✔
4228
                },
4✔
4229

4✔
4230
                PongBuf: s.pongBuf,
4✔
4231

4✔
4232
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4✔
4233

4✔
4234
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4✔
4235

4✔
4236
                FundingManager: s.fundingMgr,
4✔
4237

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

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

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

4✔
4276
        p := peer.NewBrontide(pCfg)
4✔
4277

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

4✔
4281
        s.addPeer(p)
4✔
4282

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

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

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

4✔
4302
        pubBytes := p.IdentityKey().SerializeCompressed()
4✔
4303

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

4310
                return
4311
        }
4312

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

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

4322
        s.peersByPub[pubStr] = p
4323

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4419
        p.WaitForDisconnect(ready)
4420

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

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

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

×
4436
        pubKey := p.IdentityKey()
4437

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

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

4✔
4452
        for _, link := range links {
4✔
4453
                s.htlcSwitch.RemoveLink(link.ChanID())
6✔
4454
        }
2✔
4455

2✔
4456
        s.mu.Lock()
2✔
4457
        defer s.mu.Unlock()
2✔
4458

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

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

4✔
4473
                pubKey := p.PubKey()
8✔
4474
                pubStr := string(pubKey[:])
4✔
4475

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4599
                s.connectToPersistentPeer(pubStr)
8✔
4600
        }()
4✔
4601
}
4602

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

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

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

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

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

8✔
4653
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
4✔
4654

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

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

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

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

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

4✔
4687
                        go s.connMgr.Connect(connReq)
4✔
4688

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

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

4✔
4707
        srvrLog.Debugf("removing peer %v", p)
4✔
4708

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

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

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

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

4✔
4727
        delete(s.peersByPub, pubStr)
4✔
4728

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

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

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

4✔
4746
        s.peerNotifier.NotifyPeerOffline(pubKey)
4✔
4747
}
8✔
4748

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

4✔
4757
        targetPub := string(addr.IdentityKey.SerializeCompressed())
4✔
4758

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

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

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

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

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

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

4✔
4805
                go s.connMgr.Connect(connReq)
4✔
4806

4✔
4807
                return nil
8✔
4808
        }
4✔
4809
        s.mu.Unlock()
8✔
4810

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

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

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

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

4✔
4844
        close(errChan)
4✔
4845

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

4✔
4849
        s.OutboundPeerConnected(nil, conn)
4850
}
4851

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

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

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

4✔
4871
        srvrLog.Infof("Disconnecting from %v", peer)
4✔
4872

4✔
4873
        s.cancelConnReqs(pubStr, nil)
4✔
4874

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

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

4✔
4885
        return nil
4✔
4886
}
4887

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

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

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

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

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

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

4✔
4935
                return req.Updates, req.Err
4✔
4936
        }
4✔
4937

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

4✔
4944
        return req.Updates, req.Err
4✔
4945
}
8✔
4946

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

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

4✔
4959
        return peers
4✔
4960
}
4✔
4961

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

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

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

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

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

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

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

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

4✔
5010
        return node.Addresses, nil
×
5011
}
×
5012

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

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

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

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

5037
        var (
4✔
5038
                peerAlias    *lnwire.ShortChannelID
5039
                defaultAlias lnwire.ShortChannelID
5040
        )
5041

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
5189
        return closedSCIDs
4✔
5190
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc