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

lightningnetwork / lnd / 12453190405

22 Dec 2024 12:46AM UTC coverage: 58.705% (+0.1%) from 58.598%
12453190405

Pull #8582

github

ziggie1984
docs: update release-docs
Pull Request #8582: set dont forward bit in chanupdate msg for private channels

340 of 432 new or added lines in 10 files covered. (78.7%)

60 existing lines in 11 files now uncovered.

135401 of 230646 relevant lines covered (58.71%)

19113.28 hits per line

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

64.17
/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)
3✔
156
}
3✔
157

3✔
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

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

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

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

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

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

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

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

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

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

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

3✔
435
                                        s.mu.Unlock()
6✔
436

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

3✔
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
3✔
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

3✔
462
        // Split the address into its host and port components.
3✔
463
        h, p, err := net.SplitHostPort(address)
3✔
464
        if err != nil {
3✔
465
                // If a port wasn't specified, we'll assume the address only
3✔
466
                // contains the host so we'll use the default port.
3✔
467
                host = address
3✔
468
                port = defaultPeerPort
3✔
469
        } else {
3✔
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
3✔
475
                }
3✔
476
                port = portNum
3✔
477
        }
3✔
478

3✔
479
        if tor.IsOnionHost(host) {
×
480
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
481
        }
3✔
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
3✔
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.
3✔
493
func noiseDial(idKey keychain.SingleKeyECDH,
3✔
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
        }
3✔
500
}
3✔
501

6✔
502
// newServer creates a new instance of the server which is to listen using the
3✔
503
// passed listener address.
3✔
504
func newServer(cfg *Config, listenAddrs []net.Addr,
3✔
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

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

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

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

×
540
        netParams := cfg.ActiveNetParams.Params
541

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

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

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

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

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

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

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

3✔
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(),
3✔
582
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
583
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
584
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
585
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
586
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
587
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
588
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
589
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
590
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
591
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
592
        })
3✔
593
        if err != nil {
3✔
594
                return nil, err
3✔
595
        }
3✔
596

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

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

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

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

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

3✔
634
                listenAddrs: listenAddrs,
3✔
635

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

3✔
640
                torController: torController,
3✔
641

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

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

3✔
658
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
659

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

3✔
662
                tlsManager: tlsManager,
3✔
663

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

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

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

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

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

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

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

3✔
694
                return nil
3✔
695
        }
3✔
696

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

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

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

×
719
                        peer.HandleLocalCloseChanReqs(request)
×
720
                },
721
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
3✔
722
                SwitchPackager:         channeldb.NewSwitchPackager(),
3✔
723
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
3✔
724
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
3✔
725
                Notifier:               s.cc.ChainNotifier,
3✔
726
                HtlcNotifier:           s.htlcNotifier,
3✔
727
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
6✔
728
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
3✔
729
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
3✔
730
                AllowCircularRoute:     cfg.AllowCircularRoute,
3✔
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 {
3✔
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
        )
3✔
758

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

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

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

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

3✔
785
                ctx, cancel := context.WithTimeout(
3✔
786
                        context.Background(), discoveryTimeout,
3✔
787
                )
3✔
788
                defer cancel()
3✔
789
                upnp, err := nat.DiscoverUPnP(ctx)
3✔
790
                if err == nil {
3✔
791
                        s.natTraversal = upnp
3✔
792
                } else {
3✔
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.
3✔
796
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
3✔
797
                                "device on the local network: %v", err)
3✔
798

3✔
799
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
3✔
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",
3✔
837
                                s.natTraversal.Name(), err)
6✔
838
                } else {
3✔
839
                        srvrLog.Infof("Automatically set up port forwarding "+
3✔
840
                                "using %s to advertise external IP",
3✔
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
3✔
868
        }
3✔
869

3✔
870
        // If no alias is provided, default to first 10 characters of public
3✔
871
        // key.
3✔
872
        alias := cfg.Alias
×
873
        if alias == "" {
×
874
                alias = hex.EncodeToString(serializedPubKey[:10])
875
        }
3✔
876
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
877
        if err != nil {
3✔
878
                return nil, err
3✔
879
        }
3✔
880
        selfNode := &models.LightningNode{
3✔
881
                HaveNodeAnnouncement: true,
3✔
882
                LastUpdate:           time.Now(),
3✔
883
                Addresses:            selfAddrs,
3✔
884
                Alias:                nodeAlias.String(),
3✔
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
3✔
892
        // network so we can properly sign it.
6✔
893
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
894
        if err != nil {
3✔
895
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
3✔
896
        }
3✔
897

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

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

3✔
929
        // Instantiate mission control with config from the sub server.
3✔
930
        //
3✔
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
3✔
937
        if cfg.Estimator != nil {
×
938
                estimator = cfg.Estimator
×
939
        } else {
3✔
940
                switch routingConfig.ProbabilityEstimatorType {
3✔
941
                case routing.AprioriEstimatorName:
3✔
942
                        aCfg := routingConfig.AprioriConfig
3✔
943
                        aprioriConfig := routing.AprioriConfig{
3✔
944
                                AprioriHopProbability: aCfg.HopProbability,
3✔
945
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
×
946
                                AprioriWeight:         aCfg.Weight,
×
947
                                CapacityFraction:      aCfg.CapacityFraction,
948
                        }
949

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

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

3✔
967
                        estimator, err = routing.NewBimodalEstimator(
3✔
968
                                bimodalConfig,
3✔
969
                        )
3✔
970
                        if err != nil {
3✔
971
                                return nil, err
3✔
972
                        }
3✔
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 "+
3✔
1000
                        "default namespace: %w", err)
3✔
1001
        }
3✔
1002

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

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

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

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

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

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

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

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

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

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

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

3✔
1100
                        return s.genNodeAnnouncement(nil)
3✔
1101
                },
×
1102
                ProofMatureDelta:        0,
×
1103
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1104
                RetransmitTicker:        ticker.New(time.Minute * 30),
3✔
1105
                RebroadcastInterval:     time.Hour * 24,
3✔
1106
                WaitingProofStore:       waitingProofStore,
3✔
1107
                MessageStore:            gossipMessageStore,
3✔
1108
                AnnSigner:               s.nodeSigner,
3✔
1109
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
3✔
1110
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
3✔
1111
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
3✔
1112
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
3✔
1113
                MinimumBatchSize:        10,
3✔
1114
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
3✔
1115
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
3✔
1116
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
3✔
1117
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
3✔
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,
3✔
1148
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
3✔
1149
                FetchChannel:              s.chanStateDB.FetchChannel,
3✔
1150
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
3✔
1151
                        return s.graphBuilder.AddEdge(edge)
3✔
1152
                },
3✔
1153
        }
6✔
1154

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

3✔
1163
        sweeperStore, err := sweep.NewSweeperStore(
3✔
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
        )
3✔
1175

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

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

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

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

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

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

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

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

3✔
1261
                        return addr.DeliveryAddress, nil
3✔
1262
                },
3✔
1263
                PublishTx: cc.Wallet.PublishTransaction,
3✔
1264
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1265
                        for _, msg := range msgs {
3✔
1266
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1267
                                if err != nil {
3✔
1268
                                        return err
3✔
1269
                                }
3✔
1270
                        }
3✔
1271
                        return nil
3✔
1272
                },
3✔
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
                },
3✔
1284
                PreimageDB:   s.witnessBeacon,
6✔
1285
                Notifier:     cc.ChainNotifier,
3✔
1286
                Mempool:      cc.MempoolNotifier,
3✔
1287
                Signer:       cc.Wallet.Cfg.Signer,
×
1288
                FeeEstimator: cc.FeeEstimator,
×
1289
                ChainIO:      cc.ChainIO,
1290
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
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,
3✔
1297
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1298

3✔
1299
                        // processACK will handle the BreachArbitrator ACKing
3✔
1300
                        // the event.
3✔
1301
                        finalErr := make(chan error, 1)
3✔
1302
                        processACK := func(brarErr error) {
3✔
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
3✔
1310
                                // was successful.
3✔
1311
                                finalErr <- nil
3✔
1312
                        }
3✔
1313

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

3✔
1320
                        // Send the contract breach event to the
3✔
1321
                        // BreachArbitrator.
6✔
1322
                        select {
3✔
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 {
3✔
1331
                        case err := <-finalErr:
1332
                                return err
1333
                        case <-s.quit:
3✔
1334
                                return ErrServerShuttingDown
3✔
1335
                        }
3✔
1336
                },
3✔
1337
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1338
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1339
                },
3✔
1340
                Sweeper:                       s.sweeper,
3✔
1341
                Registry:                      s.invoices,
3✔
1342
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
3✔
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,
3✔
1350
                HtlcNotifier:                  s.htlcNotifier,
3✔
1351
                Budget:                        *s.cfg.Sweeper.Budget,
3✔
1352

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

3✔
1357
                        // Get the circuit map.
3✔
1358
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
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
3✔
1375
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1376
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1377

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

3✔
1383
        // Wrap the `ReAddChannelEdge` method so that the funding manager can
3✔
1384
        // use it without depending on several layers of indirection.
1385
        reAssignSCID := func(aliasScID, newScID lnwire.ShortChannelID) (
3✔
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
3✔
1394
                        // funding manager was stepping through the delete
3✔
1395
                        // alias edge logic.
3✔
1396
                        return nil, nil
3✔
1397
                } else if err != nil {
3✔
1398
                        return nil, err
3✔
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()
3✔
1405

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

6✔
1411
                var ourPolicy *models.ChannelEdgePolicy
3✔
1412
                if info != nil && info.NodeKey1Bytes == ourKey {
3✔
1413
                        ourPolicy = e1
3✔
1414
                } else {
3✔
1415
                        ourPolicy = e2
3✔
1416
                }
6✔
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.
3✔
1422
                        return nil, fmt.Errorf("edge policy not found")
3✔
1423
                }
3✔
1424

3✔
1425
                // Update the policy data, this invalidates the signature
3✔
1426
                // therefore we need to resign the data.
3✔
1427
                ourPolicy.ChannelID = newEdgeInfo.ChannelID
3✔
1428

3✔
1429
                // Make sure we reset the msgFlag to not set the
3✔
1430
                // __dont_forward__ bit. We only reassign the SCID if it is a
3✔
1431
                // public channel.
6✔
1432
                ourPolicy.MessageFlags = lnwire.ChanUpdateRequiredMaxHtlc
3✔
1433
                chanUpdate := netann.UnsignedChannelUpdateFromEdge(
6✔
1434
                        newEdgeInfo, ourPolicy,
3✔
1435
                )
3✔
1436

1437
                data, err := chanUpdate.DataToSign()
