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

lightningnetwork / lnd / 12375116696

17 Dec 2024 02:29PM UTC coverage: 58.366% (-0.2%) from 58.595%
12375116696

Pull #8777

github

ziggie1984
docs: add release-notes
Pull Request #8777: multi: make deletion of edge atomic.

132 of 177 new or added lines in 6 files covered. (74.58%)

670 existing lines in 37 files now uncovered.

133926 of 229458 relevant lines covered (58.37%)

19223.6 hits per line

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

63.64
/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 {
1✔
155
        return fmt.Sprintf("already connected to peer: %v", e.peer)
1✔
156
}
1✔
157

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 {
1✔
367
        graphSub, err := s.graphBuilder.SubscribeTopology()
1✔
368
        if err != nil {
1✔
369
                return err
×
370
        }
×
371

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

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

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

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

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

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

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

419
                                        s.mu.Lock()
1✔
420

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

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

435
                                        s.mu.Unlock()
1✔
436

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

443
        return nil
1✔
444
}
445

446
// CustomMessage is a custom message that is received from a peer.
447
type CustomMessage struct {
448
        // Peer is the peer pubkey
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) {
1✔
457
        var (
1✔
458
                host string
1✔
459
                port int
1✔
460
        )
1✔
461

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

479
        if tor.IsOnionHost(host) {
1✔
480
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
481
        }
×
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
485
        // addresses over Tor in order to prevent leaking your real IP
486
        // address.
487
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
1✔
488
        return netCfg.ResolveTCPAddr("tcp", hostPort)
1✔
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.
493
func noiseDial(idKey keychain.SingleKeyECDH,
494
        netCfg tor.Net, timeout time.Duration) func(net.Addr) (net.Conn, error) {
1✔
495

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

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

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

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

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

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

1✔
540
        netParams := cfg.ActiveNetParams.Params
1✔
541

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
634
                listenAddrs: listenAddrs,
1✔
635

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

1✔
640
                torController: torController,
1✔
641

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

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

1✔
658
                invoiceHtlcModifier: invoiceHtlcModifier,
1✔
659

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

1✔
662
                tlsManager: tlsManager,
1✔
663

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

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

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

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

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

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

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

1✔
694
                return nil
1✔
695
        }
696

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

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

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

719
                        peer.HandleLocalCloseChanReqs(request)
1✔
720
                },
721
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
722
                SwitchPackager:         channeldb.NewSwitchPackager(),
723
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
724
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
725
                Notifier:               s.cc.ChainNotifier,
726
                HtlcNotifier:           s.htlcNotifier,
727
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
728
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
729
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
730
                AllowCircularRoute:     cfg.AllowCircularRoute,
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 {
1✔
739
                return nil, err
×
740
        }
×
741
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
1✔
742
                &htlcswitch.InterceptableSwitchConfig{
1✔
743
                        Switch:             s.htlcSwitch,
1✔
744
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
1✔
745
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
1✔
746
                        RequireInterceptor: s.cfg.RequireInterceptor,
1✔
747
                        Notifier:           s.cc.ChainNotifier,
1✔
748
                },
1✔
749
        )
1✔
750
        if err != nil {
1✔
751
                return nil, err
×
752
        }
×
753

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

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

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

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

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

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

×
799
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
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))
1✔
818
        for idx, ip := range cfg.ExternalIPs {
2✔
819
                externalIPStrings[idx] = ip.String()
1✔
820
        }
1✔
821
        if s.natTraversal != nil {
1✔
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",
×
837
                                s.natTraversal.Name(), err)
×
838
                } else {
×
839
                        srvrLog.Infof("Automatically set up port forwarding "+
×
840
                                "using %s to advertise external IP",
×
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(
1✔
849
                externalIPStrings, strconv.Itoa(defaultPeerPort),
1✔
850
                cfg.net.ResolveTCPAddr,
1✔
851
        )
1✔
852
        if err != nil {
1✔
853
                return nil, err
×
854
        }
×
855

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

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

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

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

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

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

929
        // Instantiate mission control with config from the sub server.
930
        //
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)
1✔
934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1100
                        return s.genNodeAnnouncement(nil)
×
1101
                },
×
1102
                ProofMatureDelta:        0,
1103
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1104
                RetransmitTicker:        ticker.New(time.Minute * 30),
1105
                RebroadcastInterval:     time.Hour * 24,
1106
                WaitingProofStore:       waitingProofStore,
1107
                MessageStore:            gossipMessageStore,
1108
                AnnSigner:               s.nodeSigner,
1109
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1110
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1111
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1112
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1113
                MinimumBatchSize:        10,
1114
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1115
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1116
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1117
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
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())
1✔
1129
        //nolint:ll
1✔
1130
        s.localChanMgr = &localchans.Manager{
1✔
1131
                SelfPub:              nodeKeyDesc.PubKey,
1✔
1132
                DefaultRoutingPolicy: cc.RoutingPolicy,
1✔
1133
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
1✔
1134
                        *models.ChannelEdgePolicy) error) error {
2✔
1135

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

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

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

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

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

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

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

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

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

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

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

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

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

1261
                        return addr.DeliveryAddress, nil
×
1262
                },