3✔
NEW
1438
                if err != nil {
×
NEW
1439
                        return nil, err
×
UNCOV
1440
                }
×
UNCOV
1441

×
NEW
1442
                nodeSig, err := cc.MsgSigner.SignMessage(
×
1443
                        nodeKeyDesc.KeyLocator, data, true,
1444
                )
1445
                if err != nil {
1446
                        return nil, err
3✔
1447
                }
3✔
1448

3✔
1449
                sig, err := lnwire.NewSigFromSignature(nodeSig)
3✔
1450
                if err != nil {
3✔
1451
                        return nil, err
3✔
1452
                }
3✔
1453
                ourPolicy.SetSigBytes(sig.ToSignatureBytes())
3✔
1454

3✔
1455
                // Delete the old edge information under the alias SCID and add
3✔
1456
                // the updated data with the new SCID.
3✔
1457
                err = s.graphDB.ReAddChannelEdge(
3✔
NEW
1458
                        aliasScID.ToUint64(), newEdgeInfo, ourPolicy,
×
NEW
1459
                )
×
1460

1461
                return ourPolicy, err
3✔
1462
        }
3✔
1463

3✔
1464
        // For the reservationTimeout and the zombieSweeperInterval different
3✔
UNCOV
1465
        // values are set in case we are in a dev environment so enhance test
×
UNCOV
1466
        // capacilities.
×
1467
        reservationTimeout := chanfunding.DefaultReservationTimeout
1468
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1469

3✔
UNCOV
1470
        // Get the development config for funding manager. If we are not in
×
UNCOV
1471
        // development mode, this would be nil.
×
1472
        var devCfg *funding.DevConfig
3✔
1473
        if lncfg.IsDevBuild() {
3✔
1474
                devCfg = &funding.DevConfig{
3✔
1475
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1476
                }
3✔
1477

3✔
1478
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1479
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1480

3✔
1481
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
1482
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
1483
                        devCfg, reservationTimeout, zombieSweeperInterval)
1484
        }
1485

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

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

3✔
1524
                        // In case the user has explicitly specified
3✔
1525
                        // a default value for the number of
1526
                        // confirmations, we use it.
1527
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
1528
                        if defaultConf != 0 {
1529
                                return defaultConf
1530
                        }
1531

1532
                        minConf := uint64(3)
3✔
1533
                        maxConf := uint64(6)
3✔
1534

3✔
1535
                        // If this is a wumbo channel, then we'll require the
3✔
1536
                        // max amount of confirmations.
3✔
1537
                        if chanAmt > MaxFundingAmount {
3✔
1538
                                return uint16(maxConf)
3✔
1539
                        }
3✔
1540

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

1563
                        // In case the user has explicitly specified
×
1564
                        // a default value for the remote delay, we
×
1565
                        // use it.
×
1566
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
×
1567
                        if defaultDelay > 0 {
×
1568
                                return defaultDelay
×
1569
                        }
×
1570

×
1571
                        // If this is a wumbo channel, then we'll require the
×
1572
                        // max value.
×
1573
                        if chanAmt > MaxFundingAmount {
×
1574
                                return maxRemoteDelay
1575
                        }
3✔
1576

3✔
1577
                        // If not we scale according to channel size.
3✔
1578
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
3✔
1579
                                chanAmt / MaxFundingAmount)
3✔
1580
                        if delay < minRemoteDelay {
3✔
1581
                                delay = minRemoteDelay
3✔
1582
                        }
3✔
1583
                        if delay > maxRemoteDelay {
3✔
1584
                                delay = maxRemoteDelay
3✔
1585
                        }
3✔
1586
                        return delay
6✔
1587
                },
3✔
1588
                WatchNewChannel: func(channel *channeldb.OpenChannel,
3✔
1589
                        peerKey *btcec.PublicKey) error {
1590

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

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

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

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

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

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

1687
        // Assemble a peer notifier which will provide clients with subscriptions
1688
        // to peer online and offline events.
3✔
1689
        s.peerNotifier = peernotifier.New()
3✔
1690

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

1706
        if cfg.WtClient.Active {
1707
                policy := wtpolicy.DefaultPolicy()
1708
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1709

3✔
1710
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1711
                // protocol operations on sat/kw.
3✔
1712
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
6✔
1713
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1714
                )
3✔
1715

3✔
1716
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1717

3✔
1718
                if err := policy.Validate(); err != nil {
1719
                        return nil, err
1720
                }
1721

1722
                // authDial is the wrapper around the btrontide.Dial for the
1723
                // watchtower.
1724
                authDial := func(localKey keychain.SingleKeyECDH,
1725
                        netAddr *lnwire.NetAddress,
6✔
1726
                        dialer tor.DialFunc) (wtserver.Peer, error) {
3✔
1727

3✔
1728
                        return brontide.Dial(
3✔
1729
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1730
                        )
3✔
1731
                }
3✔
1732

3✔
1733
                // buildBreachRetribution is a call-back that can be used to
3✔
1734
                // query the BreachRetribution info and channel type given a
3✔
1735
                // channel ID and commitment height.
3✔
1736
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1737
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1738
                        channeldb.ChannelType, error) {
×
1739

×
1740
                        channel, err := s.chanStateDB.FetchChannelByID(
1741
                                nil, chanID,
1742
                        )
1743
                        if err != nil {
3✔
1744
                                return nil, 0, err
3✔
1745
                        }
6✔
1746

3✔
1747
                        br, err := lnwallet.NewBreachRetribution(
3✔
1748
                                channel, commitHeight, 0, nil,
3✔
1749
                                implCfg.AuxLeafStore,
3✔
1750
                                implCfg.AuxContractResolver,
3✔
1751
                        )
1752
                        if err != nil {
1753
                                return nil, 0, err
1754
                        }
1755

3✔
1756
                        return br, channel.ChanType, nil
3✔
1757
                }
6✔
1758

3✔
1759
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1760

3✔
1761
                // Copy the policy for legacy channels and set the blob flag
3✔
1762
                // signalling support for anchor channels.
3✔
1763
                anchorPolicy := policy
×
1764
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
×
1765

1766
                // Copy the policy for legacy channels and set the blob flag
3✔
1767
                // signalling support for taproot channels.
3✔
1768
                taprootPolicy := policy
3✔
1769
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1770
                        blob.FlagTaprootChannel,
3✔
1771
                )
3✔
1772

×
1773
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
×
1774
                        FetchClosedChannel:     fetchClosedChannel,
1775
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1776
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
1777
                        ChainNotifier:          s.cc.ChainNotifier,
1778
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1779
                                error) {
3✔
1780

3✔
1781
                                return s.channelNotifier.
3✔
1782
                                        SubscribeChannelEvents()
3✔
1783
                        },
3✔
1784
                        Signer: cc.Wallet.Cfg.Signer,
3✔
1785
                        NewAddress: func() ([]byte, error) {
3✔
1786
                                addr, err := newSweepPkScriptGen(
3✔
1787
                                        cc.Wallet, netParams,
3✔
1788
                                )().Unpack()
3✔
1789
                                if err != nil {
3✔
1790
                                        return nil, err
3✔
1791
                                }
3✔
1792

3✔
1793
                                return addr.DeliveryAddress, nil
3✔
1794
                        },
3✔
1795
                        SecretKeyRing:      s.cc.KeyRing,
3✔
1796
                        Dial:               cfg.net.Dial,
3✔
1797
                        AuthDial:           authDial,
3✔
1798
                        DB:                 dbs.TowerClientDB,
6✔
1799
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
3✔
1800
                        MinBackoff:         10 * time.Second,
3✔
1801
                        MaxBackoff:         5 * time.Minute,
3✔
1802
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
3✔
1803
                }, policy, anchorPolicy, taprootPolicy)
1804
                if err != nil {
3✔
1805
                        return nil, err
3✔
1806
                }
3✔
1807
        }
3✔
1808

3✔
1809
        if len(cfg.ExternalHosts) != 0 {
×
1810
                advertisedIPs := make(map[string]struct{})
×
1811
                for _, addr := range s.currentNodeAnn.Addresses {
1812
                        advertisedIPs[addr.String()] = struct{}{}
3✔
1813
                }
1814

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

3✔
1829
                                        return s.genNodeAnnouncement(
×
1830
                                                nil, modifier...,
×
1831
                                        )
×
1832
                                }),
×
1833
                })
1834
        }
×
1835

×
1836
        // Create liveness monitor.
×
1837
        s.createLivenessMonitor(cfg, cc, leaderElector)
×
1838

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

3✔
1857
        return s, nil
3✔
1858
}
3✔
1859

3✔
1860
// UpdateRoutingConfig is a callback function to update the routing config
3✔
1861
// values in the main cfg.
3✔
1862
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1863
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1864

3✔
1865
        switch c := cfg.Estimator.Config().(type) {
3✔
1866
        case routing.AprioriConfig:
3✔
1867
                routerCfg.ProbabilityEstimatorType =
3✔
1868
                        routing.AprioriEstimatorName
3✔
1869

3✔
1870
                targetCfg := routerCfg.AprioriConfig
3✔
1871
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1872
                targetCfg.Weight = c.AprioriWeight
×
1873
                targetCfg.CapacityFraction = c.CapacityFraction
×
1874
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1875

3✔
1876
        case routing.BimodalConfig:
3✔
1877
                routerCfg.ProbabilityEstimatorType =
3✔
1878
                        routing.BimodalEstimatorName
3✔
1879

3✔
1880
                targetCfg := routerCfg.BimodalConfig
1881
                targetCfg.Scale = int64(c.BimodalScaleMsat)
1882
                targetCfg.NodeWeight = c.BimodalNodeWeight
1883
                targetCfg.DecayTime = c.BimodalDecayTime
1884
        }
3✔
1885

3✔
1886
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1887
}
3✔
1888

3✔
1889
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
3✔
1890
// used for option_scid_alias channels where the ChannelUpdate to be sent back
3✔
1891
// may differ from what is on disk.
3✔
1892
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
3✔
1893
        error) {
3✔
1894

3✔
1895
        data, err := u.DataToSign()
3✔
1896
        if err != nil {
3✔
1897
                return nil, err
1898
        }
3✔
1899

3✔
1900
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1901
}
3✔
1902

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

1916
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
1917
        if cfg.Bitcoin.Node == "nochainbackend" {
1918
                srvrLog.Info("Disabling chain backend checks for " +
1919
                        "nochainbackend mode")
3✔
1920

3✔
1921
                chainBackendAttempts = 0
3✔
1922
        }
3✔
1923

3✔
1924
        chainHealthCheck := healthcheck.NewObservation(
3✔
1925
                "chain backend",
3✔
1926
                cc.HealthCheck,
3✔
1927
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1928
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1929
                cfg.HealthChecks.ChainCheck.Backoff,
1930
                chainBackendAttempts,
1931
        )
1932

1933
        diskCheck := healthcheck.NewObservation(
1934
                "disk space",
3✔
1935
                func() error {
3✔
1936
                        free, err := healthcheck.AvailableDiskSpaceRatio(
3✔
1937
                                cfg.LndDir,
3✔
1938
                        )
×
1939
                        if err != nil {
×
1940
                                return err
1941
                        }
3✔
1942

1943
                        // If we have more free space than we require,
1944
                        // we return a nil error.
1945
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
1946
                                return nil
1947
                        }
1948

1949
                        return fmt.Errorf("require: %v free space, got: %v",
1950
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
1951
                                free)
1952
                },
1953
                cfg.HealthChecks.DiskCheck.Interval,
1954
                cfg.HealthChecks.DiskCheck.Timeout,
1955
                cfg.HealthChecks.DiskCheck.Backoff,
3✔
1956
                cfg.HealthChecks.DiskCheck.Attempts,
3✔
1957
        )
3✔
1958

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

3✔
1973
                        // If the certificate is not outdated, no error needs
3✔
1974
                        // to be returned
3✔
1975
                        return nil
3✔
1976
                },
3✔
1977
                cfg.HealthChecks.TLSCheck.Interval,
×
1978
                cfg.HealthChecks.TLSCheck.Timeout,
×
1979
                cfg.HealthChecks.TLSCheck.Backoff,
×
1980
                cfg.HealthChecks.TLSCheck.Attempts,
×
1981
        )
×
1982

×
1983
        checks := []*healthcheck.Observation{
1984
                chainHealthCheck, diskCheck, tlsHealthCheck,
1985
        }
1986

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

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

×
2013
                remoteSignerConnectionCheck := healthcheck.NewObservation(
2014
                        "remote signer connection",
2015
                        rpcwallet.HealthCheck(
2016
                                s.cfg.RemoteSigner,
×
2017

2018
                                // For the health check we might to be even
2019
                                // stricter than the initial/normal connect, so
2020
                                // we use the health check timeout here.
2021
                                cfg.HealthChecks.RemoteSigner.Timeout,
2022
                        ),
2023
                        cfg.HealthChecks.RemoteSigner.Interval,
2024
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2025
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2026
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2027
                )
3✔
2028
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2029
        }
3✔
2030

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

6✔
2049
                                leader, err := leaderElector.IsLeader(
3✔
2050
                                        timeoutCtx,
3✔
2051
                                )
3✔
2052
                                if err != nil {
3✔
2053
                                        return fmt.Errorf("unable to check if "+
3✔
2054
                                                "still leader: %v", err)
3✔
2055
                                }
3✔
2056

3✔
2057
                                if !leader {
3✔
2058
                                        srvrLog.Debug("Not the current leader")
3✔
2059
                                        return fmt.Errorf("not the current " +
3✔
2060
                                                "leader")
3✔
2061
                                }
3✔
2062

3✔
2063
                                return nil
3✔
2064
                        },
3✔
2065
                        cfg.HealthChecks.LeaderCheck.Interval,
3✔
2066
                        cfg.HealthChecks.LeaderCheck.Timeout,
3✔
2067
                        cfg.HealthChecks.LeaderCheck.Backoff,
3✔
2068
                        cfg.HealthChecks.LeaderCheck.Attempts,
3✔
2069
                )
3✔
2070

3✔
2071
                checks = append(checks, leaderCheck)
2072
        }
2073

2074
        // If we have not disabled all of our health checks, we create a
2075
        // liveness monitor with our configured checks.
2076
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2077
                &healthcheck.Config{
×
2078
                        Checks:   checks,
×
2079
                        Shutdown: srvrLog.Criticalf,
×
2080
                },
×
2081
        )
×
2082
}
×
2083

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

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

×
2096
// add is used to add a cleanup function to be called when
×
2097
// the run function is executed.
2098
func (c cleaner) add(cleanup func() error) cleaner {
×
2099
        return append(c, cleanup)
×
2100
}
×
2101

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

2111
// Start starts the main daemon server, all requested listeners, and any helper
2112
// goroutines.
×
2113
// NOTE: This function is safe for concurrent access.
2114
//
2115
//nolint:funlen
2116
func (s *server) Start() error {
2117
        var startErr error
3✔
2118

3✔
2119
        // If one sub system fails to start, the following code ensures that the
3✔
2120
        // previous started ones are stopped. It also ensures a proper wallet
3✔
2121
        // shutdown which is important for releasing its resources (boltdb, etc...)
3✔
2122
        cleanup := cleaner{}
3✔
2123

2124
        s.start.Do(func() {
2125
                cleanup = cleanup.add(s.customMessageServer.Stop)
2126
                if err := s.customMessageServer.Start(); err != nil {
2127
                        startErr = err
3✔
2128
                        return
3✔
2129
                }
3✔
2130

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

2139
                if s.livenessMonitor != nil {
3✔
2140
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2141
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2142
                                startErr = err
2143
                                return
2144
                        }
×
2145
                }
×
2146

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

2158
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2159
                if err := s.writePool.Start(); err != nil {
3✔
2160
                        startErr = err
3✔
2161
                        return
3✔
2162
                }
3✔
2163

3✔
2164
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2165
                if err := s.readPool.Start(); err != nil {
×
2166
                        startErr = err
×
2167
                        return
2168
                }
3✔
2169

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

2176
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
2177
                if err := s.cc.BestBlockTracker.Start(); err != nil {
2178
                        startErr = err
2179
                        return
2180
                }
3✔
2181

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

3✔
2188
                cleanup = cleanup.add(func() error {
3✔
2189
                        return s.peerNotifier.Stop()
3✔
2190
                })
3✔
2191
                if err := s.peerNotifier.Start(); err != nil {
3✔
2192
                        startErr = err
3✔
2193
                        return
3✔
2194
                }
6✔
2195

3✔
2196
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2197
                if err := s.htlcNotifier.Start(); err != nil {
×
2198
                        startErr = err
×
2199
                        return
×
2200
                }
2201

3✔
2202
                if s.towerClientMgr != nil {
×
2203
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
×
2204
                        if err := s.towerClientMgr.Start(); err != nil {
×
2205
                                startErr = err
×
2206
                                return
×
2207
                        }
2208
                }
2209

6✔
2210
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2211
                if err := s.txPublisher.Start(); err != nil {
3✔
2212
                        startErr = err
×
2213
                        return
×
2214
                }
×
2215

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

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

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

2234
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2235
                if err := s.fundingMgr.Start(); err != nil {
3✔
2236
                        startErr = err
×
2237
                        return
×
2238
                }
×
2239

2240
                // htlcSwitch must be started before chainArb since the latter
3✔
2241
                // relies on htlcSwitch to deliver resolution message upon
3✔
2242
                // start.
×
2243
                cleanup = cleanup.add(s.htlcSwitch.Stop)
×
2244
                if err := s.htlcSwitch.Start(); err != nil {
×
2245
                        startErr = err
2246
                        return
3✔
2247
                }
3✔
2248

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

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

3✔
2261
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2262
                if err := s.chainArb.Start(); err != nil {
×
2263
                        startErr = err
×
2264
                        return
×
2265
                }
2266

6✔
2267
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2268
                if err := s.graphBuilder.Start(); err != nil {
3✔
2269
                        startErr = err
×
2270
                        return
×
2271
                }
×
2272

2273
                cleanup = cleanup.add(s.chanRouter.Stop)
2274
                if err := s.chanRouter.Start(); err != nil {
3✔
2275
                        startErr = err
3✔
2276
                        return
×
2277
                }
×
2278
                // The authGossiper depends on the chanRouter and therefore
×
2279
                // should be started after it.
2280
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2281
                if err := s.authGossiper.Start(); err != nil {
3✔
2282
                        startErr = err
×
2283
                        return
×
2284
                }
×
2285

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

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

2298
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2299
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2300
                        startErr = err
×
2301
                        return
×
2302
                }
×
2303

2304
                cleanup = cleanup.add(s.chanEventStore.Stop)
2305
                if err := s.chanEventStore.Start(); err != nil {
2306
                        startErr = err
2307
                        return
3✔
2308
                }
3✔
2309

×
2310
                cleanup.add(func() error {
×
2311
                        s.missionController.StopStoreTickers()
×
2312
                        return nil
2313
                })
3✔
2314
                s.missionController.RunStoreTickers()
3✔
2315

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

×
2348
                // chanSubSwapper must be started after the `channelNotifier`
×
2349
                // because it depends on channel events as a synchronization
2350
                // point.
3✔
2351
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2352
                if err := s.chanSubSwapper.Start(); err != nil {
×
2353
                        startErr = err
×
2354
                        return
×
2355
                }
2356

3✔
2357
                if s.torController != nil {
3✔
2358
                        cleanup = cleanup.add(s.torController.Stop)
×
2359
                        if err := s.createNewHiddenService(); err != nil {
×
2360
                                startErr = err
×
2361
                                return
2362
                        }
3✔
2363
                }
3✔
2364

×
2365
                if s.natTraversal != nil {
×
2366
                        s.wg.Add(1)
×
2367
                        go s.watchExternalIP()
2368
                }
3✔
2369

3✔
2370
                // Start connmgr last to prevent connections before init.
×
2371
                cleanup = cleanup.add(func() error {
×
2372
                        s.connMgr.Stop()
×
2373
                        return nil
2374
                })
3✔
2375
                s.connMgr.Start()
×
2376

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

×
2396
                        peerAddr := &lnwire.NetAddress{
×
2397
                                IdentityKey: parsedPubkey,
×
2398
                                Address:     addr,
×
2399
                                ChainNet:    s.cfg.ActiveNetParams.Net,
2400
                        }
6✔
2401

3✔
2402
                        err = s.ConnectToPeer(
3✔
2403
                                peerAddr, true,
3✔
2404
                                s.cfg.ConnectionTimeout,
3✔
2405
                        )
3✔
2406
                        if err != nil {
×
2407
                                startErr = fmt.Errorf("unable to connect to "+
×
2408
                                        "peer address provided as a config "+
×
2409
                                        "option: %v", err)
×
2410
                                return
2411
                        }
2412
                }
2413

2414
                // Subscribe to NodeAnnouncements that advertise new addresses
2415
                // our persistent peers.
3✔
2416
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2417
                        startErr = err
×
2418
                        return
×
2419
                }
×
2420

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

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

3✔
2445
                        result := make([][2]string, len(tuples))