1263
                PublishTx: cc.Wallet.PublishTransaction,
1264
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
1✔
1265
                        for _, msg := range msgs {
2✔
1266
                                err := s.htlcSwitch.ProcessContractResolution(msg)
1✔
1267
                                if err != nil {
1✔
1268
                                        return err
×
1269
                                }
×
1270
                        }
1271
                        return nil
1✔
1272
                },
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 {
1✔
1278

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

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

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

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

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

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

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

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

1366
                        return &pc.Incoming
1✔
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
1✔
1375
        minRemoteDelay := funding.MinBtcRemoteDelay
1✔
1376
        maxRemoteDelay := funding.MaxBtcRemoteDelay
1✔
1377

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1916
                chainBackendAttempts = 0
×
1917
        }
×
1918

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2066
                checks = append(checks, leaderCheck)
×
2067
        }
2068

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
2517
                close(s.quit)
1✔
2518

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

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

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

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

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

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

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

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

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

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

2660
        return nil
1✔
2661
}
2662

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

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

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

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

2692
        return externalIPs, nil
×
2693
}
2694

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

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

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

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

2730
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2731

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
2852
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2853

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

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

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

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

2882
        return bootStrappers, nil
×
2883
}
2884

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

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

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

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

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

2915
        return ignore
×
2916
}
2917

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

×
2926
        defer s.wg.Done()
×
2927

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

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

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

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

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

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

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

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

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

×
2979
                                sampleTicker.Stop()
×
2980

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3239
        return nil
×
3240
}
3241

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

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

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

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

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

1✔
3267
        return *s.currentNodeAnn
1✔
3268
}
1✔
3269

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

1✔
3276
        s.mu.Lock()
1✔
3277
        defer s.mu.Unlock()
1✔
3278

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

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

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

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

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

3315
        return *s.currentNodeAnn, nil
1✔
3316
}
3317

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

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

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

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

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

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

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

3361
        return nil
1✔
3362
}
3363

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3540
                numOutboundConns++
1✔
3541
        }
3542

3543
        return nil
1✔
3544
}
3545

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

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

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

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

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

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

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

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

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

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

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

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

1✔
3630
        return nil
1✔
3631
}
3632

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

1✔
3640
        s.mu.Lock()
1✔
3641

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

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

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

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

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

3675
                return
1✔
3676
        }
3677

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

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

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

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

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

1✔
3711
        return c
1✔
3712
}
3713

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

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

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

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

1✔
3737
        return s.findPeerByPubStr(pubStr)
1✔
3738
}
1✔
3739

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

3748
        return peer, nil
1✔
3749
}
3750

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

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

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

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

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

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

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

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

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

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

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

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

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

×
3840
                return
×
3841
        }
×
3842

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

×
3847
                conn.Close()
×
3848

×
3849
                return
×
3850
        }
×
3851

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

1✔
3859
                conn.Close()
1✔
3860
                return
1✔
3861
        }
1✔
3862

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

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

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

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

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

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

×
3910
                s.cancelConnReqs(pubStr, nil)
×
3911

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

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

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

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

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

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

×
3950
                return
×
3951
        }
×
3952

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

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

3961
                conn.Close()
×
3962

×
3963
                return
×
3964
        }
3965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4108
                s.connMgr.Remove(connID)
1✔
4109
        }
4110

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4230
                PongBuf: s.pongBuf,
4231

4232
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4233

4234
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4235

4236
                FundingManager: s.fundingMgr,
4237

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

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

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

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

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

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

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

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

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

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

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

×
4310
                return
×
4311
        }
×
4312

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

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

1✔
4322
        s.peersByPub[pubStr] = p
1✔
4323

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

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

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

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

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

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

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

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

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

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

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

1✔
4386
        s.mu.Lock()
1✔
4387
        defer s.mu.Unlock()
1✔
4388

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

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

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

1✔
4419
        p.WaitForDisconnect(ready)
1✔
4420

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

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

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

1✔
4436
        pubKey := p.IdentityKey()
1✔
4437

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

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

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

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

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

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

×
4473
                pubKey := p.PubKey()
×
4474
                pubStr := string(pubKey[:])
×
4475

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4653
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
1✔
4654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4844
        close(errChan)
1✔
4845

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

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

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

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

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

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

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

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

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

1✔
4885
        return nil
1✔
4886
}
4887

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

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

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

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

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

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

×
4935
                return req.Updates, req.Err
×
4936
        }
×
4937

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

1✔
4944
        return req.Updates, req.Err
1✔
4945
}
4946

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

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

4959
        return peers
1✔
4960
}
4961

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

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

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

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

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

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

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

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

5010
        return node.Addresses, nil
1✔
5011
}
5012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

© 2025 Coveralls, Inc