3✔
2446
                        for idx, tuple := range tuples {
3✔
2447
                                tuple = strings.TrimSpace(tuple)
3✔
2448
                                if len(tuple) == 0 {
×
2449
                                        return
×
2450
                                }
×
2451

×
2452
                                servers := strings.Split(tuple, ",")
3✔
2453
                                if len(servers) > 2 || len(servers) == 0 {
3✔
2454
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2455
                                                "seed tuple: %v", servers)
×
2456
                                        return
×
2457
                                }
×
2458

×
2459
                                copy(result[idx][:], servers)
2460
                        }
3✔
2461

3✔
2462
                        chainreg.ChainDNSSeeds[genesisHash] = result
3✔
2463
                }
3✔
2464

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

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

×
2497
                        s.wg.Add(1)
×
2498
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2499
                } else {
2500
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
2501
                }
2502

2503
                // Set the active flag now that we've completed the full
2504
                // startup.
3✔
2505
                atomic.StoreInt32(&s.active, 1)
×
2506
        })
×
2507

×
2508
        if startErr != nil {
2509
                cleanup.run()
×
2510
        }
×
2511
        return startErr
×
2512
}
×
2513

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

×
2522
                close(s.quit)
2523

×
2524
                // Shutdown connMgr first to prevent conns during shutdown.
2525
                s.connMgr.Stop()
2526

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

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

3✔
2602
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2603
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
3✔
2604
                }
3✔
2605
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2606
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
3✔
2607
                }
×
2608
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
×
2609
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
3✔
2610
                                err)
×
2611
                }
×
2612
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2613
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2614
                                err)
×
2615
                }
3✔
2616
                s.missionController.StopStoreTickers()
×
2617

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

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

×
2641
                if s.hostAnn != nil {
×
2642
                        if err := s.hostAnn.Stop(); err != nil {
3✔
2643
                                srvrLog.Warnf("unable to shut down host "+
×
2644
                                        "annoucner: %v", err)
×
2645
                        }
3✔
2646
                }
×
2647

×
2648
                if s.livenessMonitor != nil {
3✔
2649
                        if err := s.livenessMonitor.Stop(); err != nil {
×
2650
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2651
                                        "monitor: %v", err)
3✔
2652
                        }
×
2653
                }
×
2654

3✔
2655
                // Wait for all lingering goroutines to quit.
×
2656
                srvrLog.Debug("Waiting for server to shutdown...")
×
2657
                s.wg.Wait()
3✔
2658

×
2659
                srvrLog.Debug("Stopping buffer pools...")
×
2660
                s.sigPool.Stop()
3✔
2661
                s.writePool.Stop()
×
2662
                s.readPool.Stop()
×
2663
        })
2664

2665
        return nil
2666
}
3✔
2667

3✔
2668
// Stopped returns true if the server has been instructed to shutdown.
3✔
2669
// NOTE: This function is safe for concurrent access.
3✔
2670
func (s *server) Stopped() bool {
×
2671
        return atomic.LoadInt32(&s.stopping) != 0
×
2672
}
3✔
2673

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

×
2686
        externalIPs := make([]string, 0, len(ports))
3✔
2687
        for _, port := range ports {
×
2688
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2689
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2690
                        continue
3✔
2691
                }
×
2692

×
2693
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2694
                externalIPs = append(externalIPs, hostIP)
3✔
2695
        }
3✔
2696

3✔
2697
        return externalIPs, nil
3✔
2698
}
6✔
2699

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

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

×
2724
        // Before exiting, we'll make sure to remove the forwarding rules set
2725
        // up by the server.
2726
        defer s.removePortForwarding()
6✔
2727

3✔
2728
        // Keep track of the external IPs set by the user to avoid replacing
×
2729
        // them when detecting a new IP.
×
2730
        ipsSetByUser := make(map[string]struct{})
×
2731
        for _, ip := range s.cfg.ExternalIPs {
2732
                ipsSetByUser[ip.String()] = struct{}{}
2733
        }
2734

3✔
2735
        forwardedPorts := s.natTraversal.ForwardedPorts()
3✔
2736

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

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

×
2767
                        if ip.Equal(s.lastDetectedIP) {
×
2768
                                continue
×
2769
                        }
2770

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

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

×
2788
                                newAddrs = append(newAddrs, addr)
×
2789
                        }
×
2790

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

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

×
2807
                        for _, addr := range currentNodeAnn.Addresses {
×
2808
                                host, _, err := net.SplitHostPort(addr.String())
×
2809
                                if err != nil {
×
2810
                                        srvrLog.Debugf("Unable to determine "+
×
2811
                                                "host from address %v: %v",
×
2812
                                                addr, err)
2813
                                        continue
×
2814
                                }
×
2815

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

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

×
2836
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2837
                        if err != nil {
×
2838
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2839
                                        "announcement to peers: %v", err)
×
2840
                                continue
×
2841
                        }
×
2842

×
2843
                        // Finally, update the last IP seen to the current one.
2844
                        s.lastDetectedIP = ip
2845
                case <-s.quit:
×
2846
                        break out
×
2847
                }
2848
        }
2849
}
×
2850

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

×
2857
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2858

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

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

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

2880
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
2881
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
2882
                        )
2883
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2884
                }
×
2885
        }
×
2886

×
2887
        return bootStrappers, nil
×
2888
}
×
2889

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

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

2902
        // We should ignore ourselves from bootstrapping.
2903
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
2904
        ignore[selfKey] = struct{}{}
2905

×
2906
        // Ignore all connected peers.
×
2907
        for _, peer := range s.peersByPub {
×
2908
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2909
                ignore[nID] = struct{}{}
×
2910
        }
×
2911

×
2912
        // Ignore all persistent peers as they have a dedicated reconnecting
2913
        // process.
2914
        for pubKeyStr := range s.persistentPeers {
×
2915
                var nID autopilot.NodeID
×
2916
                copy(nID[:], []byte(pubKeyStr))
×
2917
                ignore[nID] = struct{}{}
×
2918
        }
×
2919

2920
        return ignore
2921
}
2922

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

2931
        defer s.wg.Done()
2932

×
2933
        // Before we continue, init the ignore peers map.
×
2934
        ignoreList := s.createBootstrapIgnorePeers()
×
2935

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

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

×
2947
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2948
        // see if we've reached our minimum number of peers.
×
2949
        sampleTicker := time.NewTicker(backOff)
×
2950
        defer sampleTicker.Stop()
×
2951

×
2952
        // We'll use the number of attempts and errors to determine if we need
×
2953
        // to increase the time between discovery epochs.
×
2954
        var epochErrors uint32 // To be used atomically.
×
2955
        var epochAttempts uint32
×
2956

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

2968
                        // If we have enough peers, then we can loop back
2969
                        // around to the next round as we're done here.
2970
                        if numActivePeers >= numTargetPeers {
2971
                                continue
2972
                        }
2973

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

×
2981
                        if epochAttempts > 0 &&
×
2982
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2983

×
2984
                                sampleTicker.Stop()
×
2985

×
2986
                                backOff *= 2
×
2987
                                if backOff > bootstrapBackOffCeiling {
×
2988
                                        backOff = bootstrapBackOffCeiling
×
2989
                                }
2990

2991
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
2992
                                        "%v", backOff)
×
2993
                                sampleTicker = time.NewTicker(backOff)
×
2994
                                continue
×
2995
                        }
×
2996

×
2997
                        atomic.StoreUint32(&epochErrors, 0)
2998
                        epochAttempts = 0
×
2999

3000
                        // Since we know need more peers, we'll compute the
3001
                        // exact number we need to reach our threshold.
3002
                        numNeeded := numTargetPeers - numActivePeers
3003

3004
                        srvrLog.Debugf("Attempting to obtain %v more network "+
3005
                                "peers", numNeeded)
3006

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

×
3015
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3016
                                ignoreList, numNeeded*2, bootstrappers...,
×
3017
                        )
×
3018
                        if err != nil {
×
3019
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3020
                                        "peers: %v", err)
×
3021
                                continue
×
3022
                        }
×
3023

×
3024
                        // Finally, we'll launch a new goroutine for each
×
3025
                        // prospective peer candidates.
×
3026
                        for _, addr := range peerAddrs {
×
3027
                                epochAttempts++
×
3028

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

×
3043
                                                srvrLog.Errorf("Unable to "+
×
3044
                                                        "connect to %v: %v",
×
3045
                                                        a, err)
×
3046
                                                atomic.AddUint32(&epochErrors, 1)
×
3047
                                        case <-s.quit:
×
3048
                                        }
×
3049
                                }(addr)
×
3050
                        }
3051
                case <-s.quit:
3052
                        return
3053
                }
3054
        }
3055
}
3056

3057
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3058
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3059
// query back off each time we encounter a failure.
×
3060
const bootstrapBackOffCeiling = time.Minute * 5
×
3061

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

3069
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3070
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3071

×
3072
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3073
        // double each time we fail until we hit the bootstrapBackOffCeiling.
3074
        var delaySignal <-chan time.Time
3075
        delayTime := time.Second * 2
×
3076

×
3077
        // As want to be more aggressive, we'll use a lower back off celling
×
3078
        // then the main peer bootstrap logic.
×
3079
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3080

×
3081
        for attempts := 0; ; attempts++ {
×
3082
                // Check if the server has been requested to shut down in order
×
3083
                // to prevent blocking.
×
3084
                if s.Stopped() {
×
3085
                        return
×
3086
                }
×
3087

×
3088
                // We can exit our aggressive initial peer bootstrapping stage
×
3089
                // if we've reached out target number of peers.
×
3090
                s.mu.RLock()
×
3091
                numActivePeers := uint32(len(s.peersByPub))
×
3092
                s.mu.RUnlock()
×
3093

×
3094
                if numActivePeers >= numTargetPeers {
×
3095
                        return
×
3096
                }
×
3097

×
3098
                if attempts > 0 {
×
3099
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3100
                                "bootstrap peers (attempt #%v)", delayTime,
3101
                                attempts)
3102

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

×
3113
                        // After our delay, we'll double the time we wait up to
×
3114
                        // the max back off period.
×
3115
                        delayTime *= 2
×
3116
                        if delayTime > backOffCeiling {
×
3117
                                delayTime = backOffCeiling
×
3118
                        }
×
3119
                }
×
3120

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

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

3141
                                errChan := make(chan error, 1)
3142
                                go s.connectToPeer(
3143
                                        addr, errChan, s.cfg.ConnectionTimeout,
3144
                                )
3145

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

×
3169
                wg.Wait()
×
3170
        }
×
3171
}
×
3172

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

×
3185
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3186
        if err != nil {
×
3187
                return err
×
3188
        }
×
3189

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

×
3202
        switch {
×
3203
        case s.cfg.Tor.V2:
×
3204
                onionCfg.Type = tor.V2
×
3205
        case s.cfg.Tor.V3:
×
3206
                onionCfg.Type = tor.V3
×
3207
        }
×
3208

×
3209
        addr, err := s.torController.AddOnion(onionCfg)
3210
        if err != nil {
3211
                return err
3212
        }
3213

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

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

3244
        return nil
3245
}
3246

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

3253
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
×
3254
        if err != nil {
×
3255
                return nil, err
×
3256
        }
×
3257

×
3258
        for _, channel := range nodeChans {
×
3259
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
×
3260
                        return channel, nil
×
3261
                }
×
3262
        }
3263

×
3264
        return nil, fmt.Errorf("unable to find channel")
×
3265
}
×
3266

×
3267
// getNodeAnnouncement fetches the current, fully signed node announcement.
3268
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3269
        s.mu.Lock()
3270
        defer s.mu.Unlock()
3271

×
3272
        return *s.currentNodeAnn
×
3273
}
×
3274

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

×
3281
        s.mu.Lock()
×
3282
        defer s.mu.Unlock()
×
3283

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

×
3295
                // If we could successfully update our feature manager, add
×
3296
                // an update modifier to include these new features to our
×
3297
                // set.
×
3298
                modifiers = append(
3299
                        modifiers, netann.NodeAnnSetFeatures(features),
×
3300
                )
×
3301
        }
×
3302

×
3303
        // Always update the timestamp when refreshing to ensure the update
3304
        // propagates.
3305
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3306

×
3307
        // Apply the requested changes to the node announcement.
×
3308
        for _, modifier := range modifiers {
×
3309
                modifier(s.currentNodeAnn)
×
3310
        }
×
3311

×
3312
        // Sign a new update after applying all of the passed modifiers.
×
3313
        err := netann.SignNodeAnnouncement(
×
3314
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
×
3315
        )
×
3316
        if err != nil {
×
3317
                return lnwire.NodeAnnouncement{}, err
×
3318
        }
×
3319

×
3320
        return *s.currentNodeAnn, nil
×
3321
}
3322

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

3✔
3330
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3331
        if err != nil {
3✔
3332
                return fmt.Errorf("unable to generate new node "+
3✔
3333
                        "announcement: %v", err)
×
3334
        }
×
3335

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

3344
        selfNode.HaveNodeAnnouncement = true
3345
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3346
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3347
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3348
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3349
        selfNode.Color = newNodeAnn.RGBColor
3✔
3350
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3351

3✔
3352
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
3353

3354
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3355
                return fmt.Errorf("can't set self node: %w", err)
3356
        }
3357

3✔
3358
        // Finally, propagate it to the nodes in the network.
3✔
3359
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3360
        if err != nil {
3✔
3361
                rpcsLog.Debugf("Unable to broadcast new node "+
3✔
3362
                        "announcement to peers: %v", err)
3✔
3363
                return err
3✔
3364
        }
6✔
3365

3✔
3366
        return nil
3✔
3367
}
3✔
3368

3✔
3369
type nodeAddresses struct {
6✔
3370
        pubKey    *btcec.PublicKey
3✔
3371
        addresses []net.Addr
3✔
3372
}
3373

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

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

3400
        // After checking our previous connections for addresses to connect to,
3401
        // iterate through the nodes in our channel graph to find addresses
3402
        // that have been added via NodeAnnouncement messages.
3403
        sourceNode, err := s.graphDB.SourceNode()
3404
        if err != nil {
3405
                return err
3406
        }
3✔
3407

3✔
3408
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3✔
3409
        // each of the nodes.
6✔
3410
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3411
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3412
                tx kvdb.RTx,
3✔
3413
                chanInfo *models.ChannelEdgeInfo,
3414
                policy, _ *models.ChannelEdgePolicy) error {
3415

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

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

×
3435
                pubStr := string(channelPeer.PubKeyBytes[:])
3436

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

3446
                        // We'll only attempt to connect to Tor addresses if Tor
3447
                        // outbound support is enabled.
3448
                        case *tor.OnionAddr:
3449
                                if s.cfg.Tor.Active {
3450
                                        addrSet[addr.String()] = addr
3451
                                }
3452
                        }
3453
                }
3454

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

3✔
3464
                                // We'll only attempt to connect to Tor
3✔
3465
                                // addresses if Tor outbound support is enabled.
3✔
3466
                                case *tor.OnionAddr:
3✔
3467
                                        if s.cfg.Tor.Active {
×
3468
                                                addrSet[lnAddress.String()] = lnAddress
×
3469
                                        }
6✔
3470
                                }
3✔
3471
                        }
3✔
3472
                }
3✔
3473

3✔
3474
                // Construct a slice of the deduped addresses.
3✔
3475
                var addrs []net.Addr
3✔
3476
                for _, addr := range addrSet {
3✔
3477
                        addrs = append(addrs, addr)
3478
                }
3479

3480
                n := &nodeAddresses{
3481
                        addresses: addrs,
3✔
3482
                }
3✔
3483
                n.pubKey, err = channelPeer.PubKey()
×
3484
                if err != nil {
×
3485
                        return err
3486
                }
3487

3488
                nodeAddrsMap[pubStr] = n
3✔
3489
                return nil
3✔
3490
        })
3✔
3491
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3492
                return err
6✔
3493
        }
3✔
3494

3✔
3495
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3496
                len(nodeAddrsMap))
3✔
3497

3✔
3498
        // Acquire and hold server lock until all persistent connection requests
×
3499
        // have been recorded and sent to the connection manager.
×
3500
        s.mu.Lock()
×
3501
        defer s.mu.Unlock()
3502

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

3✔
3517
                for _, address := range nodeAddr.addresses {
3✔
3518
                        // Create a wrapper address which couples the IP and
3✔
3519
                        // the pubkey so the brontide authenticated connection
6✔
3520
                        // can be established.
3✔
3521
                        lnAddr := &lnwire.NetAddress{
3✔
3522
                                IdentityKey: nodeAddr.pubKey,
3✔
3523
                                Address:     address,
3524
                        }
3525

3526
                        s.persistentPeerAddrs[pubStr] = append(
×
3527
                                s.persistentPeerAddrs[pubStr], lnAddr)
×
3528
                }
×
3529

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

3✔
3540
                        go s.connectToPersistentPeer(pubStr)
3✔
3541
                } else {
3542
                        go s.delayInitialReconnect(pubStr)
3543
                }
3544

×
3545
                numOutboundConns++
×
3546
        }
×
3547

×
3548
        return nil
3549
}
3550

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

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

3✔
3570
        s.mu.Lock()
×
3571
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
×
3572
                delete(s.persistentPeers, pubKeyStr)
3573
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3574
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3575
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3576
                s.mu.Unlock()
3✔
3577

3✔
3578
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3579
                        "peer has no open channels", compressedPubKey)
3✔
3580

3✔
3581
                return
3✔
3582
        }
3✔
3583
        s.mu.Unlock()
3✔
3584
}
6✔
3585

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

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

3609
                peers = append(peers, sPeer)
3610
        }
3611
        s.mu.RUnlock()
3612

3613
        // Iterate over all known peers, dispatching a go routine to enqueue
3614
        // all messages to each of peers.
3615
        var wg sync.WaitGroup
3✔
3616
        for _, sPeer := range peers {
6✔
3617
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3618
                        sPeer.PubKey())
3✔
3619

3✔
3620
                // Dispatch a go routine to enqueue all messages to this peer.
×
3621
                wg.Add(1)
×
3622
                s.wg.Add(1)
3623
                go func(p lnpeer.Peer) {
3✔
3624
                        defer s.wg.Done()
3625
                        defer wg.Done()
3626

3✔
3627
                        p.SendMessageLazy(false, msgs...)
3628
                }(sPeer)
3629
        }
3630

3631
        // Wait for all messages to have been dispatched before returning to
3632
        // caller.
3633
        wg.Wait()
×
3634

×
3635
        return nil
×
3636
}
×
3637

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

3645
        s.mu.Lock()
3✔
3646

3✔
3647
        // Compute the target peer's identifier.
3✔
3648
        pubStr := string(peerKey[:])
3✔
3649

6✔
3650
        // Check if peer is connected.
3✔
3651
        peer, ok := s.peersByPub[pubStr]
3✔
3652
        if ok {
3✔
3653
                // Unlock here so that the mutex isn't held while we are
3✔
3654
                // waiting for the peer to become active.
3✔
3655
                s.mu.Unlock()
3✔
3656

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

3✔
3672
                // Connected, can return early.
3✔
3673
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3674

3✔
3675
                select {
3✔
3676
                case peerChan <- peer:
3✔
3677
                case <-s.quit:
3✔
3678
                }
6✔
3679

6✔
3680
                return
6✔
3681
        }
3✔
3682

3✔
3683
        // Not connected, store this listener such that it can be notified when
3✔
3684
        // the peer comes online.
3685
        s.peerConnectedListeners[pubStr] = append(
3686
                s.peerConnectedListeners[pubStr], peerChan,
3687
        )
3✔
3688
        s.mu.Unlock()
3689
}
3✔
3690

3✔
3691
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3✔
3692
// the given public key has been disconnected. The notification is signaled by
3✔
3693
// closing the channel returned.
3✔
3694
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
6✔
3695
        s.mu.Lock()
3✔
3696
        defer s.mu.Unlock()
3✔
3697

3✔
3698
        c := make(chan struct{})
3✔
3699

3✔
3700
        // If the peer is already offline, we can immediately trigger the
3✔
3701
        // notification.
6✔
3702
        peerPubKeyStr := string(peerPubKey[:])
3✔
3703
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3704
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
3✔
3705
                close(c)
3✔
3706
                return c
3✔
3707
        }
3708

3709
        // Otherwise, the peer is online, so we'll keep track of the channel to
3710
        // trigger the notification once the server detects the peer
3711
        // disconnects.
3✔
3712
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3713
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3714
        )
3715

3716
        return c
3717
}
3718

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

3✔
3728
        pubStr := string(peerKey.SerializeCompressed())
3✔
3729

3✔
3730
        return s.findPeerByPubStr(pubStr)
6✔
3731
}
3✔
3732

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

×
3742
        return s.findPeerByPubStr(pubStr)
×
3743
}
×
3744

×
3745
// findPeerByPubStr is an internal method that retrieves the specified peer from
×
3746
// the server's internal state using.
×
3747
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
×
3748
        peer, ok := s.peersByPub[pubStr]
3749
        if !ok {
3750
                return nil, ErrPeerNotConnected
3751
        }
3✔
3752

3✔
3753
        return peer, nil
3✔
3754
}
3✔
3755

×
3756
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3757
// exponential backoff. If no previous backoff was known, the default is
3758
// returned.
3✔
3759
func (s *server) nextPeerBackoff(pubStr string,
3760
        startTime time.Time) time.Duration {
3761

3762
        // Now, determine the appropriate backoff to use for the retry.
3763
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3764
        if !ok {
3✔
3765
                // If an existing backoff was unknown, use the default.
3✔
3766
                return s.cfg.MinBackoff
3✔
3767
        }
3768

3769
        // If the peer failed to start properly, we'll just use the previous
3770
        // backoff to compute the subsequent randomized exponential backoff
3771
        // duration. This will roughly double on average.
3772
        if startTime.IsZero() {
3✔
3773
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3774
        }
3✔
3775

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

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

3✔
3794
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3✔
3795
        // the stable connection lasted much longer than our previous backoff.
3796
        // To reward such good behavior, we'll reconnect after the default
3797
        // timeout.
3798
        return s.cfg.MinBackoff
3799
}
3800

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

3811
        // The connection that comes from the node with a "smaller" pubkey
3812
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
3813
        // should drop our established connection.
3814
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
3815
}
3816

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

6✔
3828
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3829
        pubSer := nodePub.SerializeCompressed()
3✔
3830
        pubStr := string(pubSer)
3831

3✔
3832
        var pubBytes [33]byte
3833
        copy(pubBytes[:], pubSer)
3834

3835
        s.mu.Lock()
3836
        defer s.mu.Unlock()
3837

3838
        // If the remote node's public key is banned, drop the connection.
3✔
3839
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3840
        if dcErr != nil {
3✔
3841
                srvrLog.Errorf("Unable to check if we should disconnect "+
3✔
3842
                        "peer: %v", dcErr)
6✔
3843
                conn.Close()
3✔
3844

3✔
3845
                return
3✔
3846
        }
3847

3848
        if shouldDc {
3849
                srvrLog.Debugf("Dropping connection for %v since they are "+
3850
                        "banned.", pubSer)
3✔
3851

×
3852
                conn.Close()
×
3853

3854
                return
3855
        }
3856

3857
        // If we already have an outbound connection to this peer, then ignore
3✔
3858
        // this new connection.
6✔
3859
        if p, ok := s.outboundPeers[pubStr]; ok {
3✔
3860
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3861
                        "ignoring inbound connection from local=%v, remote=%v",
3862
                        p, conn.LocalAddr(), conn.RemoteAddr())
3863

3864
                conn.Close()
3865
                return
3866
        }
3867

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

3878
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3879

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

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

3✔
3903
                        srvrLog.Warnf("Received inbound connection from "+
×
3904
                                "peer %v, but already have outbound "+
×
3905
                                "connection, dropping conn", connectedPeer)
3906
                        conn.Close()
3✔
3907
                        return
3✔
3908
                }
3✔
3909

3✔
3910
                // Otherwise, if we should drop the connection, then we'll
3✔
3911
                // disconnect our already connected peer.
3✔
3912
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
3913
                        connectedPeer)
3✔
3914

3✔
3915
                s.cancelConnReqs(pubStr, nil)
3✔
3916

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

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

6✔
3938
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3939
        pubSer := nodePub.SerializeCompressed()
3✔
3940
        pubStr := string(pubSer)
3✔
3941

3✔
3942
        var pubBytes [33]byte
3✔
3943
        copy(pubBytes[:], pubSer)
3✔
3944

3✔
3945
        s.mu.Lock()
3946
        defer s.mu.Unlock()
3947

3948
        // If the remote node's public key is banned, drop the connection.
3949
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3950
        if dcErr != nil {
×
3951
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3952
                        "peer: %v", dcErr)
×
3953
                conn.Close()
×
3954

×
3955
                return
3956
        }
3✔
3957

3✔
3958
        if shouldDc {
3✔
3959
                srvrLog.Debugf("Dropping connection for %v since they are "+
3✔
3960
                        "banned.", pubSer)
3✔
3961

3✔
3962
                if connReq != nil {
3✔
3963
                        s.connMgr.Remove(connReq.ID())
3✔
3964
                }
3✔
3965

3✔
3966
                conn.Close()
3✔
3967

3✔
3968
                return
3✔
3969
        }
3✔
3970

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

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

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

×
3997
                if connReq != nil {
×
3998
                        s.connMgr.Remove(connReq.ID())
×
3999
                }
×
4000

×
4001
                conn.Close()
×
4002
                return
×
4003
        }
4004

4005
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
4006
                conn.RemoteAddr())
4007

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

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

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

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

4051
                // Otherwise, _their_ connection should be dropped. So we'll
6✔
4052
                // disconnect the peer and send the now obsolete peer to the
3✔
4053
                // server for garbage collection.
3✔
4054
                srvrLog.Debugf("Disconnecting stale connection to %v",
3✔
4055
                        connectedPeer)
3✔
4056

6✔
4057
                // Remove the current peer from the server's internal state and
3✔
4058
                // signal that the peer termination watcher does not need to
3✔
4059
                // execute for this peer.
3✔
4060
                s.removePeer(connectedPeer)
3✔
4061
                s.ignorePeerTermination[connectedPeer] = struct{}{}
4062
                s.scheduledPeerConnection[pubStr] = func() {
3✔
4063
                        s.peerConnected(conn, connReq, false)
×
4064
                }
×
4065
        }
×
4066
}
×
4067

×
4068
// UnassignedConnID is the default connection ID that a request can have before
4069
// it actually is submitted to the connmgr.
4070
// TODO(conner): move into connmgr package, or better, add connmgr method for
4071
// generating atomic IDs
4072
const UnassignedConnID uint64 = 0
3✔
4073

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

3✔
4088
        // Next, check to see if we have any outstanding persistent connection
3✔
4089
        // requests to this peer. If so, then we'll remove all of these
3✔
4090
        // connection requests, and also delete the entry from the map.
3✔
4091
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4092
        if !ok {
6✔
4093
                return
3✔
4094
        }
3✔
4095

3✔
4096
        for _, connReq := range connReqs {
3✔
4097
                srvrLog.Tracef("Canceling %s:", connReqs)
4098

4099
                // Atomically capture the current request identifier.
4100
                connID := connReq.ID()
4101

4102
                // Skip any zero IDs, this indicates the request has not
3✔
4103
                // yet been schedule.
3✔
4104
                if connID == UnassignedConnID {
3✔
4105
                        continue
3✔
4106
                }
3✔
4107

3✔
4108
                // Skip a particular connection ID if instructed.
4109
                if skip != nil && connID == *skip {
×
4110
                        continue
×
4111
                }
×
4112

×
4113
                s.connMgr.Remove(connID)
×
4114
        }
×
4115

×
4116
        delete(s.persistentConnReqs, pubStr)
×
4117
}
×
4118

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

×
4125
        return s.customMessageServer.SendUpdate(&CustomMessage{
×
4126
                Peer: peer,
×
4127
                Msg:  msg,
4128
        })
4129
}
4130

4131
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4132
// messages.
×
4133
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
×
4134
        return s.customMessageServer.Subscribe()
×
4135
}
×
4136

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

4144
        brontideConn := conn.(*brontide.Conn)
4145
        addr := conn.RemoteAddr()
4146
        pubKey := brontideConn.RemotePub()
4147

4148
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
4149
                pubKey.SerializeCompressed(), addr, inbound)
4150

4151
        peerAddr := &lnwire.NetAddress{
4152
                IdentityKey: pubKey,
4153
                Address:     addr,
4154
                ChainNet:    s.cfg.ActiveNetParams.Net,
4155
        }
4156

4157
        // With the brontide connection established, we'll now craft the feature
4158
        // vectors to advertise to the remote node.
3✔
4159
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4160
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4161

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

6✔
4175
        // If we directly set the peer.Config TowerClient member to the
3✔
4176
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
3✔
4177
        // the peer.Config's TowerClient member will not evaluate to nil even
3✔
4178
        // though the underlying value is nil. To avoid this gotcha which can
3✔
4179
        // cause a panic, we need to explicitly pass nil to the peer.Config's
3✔
4180
        // TowerClient if needed.
3✔
4181
        var towerClient wtclient.ClientManager
3✔
4182
        if s.towerClientMgr != nil {
3✔
4183
                towerClient = s.towerClientMgr
×
4184
        }
4185

4186
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
4187
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
6✔
4188

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

3✔
4232
                        return s.genNodeAnnouncement(nil)
3✔
4233
                },
3✔
4234

3✔
4235
                PongBuf: s.pongBuf,
3✔
4236

3✔
4237
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
3✔
4238

3✔
4239
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
3✔
4240

3✔
4241
                FundingManager: s.fundingMgr,
3✔
4242

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

3✔
4272
                        return clock.NewDefaultClock().Now().Before(
3✔
4273
                                EndorsementExperimentEnd,
3✔
4274
                        )
3✔
4275
                },
3✔
4276
        }
3✔
4277

3✔
4278
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4279
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4280

3✔
4281
        p := peer.NewBrontide(pCfg)
3✔
4282

3✔
4283
        // TODO(roasbeef): update IP address for link-node
3✔
4284
        //  * also mark last-seen, do it one single transaction?
3✔
4285

3✔
4286
        s.addPeer(p)
3✔
4287

3✔
4288
        // Once we have successfully added the peer to the server, we can
3✔
4289
        // delete the previous error buffer from the server's map of error
3✔
4290
        // buffers.
3✔
4291
        delete(s.peerErrors, pkStr)
3✔
4292

3✔
4293
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4294
        // includes sending and receiving Init messages, which would be a DOS
3✔
4295
        // vector if we held the server's mutex throughout the procedure.
3✔
4296
        s.wg.Add(1)
3✔
4297
        go s.peerInitializer(p)
3✔
4298
}
3✔
4299

3✔
4300
// addPeer adds the passed peer to the server's global state of all active
3✔
4301
// peers.
3✔
4302
func (s *server) addPeer(p *peer.Brontide) {
3✔
4303
        if p == nil {
3✔
4304
                return
3✔
4305
        }
3✔
4306

3✔
4307
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4308

6✔
4309
        // Ignore new peers if we're shutting down.
3✔
4310
        if s.Stopped() {
3✔
4311
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
3✔
4312
                        pubBytes)
4313
                p.Disconnect(ErrServerShuttingDown)
4314

4315
                return
4316
        }
4317

4318
        // Track the new peer in our indexes so we can quickly look it up either
4319
        // according to its public key, or its peer ID.
4320
        // TODO(roasbeef): pipe all requests through to the
4321
        // queryHandler/peerManager
4322

4323
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4324
        // be human-readable.
4325
        pubStr := string(pubBytes)
4326

4327
        s.peersByPub[pubStr] = p
4328

4329
        if p.Inbound() {
4330
                s.inboundPeers[pubStr] = p
4331
        } else {
4332
                s.outboundPeers[pubStr] = p
4333
        }
4334

4335
        // Inform the peer notifier of a peer online event so that it can be reported
4336
        // to clients listening for peer events.
4337
        var pubKey [33]byte
4338
        copy(pubKey[:], pubBytes)
4339

4340
        s.peerNotifier.NotifyPeerOnline(pubKey)
4341
}
4342

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

4355
        pubBytes := p.IdentityKey().SerializeCompressed()
4356

3✔
4357
        // Avoid initializing peers while the server is exiting.
3✔
4358
        if s.Stopped() {
3✔
4359
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
3✔
4360
                        pubBytes)
3✔
4361
                return
3✔
4362
        }
3✔
4363

3✔
4364
        // Create a channel that will be used to signal a successful start of
3✔
4365
        // the link. This prevents the peer termination watcher from beginning
3✔
4366
        // its duty too early.
3✔
4367
        ready := make(chan struct{})
3✔
4368

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

4378
        // Start the peer! If an error occurs, we Disconnect the peer, which
4379
        // will unblock the peerTerminationWatcher.
4380
        if err := p.Start(); err != nil {
3✔
4381
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4382

×
4383
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
4384
                return
4385
        }
3✔
4386

3✔
4387
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
3✔
4388
        // was successful, and to begin watching the peer's wait group.
3✔
4389
        close(ready)
×
4390

×
4391
        s.mu.Lock()
×
4392
        defer s.mu.Unlock()
×
4393

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

4397
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
4398
        // route.Vertex as the key type of peerConnectedListeners.
4399
        pubStr := string(pubBytes)
4400
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
4401
                select {
4402
                case peerChan <- p:
4403
                case <-s.quit:
3✔
4404
                        return
3✔
4405
                }
3✔
4406
        }
3✔
4407
        delete(s.peerConnectedListeners, pubStr)
6✔
4408
}
3✔
4409

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

4424
        p.WaitForDisconnect(ready)
4425

4426
        srvrLog.Debugf("Peer %v has been disconnected", p)
4427

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

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

×
4441
        pubKey := p.IdentityKey()
4442

4443
        // We'll also inform the gossiper that this peer is no longer active,
4444
        // so we don't need to maintain sync state for it any longer.
4445
        s.authGossiper.PruneSyncState(p.PubKey())
3✔
4446

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

3✔
4457
        for _, link := range links {
3✔
4458
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4459
        }
×
4460

×
4461
        s.mu.Lock()
×
4462
        defer s.mu.Unlock()
×
4463

×
4464
        // If there were any notification requests for when this peer
4465
        // disconnected, we can trigger them now.
4466
        srvrLog.Debugf("Notifying that peer %v is offline", p)
4467
        pubStr := string(pubKey.SerializeCompressed())
3✔
4468
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
3✔
4469
                close(offlineChan)
3✔
4470
        }
3✔
4471
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4472

3✔
4473
        // If the server has already removed this peer, we can short circuit the
3✔
4474
        // peer termination watcher and skip cleanup.
3✔
4475
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4476
                delete(s.ignorePeerTermination, p)
3✔
4477

3✔
4478
                pubKey := p.PubKey()
6✔
4479
                pubStr := string(pubKey[:])
3✔
4480

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

4494
        // First, cleanup any remaining state the server has regarding the peer
4495
        // in question.
4496
        s.removePeer(p)
4497

4498
        // Next, check to see if this is a persistent peer or not.
4499
        if _, ok := s.persistentPeers[pubStr]; !ok {
3✔
4500
                return
3✔
4501
        }
3✔
4502

3✔
4503
        // Get the last address that we used to connect to the peer.
3✔
4504
        addrs := []net.Addr{
3✔
4505
                p.NetAddress().Address,
3✔
4506
        }
3✔
4507

3✔
4508
        // We'll ensure that we locate all the peers advertised addresses for
6✔
4509
        // reconnection purposes.
3✔
4510
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4511
        switch {
3✔
4512
        // We found advertised addresses, so use them.
4513
        case err == nil:
4514
                addrs = advertisedAddrs
4515

4516
        // The peer doesn't have an advertised address.
4517
        case err == errNoAdvertisedAddr:
3✔
4518
                // If it is an outbound peer then we fall back to the existing
3✔
4519
                // peer address.
3✔
4520
                if !p.Inbound() {
3✔
4521
                        break
3✔
4522
                }
3✔
4523

3✔
4524
                // Fall back to the existing peer address if
3✔
4525
                // we're not accepting connections over Tor.
3✔
4526
                if s.torController == nil {
3✔
4527
                        break
3✔
4528
                }
3✔
4529

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

3✔
4540
        // We came across an error retrieving an advertised
3✔
4541
        // address, log it, and fall back to the existing peer
3✔
4542
        // address.
3✔
4543
        default:
3✔
4544
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4545
                        "address for node %x: %v", p.PubKey(),
3✔
4546
                        err)
6✔
4547
        }
3✔
4548

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

×
4556
        // Add any missing addresses for this peer to persistentPeerAddr.
×
4557
        for _, addr := range addrs {
×
4558
                if existingAddrs[addr.String()] {
×
4559
                        continue
×
4560
                }
×
4561

×
4562
                s.persistentPeerAddrs[pubStr] = append(
×
4563
                        s.persistentPeerAddrs[pubStr],
×
4564
                        &lnwire.NetAddress{
×
4565
                                IdentityKey: p.IdentityKey(),
×
4566
                                Address:     addr,
×
4567
                                ChainNet:    p.NetAddress().ChainNet,
×
4568
                        },
×
4569
                )
×
4570
        }
4571

4572
        // Record the computed backoff in the backoff map.
4573
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
4574
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4575

3✔
4576
        // Initialize a retry canceller for this peer if one does not
3✔
4577
        // exist.
6✔
4578
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4579
        if !ok {
3✔
4580
                cancelChan = make(chan struct{})
4581
                s.persistentRetryCancels[pubStr] = cancelChan
4582
        }
3✔
4583

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

3✔
4592
                select {
3✔
4593
                case <-time.After(backoff):
4594
                case <-cancelChan:
4595
                        return
3✔
4596
                case <-s.quit:
3✔
4597
                        return
3✔
4598
                }
6✔
4599

3✔
4600
                srvrLog.Debugf("Attempting to re-establish persistent "+
4601
                        "connection to peer %x",
4602
                        p.IdentityKey().SerializeCompressed())
4603

4604
                s.connectToPersistentPeer(pubStr)
6✔
4605
        }()
3✔
4606
}
4607

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

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

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

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

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

6✔
4658
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4659

3✔
4660
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4661
        if !ok {
4662
                cancelChan = make(chan struct{})
4663
                s.persistentRetryCancels[pubKeyStr] = cancelChan
4664
        }
4665

6✔
4666
        // Any addresses left in addrMap are new ones that we have not made
3✔
4667
        // connection requests for. So create new connection requests for those.
3✔
4668
        // If there is more than one address in the address map, stagger the
3✔
4669
        // creation of the connection requests for those.
3✔
4670
        go func() {
3✔
4671
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4672
                defer ticker.Stop()
3✔
4673

3✔
4674
                for _, addr := range addrMap {
3✔
4675
                        // Send the persistent connection request to the
3✔
4676
                        // connection manager, saving the request itself so we
4677
                        // can cancel/restart the process as needed.
4678
                        connReq := &connmgr.ConnReq{
3✔
4679
                                Addr:      addr,
3✔
4680
                                Permanent: true,
3✔
4681
                        }
3✔
4682

3✔
4683
                        s.mu.Lock()
4684
                        s.persistentConnReqs[pubKeyStr] = append(
4685
                                s.persistentConnReqs[pubKeyStr], connReq,
4686
                        )
4687
                        s.mu.Unlock()
4688

4689
                        srvrLog.Debugf("Attempting persistent connection to "+
4690
                                "channel peer %v", addr)
4691

3✔
4692
                        go s.connMgr.Connect(connReq)
3✔
4693

3✔
4694
                        select {
3✔
4695
                        case <-s.quit:
3✔
4696
                                return
3✔
4697
                        case <-cancelChan:
3✔
4698
                                return
3✔
4699
                        case <-ticker.C:
3✔
4700
                        }
3✔
4701
                }
6✔
4702
        }()
3✔
4703
}
3✔
4704

4705
// removePeer removes the passed peer from the server's state of all active
4706
// peers.
4707
func (s *server) removePeer(p *peer.Brontide) {
4708
        if p == nil {
4709
                return
3✔
4710
        }
6✔
4711

3✔
4712
        srvrLog.Debugf("removing peer %v", p)
3✔
4713

3✔
4714
        // As the peer is now finished, ensure that the TCP connection is
4715
        // closed and all of its related goroutines have exited.
4716
        p.Disconnect(fmt.Errorf("server: disconnecting peer %v", p))
4717

4718
        // If this peer had an active persistent connection request, remove it.
×
4719
        if p.ConnReq() != nil {
×
4720
                s.connMgr.Remove(p.ConnReq().ID())
×
4721
        }
×
4722

×
4723
        // Ignore deleting peers if we're shutting down.
4724
        if s.Stopped() {
4725
                return
4726
        }
4727

4728
        pKey := p.PubKey()
3✔
4729
        pubSer := pKey[:]
3✔
4730
        pubStr := string(pubSer)
3✔
4731

3✔
4732
        delete(s.peersByPub, pubStr)
3✔
4733

4734
        if p.Inbound() {
4735
                delete(s.inboundPeers, pubStr)
4736
        } else {
3✔
4737
                delete(s.outboundPeers, pubStr)
3✔
4738
        }
3✔
4739

6✔
4740
        // Copy the peer's error buffer across to the server if it has any items
3✔
4741
        // in it so that we can restore peer errors across connections.
3✔
4742
        if p.ErrorBuffer().Total() > 0 {
3✔
4743
                s.peerErrors[pubStr] = p.ErrorBuffer()
4744
        }
4745

4746
        // Inform the peer notifier of a peer offline event so that it can be
4747
        // reported to clients listening for peer events.
4748
        var pubKey [33]byte
6✔
4749
        copy(pubKey[:], pubSer)
3✔
4750

3✔
4751
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4752
}
6✔
4753

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

3✔
4762
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4763

3✔
4764
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4765
        // better granularity.  In certain conditions, this method requires
3✔
4766
        // making an outbound connection to a remote peer, which requires the
3✔
4767
        // lock to be released, and subsequently reacquired.
3✔
4768
        s.mu.Lock()
3✔
4769

3✔
4770
        // Ensure we're not already connected to this peer.
3✔
4771
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4772
        if err == nil {
3✔
4773
                s.mu.Unlock()
3✔
4774
                return &errPeerAlreadyConnected{peer: peer}
3✔
4775
        }
3✔
4776

3✔
4777
        // Peer was not found, continue to pursue connection with peer.
3✔
4778

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

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

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

3✔
4810
                go s.connMgr.Connect(connReq)
3✔
4811

3✔
4812
                return nil
6✔
4813
        }
3✔
4814
        s.mu.Unlock()
6✔
4815

3✔
4816
        // If we're not making a persistent connection, then we'll attempt to
3✔
4817
        // connect to the target peer. If the we can't make the connection, or
4818
        // the crypto negotiation breaks down, then return an error to the
4819
        // caller.
4820
        errChan := make(chan error, 1)
6✔
4821
        s.connectToPeer(addr, errChan, timeout)
3✔
4822

3✔
4823
        select {
4824
        case err := <-errChan:
4825
                return err
4826
        case <-s.quit:
3✔
4827
                return ErrServerShuttingDown
3✔
4828
        }
3✔
4829
}
3✔
4830

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

4837
        conn, err := brontide.Dial(
4838
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4839
        )
3✔
4840
        if err != nil {
3✔
4841
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4842
                select {
3✔
4843
                case errChan <- err:
3✔
4844
                case <-s.quit:
3✔
4845
                }
3✔
4846
                return
3✔
4847
        }
3✔
4848

3✔
4849
        close(errChan)
3✔
4850

6✔
4851
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4852
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4853

3✔
4854
        s.OutboundPeerConnected(nil, conn)
4855
}
4856

4857
// DisconnectPeer sends the request to server to close the connection with peer
4858
// identified by public key.
4859
//
4860
// NOTE: This function is safe for concurrent access.
6✔
4861
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4862
        pubBytes := pubKey.SerializeCompressed()
3✔
4863
        pubStr := string(pubBytes)
3✔
4864

4865
        s.mu.Lock()
4866
        defer s.mu.Unlock()
4867

4868
        // Check that were actually connected to this peer. If not, then we'll
3✔
4869
        // exit in an error as we can't disconnect from a peer that we're not
6✔
4870
        // currently connected to.
3✔
4871
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4872
        if err == ErrPeerNotConnected {
3✔
4873
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4874
        }
3✔
4875

3✔
4876
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4877

3✔
4878
        s.cancelConnReqs(pubStr, nil)
3✔
4879

3✔
4880
        // If this peer was formerly a persistent connection, then we'll remove
6✔
4881
        // them from this map so we don't attempt to re-connect after we
3✔
4882
        // disconnect.
3✔
4883
        delete(s.persistentPeers, pubStr)
3✔
4884
        delete(s.persistentPeersBackoff, pubStr)
3✔
4885

3✔
4886
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4887
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4888
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4889

3✔
4890
        return nil
3✔
4891
}
4892

3✔
4893
// OpenChannel sends a request to the server to open a channel to the specified
3✔
4894
// peer identified by nodeKey with the passed channel funding parameters.
3✔
4895
//
3✔
4896
// NOTE: This function is safe for concurrent access.
3✔
4897
func (s *server) OpenChannel(
3✔
4898
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4899

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

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

3✔
4914
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
3✔
4915
                return req.Updates, req.Err
3✔
4916
        }
3✔
4917
        req.Peer = peer
3✔
4918
        s.mu.RUnlock()
6✔
4919

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

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

3✔
4940
                return req.Updates, req.Err
3✔
4941
        }
3✔
4942

3✔
4943
        // Spawn a goroutine to send the funding workflow request to the funding
3✔
4944
        // manager. This allows the server to continue handling queries instead
3✔
4945
        // of blocking on this request which is exported as a synchronous
3✔
4946
        // request to the outside world.
3✔
4947
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4948

3✔
4949
        return req.Updates, req.Err
3✔
4950
}
6✔
4951

3✔
4952
// Peers returns a slice of all active peers.
3✔
4953
//
4954
// NOTE: This function is safe for concurrent access.
3✔
4955
func (s *server) Peers() []*peer.Brontide {
3✔
4956
        s.mu.RLock()
3✔
4957
        defer s.mu.RUnlock()
3✔
4958

3✔
4959
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4960
        for _, peer := range s.peersByPub {
3✔
4961
                peers = append(peers, peer)
3✔
4962
        }
3✔
4963

3✔
4964
        return peers
3✔
4965
}
3✔
4966

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

3✔
4978
        // Using 1/10 of our duration as a margin, compute a random offset to
3✔
4979
        // avoid the nodes entering connection cycles.
3✔
4980
        margin := nextBackoff / 10
3✔
4981

3✔
4982
        var wiggle big.Int
3✔
4983
        wiggle.SetUint64(uint64(margin))
3✔
4984
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4985
                // Randomizing is not mission critical, so we'll just return the
3✔
4986
                // current backoff.
3✔
4987
                return nextBackoff
3✔
4988
        }
3✔
4989

3✔
4990
        // Otherwise add in our wiggle, but subtract out half of the margin so
×
4991
        // that the backoff can tweaked by 1/20 in either direction.
×
4992
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
×
4993
}
×
4994

×
4995
// errNoAdvertisedAddr is an error returned when we attempt to retrieve the
3✔
4996
// advertised address of a node, but they don't have one.
3✔
4997
var errNoAdvertisedAddr = errors.New("no advertised address found")
3✔
4998

3✔
4999
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
3✔
5000
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5001
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5002
        if err != nil {
×
5003
                return nil, err
×
5004
        }
×
5005

×
5006
        node, err := s.graphDB.FetchLightningNode(vertex)
×
5007
        if err != nil {
×
5008
                return nil, err
5009
        }
5010

5011
        if len(node.Addresses) == 0 {
5012
                return nil, errNoAdvertisedAddr
5013
        }
5014

3✔
5015
        return node.Addresses, nil
×
5016
}
×
5017

×
5018
// fetchLastChanUpdate returns a function which is able to retrieve our latest
×
5019
// channel update for a target channel.
×
5020
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5021
        *lnwire.ChannelUpdate1, error) {
5022

5023
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
5024
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
5025
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5026
                if err != nil {
3✔
5027
                        return nil, err
3✔
5028
                }
5029

5030
                return netann.ExtractChannelUpdate(
5031
                        ourPubKey[:], info, edge1, edge2,
5032
                )
5033
        }
3✔
5034
}
3✔
5035

3✔
5036
// applyChannelUpdate applies the channel update to the different sub-systems of
3✔
5037
// the server. The useAlias boolean denotes whether or not to send an alias in
3✔
5038
// place of the real SCID.
6✔
5039
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
3✔
5040
        op *wire.OutPoint, useAlias bool) error {
3✔
5041

5042
        var (
3✔
5043
                peerAlias    *lnwire.ShortChannelID
5044
                defaultAlias lnwire.ShortChannelID
5045
        )
5046

5047
        chanID := lnwire.NewChanIDFromOutPoint(*op)
5048

5049
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5050
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5051
        if useAlias {
3✔
5052
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
6✔
5053
                if foundAlias != defaultAlias {
3✔
5054
                        peerAlias = &foundAlias
3✔
5055
                }
5056
        }
5057

5058
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5059
                update, discovery.RemoteAlias(peerAlias),
3✔
5060
        )
3✔
5061
        select {
3✔
5062
        case err := <-errChan:
3✔
5063
                return err
×
5064
        case <-s.quit:
×
5065
                return ErrServerShuttingDown
×
5066
        }
×
5067
}
5068

5069
// SendCustomMessage sends a custom message to the peer with the specified
5070
// pubkey.
3✔
5071
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5072
        data []byte) error {
5073

5074
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
5075
        if err != nil {
5076
                return err
5077
        }
5078

3✔
5079
        // We'll wait until the peer is active.
3✔
5080
        select {
3✔
5081
        case <-peer.ActiveSignal():
×
5082
        case <-peer.QuitSignal():
×
5083
                return fmt.Errorf("peer %x disconnected", peerPub)
5084
        case <-s.quit:
3✔
5085
                return ErrServerShuttingDown
6✔
5086
        }
3✔
5087

3✔
5088
        msg, err := lnwire.NewCustom(msgType, data)
5089
        if err != nil {
6✔
5090
                return err
3✔
5091
        }
3✔
5092

5093
        // Send the message as low-priority. For now we assume that all
3✔
5094
        // application-defined message are low priority.
5095
        return peer.SendMessageLazy(true, msg)
5096
}
5097

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

3✔
5106
        return func() fn.Result[lnwallet.AddrWithKey] {
3✔
5107
                sweepAddr, err := wallet.NewAddress(
5108
                        lnwallet.TaprootPubkey, false,
3✔
5109
                        lnwallet.DefaultAccountName,
3✔
5110
                )
3✔
5111
                if err != nil {
5112
                        return fn.Err[lnwallet.AddrWithKey](err)
5113
                }
5114

5115
                addr, err := txscript.PayToAddrScript(sweepAddr)
5116
                if err != nil {
5117
                        return fn.Err[lnwallet.AddrWithKey](err)
5118
                }
3✔
5119

3✔
5120
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5121
                        wallet, netParams, addr,
3✔
5122
                )
3✔
5123
                if err != nil {
3✔
5124
                        return fn.Err[lnwallet.AddrWithKey](err)
3✔
5125
                }
3✔
5126

3✔
5127
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5128
                        DeliveryAddress: addr,
3✔
5129
                        InternalKey:     internalKeyDesc,
6✔
5130
                })
3✔
5131
        }
6✔
5132
}
3✔
5133

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

×
5143
        // TODO(yy): remove the check on simnet/regtest such that the itest is
×
5144
        // covering the bootstrapping process.
5145
        return !cfg.NoNetBootstrap && !isDevNetwork
5146
}
5147

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

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

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

5181
        for _, c := range pendings {
5182
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
3✔
5183
                        continue
3✔
5184
                }
6✔
5185

3✔
5186
                // If the channel is still reported as pending, remove it from
3✔
5187
                // the map.
3✔
5188
                delete(closedSCIDs, c.ShortChannelID)
3✔
5189

3✔
5190
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5191
                        c.ShortChannelID)
×
5192
        }
5193

3✔
5194
        return closedSCIDs
3✔
5195
}
×
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