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

lightningnetwork / lnd / 12412879685

19 Dec 2024 12:40PM UTC coverage: 58.744% (+0.09%) from 58.653%
12412879685

Pull #8754

github

ViktorTigerstrom
itest: wrap deriveCustomScopeAccounts at 80 chars

This commit fixes that word wrapping for the deriveCustomScopeAccounts
function docs, and ensures that it wraps at 80 characters or less.
Pull Request #8754: Add `Outbound` Remote Signer implementation

1858 of 2816 new or added lines in 47 files covered. (65.98%)

267 existing lines in 51 files now uncovered.

136038 of 231578 relevant lines covered (58.74%)

19020.65 hits per line

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

63.45
/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 {
3✔
155
        return fmt.Sprintf("already connected to peer: %v", e.peer)
3✔
156
}
3✔
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
        remoteSignerClient rpcwallet.RemoteSignerClient
328

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

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

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

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

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

351
        hostAnn *netann.HostAnnouncer
352

353
        // livenessMonitor monitors that lnd has access to critical resources.
354
        livenessMonitor *healthcheck.Monitor
355

356
        customMessageServer *subscribe.Server
357

358
        // txPublisher is a publisher with fee-bumping capability.
359
        txPublisher *sweep.TxPublisher
360

361
        quit chan struct{}
362

363
        wg sync.WaitGroup
364
}
365

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

374
        s.wg.Add(1)
3✔
375
        go func() {
6✔
376
                defer func() {
6✔
377
                        graphSub.Cancel()
3✔
378
                        s.wg.Done()
3✔
379
                }()
3✔
380

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

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

393
                                for _, update := range topChange.NodeUpdates {
6✔
394
                                        pubKeyStr := string(
3✔
395
                                                update.IdentityKey.
3✔
396
                                                        SerializeCompressed(),
3✔
397
                                        )
3✔
398

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

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

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

421
                                        s.mu.Lock()
3✔
422

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

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

437
                                        s.mu.Unlock()
3✔
438

3✔
439
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
440
                                }
441
                        }
442
                }
443
        }()
444

445
        return nil
3✔
446
}
447

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

453
        // Msg is the custom wire message.
454
        Msg *lnwire.Custom
455
}
456

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

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

481
        if tor.IsOnionHost(host) {
3✔
482
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
483
        }
×
484

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

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

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

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

3✔
515
        var (
3✔
516
                err         error
3✔
517
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
518

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

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

539
        var serializedPubKey [33]byte
3✔
540
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
541

3✔
542
        netParams := cfg.ActiveNetParams.Params
3✔
543

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

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

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

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

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

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

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

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

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

3✔
612
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
613

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

3✔
628
                channelNotifier: channelnotifier.New(
3✔
629
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
630
                ),
3✔
631

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

3✔
636
                listenAddrs: listenAddrs,
3✔
637

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

3✔
642
                torController: torController,
3✔
643

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

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

3✔
660
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
661

3✔
662
                customMessageServer: subscribe.NewServer(),
3✔
663

3✔
664
                tlsManager: tlsManager,
3✔
665

3✔
666
                remoteSignerClient: remoteSignerClient,
3✔
667

3✔
668
                featureMgr: featureMgr,
3✔
669
                quit:       make(chan struct{}),
3✔
670
        }
3✔
671

3✔
672
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
673
        if err != nil {
3✔
674
                return nil, err
×
675
        }
×
676

677
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
678
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
679
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
680
        )
3✔
681
        s.invoices = invoices.NewRegistry(
3✔
682
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
683
        )
3✔
684

3✔
685
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
686

3✔
687
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
688
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
689

3✔
690
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
691
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
692
                if err != nil {
3✔
693
                        return err
×
694
                }
×
695

696
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
697

3✔
698
                return nil
3✔
699
        }
700

701
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
702
        if err != nil {
3✔
703
                return nil, err
×
704
        }
×
705

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

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

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

758
        s.witnessBeacon = newPreimageBeacon(
3✔
759
                dbs.ChanStateDB.NewWitnessCache(),
3✔
760
                s.interceptableSwitch.ForwardPacket,
3✔
761
        )
3✔
762

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

3✔
776
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
777
        if err != nil {
3✔
778
                return nil, err
×
779
        }
×
780
        s.chanStatusMgr = chanStatusMgr
3✔
781

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

×
787
                discoveryTimeout := time.Duration(10 * time.Second)
×
788

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

×
803
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
804
                                "enabled device")
×
805

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

815
                        s.natTraversal = pmp
×
816
                }
817
        }
818

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

×
834
                        listenPorts = append(listenPorts, uint16(port))
×
835
                }
×
836

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

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

860
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
861
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
862

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

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

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

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

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

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

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

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

3✔
954
                        estimator, err = routing.NewAprioriEstimator(
3✔
955
                                aprioriConfig,
3✔
956
                        )
3✔
957
                        if err != nil {
3✔
958
                                return nil, err
×
959
                        }
×
960

961
                case routing.BimodalEstimatorName:
×
962
                        bCfg := routingConfig.BimodalConfig
×
963
                        bimodalConfig := routing.BimodalConfig{
×
964
                                BimodalNodeWeight: bCfg.NodeWeight,
×
965
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
966
                                        bCfg.Scale,
×
967
                                ),
×
968
                                BimodalDecayTime: bCfg.DecayTime,
×
969
                        }
×
970

×
971
                        estimator, err = routing.NewBimodalEstimator(
×
972
                                bimodalConfig,
×
973
                        )
×
974
                        if err != nil {
×
975
                                return nil, err
×
976
                        }
×
977

978
                default:
×
979
                        return nil, fmt.Errorf("unknown estimator type %v",
×
980
                                routingConfig.ProbabilityEstimatorType)
×
981
                }
982
        }
983

984
        mcCfg := &routing.MissionControlConfig{
3✔
985
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
986
                Estimator:               estimator,
3✔
987
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
988
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
989
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
990
        }
3✔
991

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

1007
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1008
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1009
                int64(routingConfig.AttemptCost),
3✔
1010
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1011
                routingConfig.MinRouteProbability)
3✔
1012

3✔
1013
        pathFindingConfig := routing.PathFindingConfig{
3✔
1014
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1015
                        routingConfig.AttemptCost,
3✔
1016
                ),
3✔
1017
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1018
                MinProbability: routingConfig.MinRouteProbability,
3✔
1019
        }
3✔
1020

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

3✔
1035
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1036

3✔
1037
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1038

3✔
1039
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1040
                cfg.Routing.StrictZombiePruning
3✔
1041

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

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

1079
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1080
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1081
        if err != nil {
3✔
1082
                return nil, err
×
1083
        }
×
1084
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1085
        if err != nil {
3✔
1086
                return nil, err
×
1087
        }
×
1088

1089
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1090

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

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

1132
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1133
        //nolint:ll
3✔
1134
        s.localChanMgr = &localchans.Manager{
3✔
1135
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1136
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1137
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1138
                        *models.ChannelEdgePolicy) error) error {
6✔
1139

3✔
1140
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1141
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
3✔
1142
                                        e *models.ChannelEdgePolicy,
3✔
1143
                                        _ *models.ChannelEdgePolicy) error {
6✔
1144

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

1159
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1160
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1161
        )
3✔
1162
        if err != nil {
3✔
1163
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1164
                return nil, err
×
1165
        }
×
1166

1167
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1168
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1169
        )
3✔
1170
        if err != nil {
3✔
1171
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1172
                return nil, err
×
1173
        }
×
1174

1175
        aggregator := sweep.NewBudgetAggregator(
3✔
1176
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1177
                s.implCfg.AuxSweeper,
3✔
1178
        )
3✔
1179

3✔
1180
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1181
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1182
                Wallet:     cc.Wallet,
3✔
1183
                Estimator:  cc.FeeEstimator,
3✔
1184
                Notifier:   cc.ChainNotifier,
3✔
1185
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1186
        })
3✔
1187

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

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

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

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

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

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

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

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

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

3✔
1303
                        // processACK will handle the BreachArbitrator ACKing
3✔
1304
                        // the event.
3✔
1305
                        finalErr := make(chan error, 1)
3✔
1306
                        processACK := func(brarErr error) {
6✔
1307
                                if brarErr != nil {
3✔
1308
                                        finalErr <- brarErr
×
1309
                                        return
×
1310
                                }
×
1311

1312
                                // If the BreachArbitrator successfully handled
1313
                                // the event, we can signal that the handoff
1314
                                // was successful.
1315
                                finalErr <- nil
3✔
1316
                        }
1317

1318
                        event := &contractcourt.ContractBreachEvent{
3✔
1319
                                ChanPoint:         chanPoint,
3✔
1320
                                ProcessACK:        processACK,
3✔
1321
                                BreachRetribution: breachRet,
3✔
1322
                        }
3✔
1323

3✔
1324
                        // Send the contract breach event to the
3✔
1325
                        // BreachArbitrator.
3✔
1326
                        select {
3✔
1327
                        case contractBreaches <- event:
3✔
1328
                        case <-s.quit:
×
1329
                                return ErrServerShuttingDown
×
1330
                        }
1331

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

1357
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1358
                QueryIncomingCircuit: func(
1359
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1360

3✔
1361
                        // Get the circuit map.
3✔
1362
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1363

3✔
1364
                        // Lookup the outgoing circuit.
3✔
1365
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1366
                        if pc == nil {
6✔
1367
                                return nil
3✔
1368
                        }
3✔
1369

1370
                        return &pc.Incoming
3✔
1371
                },
1372
                AuxLeafStore: implCfg.AuxLeafStore,
1373
                AuxSigner:    implCfg.AuxSigner,
1374
                AuxResolver:  implCfg.AuxContractResolver,
1375
        }, dbs.ChanStateDB)
1376

1377
        // Select the configuration and funding parameters for Bitcoin.
1378
        chainCfg := cfg.Bitcoin
3✔
1379
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1380
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1381

3✔
1382
        var chanIDSeed [32]byte
3✔
1383
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1384
                return nil, err
×
1385
        }
×
1386

1387
        // Wrap the DeleteChannelEdges method so that the funding manager can
1388
        // use it without depending on several layers of indirection.
1389
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1390
                *models.ChannelEdgePolicy, error) {
6✔
1391

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

1405
                // Grab our key to find our policy.
1406
                var ourKey [33]byte
3✔
1407
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1408

3✔
1409
                var ourPolicy *models.ChannelEdgePolicy
3✔
1410
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1411
                        ourPolicy = e1
3✔
1412
                } else {
6✔
1413
                        ourPolicy = e2
3✔
1414
                }
3✔
1415

1416
                if ourPolicy == nil {
3✔
1417
                        // Something is wrong, so return an error.
×
1418
                        return nil, fmt.Errorf("we don't have an edge")
×
1419
                }
×
1420

1421
                err = s.graphDB.DeleteChannelEdges(
3✔
1422
                        false, false, scid.ToUint64(),
3✔
1423
                )
3✔
1424
                return ourPolicy, err
3✔
1425
        }
1426

1427
        // For the reservationTimeout and the zombieSweeperInterval different
1428
        // values are set in case we are in a dev environment so enhance test
1429
        // capacilities.
1430
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1431
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1432

3✔
1433
        // Get the development config for funding manager. If we are not in
3✔
1434
        // development mode, this would be nil.
3✔
1435
        var devCfg *funding.DevConfig
3✔
1436
        if lncfg.IsDevBuild() {
6✔
1437
                devCfg = &funding.DevConfig{
3✔
1438
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1439
                }
3✔
1440

3✔
1441
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1442
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1443

3✔
1444
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1445
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1446
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1447
        }
3✔
1448

1449
        //nolint:ll
1450
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1451
                Dev:                devCfg,
3✔
1452
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1453
                IDKey:              nodeKeyDesc.PubKey,
3✔
1454
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1455
                Wallet:             cc.Wallet,
3✔
1456
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1457
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1458
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1459
                },
3✔
1460
                Notifier:     cc.ChainNotifier,
1461
                ChannelDB:    s.chanStateDB,
1462
                FeeEstimator: cc.FeeEstimator,
1463
                SignMessage:  cc.MsgSigner.SignMessage,
1464
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1465
                        error) {
3✔
1466

3✔
1467
                        return s.genNodeAnnouncement(nil)
3✔
1468
                },
3✔
1469
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1470
                NotifyWhenOnline:     s.NotifyWhenOnline,
1471
                TempChanIDSeed:       chanIDSeed,
1472
                FindChannel:          s.findChannel,
1473
                DefaultRoutingPolicy: cc.RoutingPolicy,
1474
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1475
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1476
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1477
                        // For large channels we increase the number
3✔
1478
                        // of confirmations we require for the
3✔
1479
                        // channel to be considered open. As it is
3✔
1480
                        // always the responder that gets to choose
3✔
1481
                        // value, the pushAmt is value being pushed
3✔
1482
                        // to us. This means we have more to lose
3✔
1483
                        // in the case this gets re-orged out, and
3✔
1484
                        // we will require more confirmations before
3✔
1485
                        // we consider it open.
3✔
1486

3✔
1487
                        // In case the user has explicitly specified
3✔
1488
                        // a default value for the number of
3✔
1489
                        // confirmations, we use it.
3✔
1490
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1491
                        if defaultConf != 0 {
6✔
1492
                                return defaultConf
3✔
1493
                        }
3✔
1494

1495
                        minConf := uint64(3)
×
1496
                        maxConf := uint64(6)
×
1497

×
1498
                        // If this is a wumbo channel, then we'll require the
×
1499
                        // max amount of confirmations.
×
1500
                        if chanAmt > MaxFundingAmount {
×
1501
                                return uint16(maxConf)
×
1502
                        }
×
1503

1504
                        // If not we return a value scaled linearly
1505
                        // between 3 and 6, depending on channel size.
1506
                        // TODO(halseth): Use 1 as minimum?
1507
                        maxChannelSize := uint64(
×
1508
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1509
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1510
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1511
                        if conf < minConf {
×
1512
                                conf = minConf
×
1513
                        }
×
1514
                        if conf > maxConf {
×
1515
                                conf = maxConf
×
1516
                        }
×
1517
                        return uint16(conf)
×
1518
                },
1519
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1520
                        // We scale the remote CSV delay (the time the
3✔
1521
                        // remote have to claim funds in case of a unilateral
3✔
1522
                        // close) linearly from minRemoteDelay blocks
3✔
1523
                        // for small channels, to maxRemoteDelay blocks
3✔
1524
                        // for channels of size MaxFundingAmount.
3✔
1525

3✔
1526
                        // In case the user has explicitly specified
3✔
1527
                        // a default value for the remote delay, we
3✔
1528
                        // use it.
3✔
1529
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1530
                        if defaultDelay > 0 {
6✔
1531
                                return defaultDelay
3✔
1532
                        }
3✔
1533

1534
                        // If this is a wumbo channel, then we'll require the
1535
                        // max value.
1536
                        if chanAmt > MaxFundingAmount {
×
1537
                                return maxRemoteDelay
×
1538
                        }
×
1539

1540
                        // If not we scale according to channel size.
1541
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1542
                                chanAmt / MaxFundingAmount)
×
1543
                        if delay < minRemoteDelay {
×
1544
                                delay = minRemoteDelay
×
1545
                        }
×
1546
                        if delay > maxRemoteDelay {
×
1547
                                delay = maxRemoteDelay
×
1548
                        }
×
1549
                        return delay
×
1550
                },
1551
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1552
                        peerKey *btcec.PublicKey) error {
3✔
1553

3✔
1554
                        // First, we'll mark this new peer as a persistent peer
3✔
1555
                        // for re-connection purposes. If the peer is not yet
3✔
1556
                        // tracked or the user hasn't requested it to be perm,
3✔
1557
                        // we'll set false to prevent the server from continuing
3✔
1558
                        // to connect to this peer even if the number of
3✔
1559
                        // channels with this peer is zero.
3✔
1560
                        s.mu.Lock()
3✔
1561
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1562
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1563
                                s.persistentPeers[pubStr] = false
3✔
1564
                        }
3✔
1565
                        s.mu.Unlock()
3✔
1566

3✔
1567
                        // With that taken care of, we'll send this channel to
3✔
1568
                        // the chain arb so it can react to on-chain events.
3✔
1569
                        return s.chainArb.WatchNewChannel(channel)
3✔
1570
                },
1571
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1572
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1573
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1574
                },
3✔
1575
                RequiredRemoteChanReserve: func(chanAmt,
1576
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1577

3✔
1578
                        // By default, we'll require the remote peer to maintain
3✔
1579
                        // at least 1% of the total channel capacity at all
3✔
1580
                        // times. If this value ends up dipping below the dust
3✔
1581
                        // limit, then we'll use the dust limit itself as the
3✔
1582
                        // reserve as required by BOLT #2.
3✔
1583
                        reserve := chanAmt / 100
3✔
1584
                        if reserve < dustLimit {
6✔
1585
                                reserve = dustLimit
3✔
1586
                        }
3✔
1587

1588
                        return reserve
3✔
1589
                },
1590
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1591
                        // By default, we'll allow the remote peer to fully
3✔
1592
                        // utilize the full bandwidth of the channel, minus our
3✔
1593
                        // required reserve.
3✔
1594
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1595
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1596
                },
3✔
1597
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1598
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1599
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1600
                        }
3✔
1601

1602
                        // By default, we'll permit them to utilize the full
1603
                        // channel bandwidth.
1604
                        return uint16(input.MaxHTLCNumber / 2)
×
1605
                },
1606
                ZombieSweeperInterval:         zombieSweeperInterval,
1607
                ReservationTimeout:            reservationTimeout,
1608
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1609
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1610
                MaxPendingChannels:            cfg.MaxPendingChannels,
1611
                RejectPush:                    cfg.RejectPush,
1612
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1613
                NotifyOpenChannelEvent:        s.channelNotifier.NotifyOpenChannelEvent,
1614
                OpenChannelPredicate:          chanPredicate,
1615
                NotifyPendingOpenChannelEvent: s.channelNotifier.NotifyPendingOpenChannelEvent,
1616
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1617
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1618
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1619
                DeleteAliasEdge:      deleteAliasEdge,
1620
                AliasManager:         s.aliasMgr,
1621
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1622
                AuxFundingController: implCfg.AuxFundingController,
1623
                AuxSigner:            implCfg.AuxSigner,
1624
                AuxResolver:          implCfg.AuxContractResolver,
1625
        })
1626
        if err != nil {
3✔
1627
                return nil, err
×
1628
        }
×
1629

1630
        // Next, we'll assemble the sub-system that will maintain an on-disk
1631
        // static backup of the latest channel state.
1632
        chanNotifier := &channelNotifier{
3✔
1633
                chanNotifier: s.channelNotifier,
3✔
1634
                addrs:        s.addrSource,
3✔
1635
        }
3✔
1636
        backupFile := chanbackup.NewMultiFile(cfg.BackupFilePath)
3✔
1637
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1638
                s.chanStateDB, s.addrSource,
3✔
1639
        )
3✔
1640
        if err != nil {
3✔
1641
                return nil, err
×
1642
        }
×
1643
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1644
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1645
        )
3✔
1646
        if err != nil {
3✔
1647
                return nil, err
×
1648
        }
×
1649

1650
        // Assemble a peer notifier which will provide clients with subscriptions
1651
        // to peer online and offline events.
1652
        s.peerNotifier = peernotifier.New()
3✔
1653

3✔
1654
        // Create a channel event store which monitors all open channels.
3✔
1655
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1656
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1657
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1658
                },
3✔
1659
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1660
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1661
                },
3✔
1662
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1663
                Clock:           clock.NewDefaultClock(),
1664
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1665
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1666
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1667
        })
1668

1669
        if cfg.WtClient.Active {
6✔
1670
                policy := wtpolicy.DefaultPolicy()
3✔
1671
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1672

3✔
1673
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1674
                // protocol operations on sat/kw.
3✔
1675
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1676
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1677
                )
3✔
1678

3✔
1679
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1680

3✔
1681
                if err := policy.Validate(); err != nil {
3✔
1682
                        return nil, err
×
1683
                }
×
1684

1685
                // authDial is the wrapper around the btrontide.Dial for the
1686
                // watchtower.
1687
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1688
                        netAddr *lnwire.NetAddress,
3✔
1689
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1690

3✔
1691
                        return brontide.Dial(
3✔
1692
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1693
                        )
3✔
1694
                }
3✔
1695

1696
                // buildBreachRetribution is a call-back that can be used to
1697
                // query the BreachRetribution info and channel type given a
1698
                // channel ID and commitment height.
1699
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1700
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1701
                        channeldb.ChannelType, error) {
6✔
1702

3✔
1703
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1704
                                nil, chanID,
3✔
1705
                        )
3✔
1706
                        if err != nil {
3✔
1707
                                return nil, 0, err
×
1708
                        }
×
1709

1710
                        br, err := lnwallet.NewBreachRetribution(
3✔
1711
                                channel, commitHeight, 0, nil,
3✔
1712
                                implCfg.AuxLeafStore,
3✔
1713
                                implCfg.AuxContractResolver,
3✔
1714
                        )
3✔
1715
                        if err != nil {
3✔
1716
                                return nil, 0, err
×
1717
                        }
×
1718

1719
                        return br, channel.ChanType, nil
3✔
1720
                }
1721

1722
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1723

3✔
1724
                // Copy the policy for legacy channels and set the blob flag
3✔
1725
                // signalling support for anchor channels.
3✔
1726
                anchorPolicy := policy
3✔
1727
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1728

3✔
1729
                // Copy the policy for legacy channels and set the blob flag
3✔
1730
                // signalling support for taproot channels.
3✔
1731
                taprootPolicy := policy
3✔
1732
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1733
                        blob.FlagTaprootChannel,
3✔
1734
                )
3✔
1735

3✔
1736
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1737
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1738
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1739
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1740
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1741
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1742
                                error) {
6✔
1743

3✔
1744
                                return s.channelNotifier.
3✔
1745
                                        SubscribeChannelEvents()
3✔
1746
                        },
3✔
1747
                        Signer: cc.Wallet.Cfg.Signer,
1748
                        NewAddress: func() ([]byte, error) {
3✔
1749
                                addr, err := newSweepPkScriptGen(
3✔
1750
                                        cc.Wallet, netParams,
3✔
1751
                                )().Unpack()
3✔
1752
                                if err != nil {
3✔
1753
                                        return nil, err
×
1754
                                }
×
1755

1756
                                return addr.DeliveryAddress, nil
3✔
1757
                        },
1758
                        SecretKeyRing:      s.cc.KeyRing,
1759
                        Dial:               cfg.net.Dial,
1760
                        AuthDial:           authDial,
1761
                        DB:                 dbs.TowerClientDB,
1762
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1763
                        MinBackoff:         10 * time.Second,
1764
                        MaxBackoff:         5 * time.Minute,
1765
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1766
                }, policy, anchorPolicy, taprootPolicy)
1767
                if err != nil {
3✔
1768
                        return nil, err
×
1769
                }
×
1770
        }
1771

1772
        if len(cfg.ExternalHosts) != 0 {
3✔
1773
                advertisedIPs := make(map[string]struct{})
×
1774
                for _, addr := range s.currentNodeAnn.Addresses {
×
1775
                        advertisedIPs[addr.String()] = struct{}{}
×
1776
                }
×
1777

1778
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1779
                        Hosts:         cfg.ExternalHosts,
×
1780
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1781
                        LookupHost: func(host string) (net.Addr, error) {
×
1782
                                return lncfg.ParseAddressString(
×
1783
                                        host, strconv.Itoa(defaultPeerPort),
×
1784
                                        cfg.net.ResolveTCPAddr,
×
1785
                                )
×
1786
                        },
×
1787
                        AdvertisedIPs: advertisedIPs,
1788
                        AnnounceNewIPs: netann.IPAnnouncer(
1789
                                func(modifier ...netann.NodeAnnModifier) (
1790
                                        lnwire.NodeAnnouncement, error) {
×
1791

×
1792
                                        return s.genNodeAnnouncement(
×
1793
                                                nil, modifier...,
×
1794
                                        )
×
1795
                                }),
×
1796
                })
1797
        }
1798

1799
        // Create liveness monitor.
1800
        err = s.createLivenessMonitor(
3✔
1801
                context.Background(), cfg, cc, leaderElector,
3✔
1802
        )
3✔
1803
        if err != nil {
3✔
NEW
1804
                return nil, err
×
NEW
1805
        }
×
1806

1807
        // Create the connection manager which will be responsible for
1808
        // maintaining persistent outbound connections and also accepting new
1809
        // incoming connections
1810
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1811
                Listeners:      listeners,
3✔
1812
                OnAccept:       s.InboundPeerConnected,
3✔
1813
                RetryDuration:  time.Second * 5,
3✔
1814
                TargetOutbound: 100,
3✔
1815
                Dial: noiseDial(
3✔
1816
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1817
                ),
3✔
1818
                OnConnection: s.OutboundPeerConnected,
3✔
1819
        })
3✔
1820
        if err != nil {
3✔
1821
                return nil, err
×
1822
        }
×
1823
        s.connMgr = cmgr
3✔
1824

3✔
1825
        return s, nil
3✔
1826
}
1827

1828
// UpdateRoutingConfig is a callback function to update the routing config
1829
// values in the main cfg.
1830
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1831
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1832

3✔
1833
        switch c := cfg.Estimator.Config().(type) {
3✔
1834
        case routing.AprioriConfig:
3✔
1835
                routerCfg.ProbabilityEstimatorType =
3✔
1836
                        routing.AprioriEstimatorName
3✔
1837

3✔
1838
                targetCfg := routerCfg.AprioriConfig
3✔
1839
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1840
                targetCfg.Weight = c.AprioriWeight
3✔
1841
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1842
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1843

1844
        case routing.BimodalConfig:
3✔
1845
                routerCfg.ProbabilityEstimatorType =
3✔
1846
                        routing.BimodalEstimatorName
3✔
1847

3✔
1848
                targetCfg := routerCfg.BimodalConfig
3✔
1849
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1850
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1851
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1852
        }
1853

1854
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1855
}
1856

1857
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1858
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1859
// may differ from what is on disk.
1860
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1861
        error) {
3✔
1862

3✔
1863
        data, err := u.DataToSign()
3✔
1864
        if err != nil {
3✔
1865
                return nil, err
×
1866
        }
×
1867

1868
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1869
}
1870

1871
// createLivenessMonitor creates a set of health checks using our configured
1872
// values and uses these checks to create a liveness monitor. Available
1873
// health checks,
1874
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1875
//   - diskCheck
1876
//   - tlsHealthCheck
1877
//   - torController, only created when tor is enabled.
1878
//
1879
// If a health check has been disabled by setting attempts to 0, our monitor
1880
// will not run it.
1881
func (s *server) createLivenessMonitor(ctx context.Context, cfg *Config,
1882
        cc *chainreg.ChainControl, leaderElector cluster.LeaderElector) error {
3✔
1883

3✔
1884
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
1885
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
1886
                srvrLog.Info("Disabling chain backend checks for " +
×
1887
                        "nochainbackend mode")
×
1888

×
1889
                chainBackendAttempts = 0
×
1890
        }
×
1891

1892
        chainHealthCheck := healthcheck.NewObservation(
3✔
1893
                "chain backend",
3✔
1894
                cc.HealthCheck,
3✔
1895
                cfg.HealthChecks.ChainCheck.Interval,
3✔
1896
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
1897
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
1898
                chainBackendAttempts,
3✔
1899
        )
3✔
1900

3✔
1901
        diskCheck := healthcheck.NewObservation(
3✔
1902
                "disk space",
3✔
1903
                func() error {
3✔
1904
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
1905
                                cfg.LndDir,
×
1906
                        )
×
1907
                        if err != nil {
×
1908
                                return err
×
1909
                        }
×
1910

1911
                        // If we have more free space than we require,
1912
                        // we return a nil error.
1913
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
1914
                                return nil
×
1915
                        }
×
1916

1917
                        return fmt.Errorf("require: %v free space, got: %v",
×
1918
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
1919
                                free)
×
1920
                },
1921
                cfg.HealthChecks.DiskCheck.Interval,
1922
                cfg.HealthChecks.DiskCheck.Timeout,
1923
                cfg.HealthChecks.DiskCheck.Backoff,
1924
                cfg.HealthChecks.DiskCheck.Attempts,
1925
        )
1926

1927
        tlsHealthCheck := healthcheck.NewObservation(
3✔
1928
                "tls",
3✔
1929
                func() error {
3✔
1930
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
1931
                                s.cc.KeyRing,
×
1932
                        )
×
1933
                        if err != nil {
×
1934
                                return err
×
1935
                        }
×
1936
                        if expired {
×
1937
                                return fmt.Errorf("TLS certificate is "+
×
1938
                                        "expired as of %v", expTime)
×
1939
                        }
×
1940

1941
                        // If the certificate is not outdated, no error needs
1942
                        // to be returned
1943
                        return nil
×
1944
                },
1945
                cfg.HealthChecks.TLSCheck.Interval,
1946
                cfg.HealthChecks.TLSCheck.Timeout,
1947
                cfg.HealthChecks.TLSCheck.Backoff,
1948
                cfg.HealthChecks.TLSCheck.Attempts,
1949
        )
1950

1951
        checks := []*healthcheck.Observation{
3✔
1952
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
1953
        }
3✔
1954

3✔
1955
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
1956
        if s.torController != nil {
3✔
1957
                torConnectionCheck := healthcheck.NewObservation(
×
1958
                        "tor connection",
×
1959
                        func() error {
×
1960
                                return healthcheck.CheckTorServiceStatus(
×
1961
                                        s.torController,
×
1962
                                        s.createNewHiddenService,
×
1963
                                )
×
1964
                        },
×
1965
                        cfg.HealthChecks.TorConnection.Interval,
1966
                        cfg.HealthChecks.TorConnection.Timeout,
1967
                        cfg.HealthChecks.TorConnection.Backoff,
1968
                        cfg.HealthChecks.TorConnection.Attempts,
1969
                )
1970
                checks = append(checks, torConnectionCheck)
×
1971
        }
1972

1973
        // If remote signing is enabled, add the healthcheck for the remote
1974
        // signing RPC interface.
1975
        if s.cfg.RemoteSigner.Enable {
6✔
1976
                rpckKeyRing, ok := cc.Wc.(*rpcwallet.RPCKeyRing)
3✔
1977
                if !ok {
3✔
NEW
1978
                        return errors.New("incorrect WalletController type, " +
×
NEW
1979
                                "expected *rpcwallet.RPCKeyRing")
×
NEW
1980
                }
×
1981

1982
                innerTimeout := cfg.HealthChecks.RemoteSigner.Timeout
3✔
1983

3✔
1984
                // Because we have two cascading timeouts here, we need to add
3✔
1985
                // some slack to the "outer" one of them in case the "inner"
3✔
1986
                // returns exactly on time.
3✔
1987
                outerTimeout := innerTimeout + time.Millisecond*10
3✔
1988

3✔
1989
                rsConnectionCheck := healthcheck.NewObservation(
3✔
1990
                        "remote signer connection",
3✔
1991
                        rpcwallet.HealthCheck(
3✔
1992
                                ctx,
3✔
1993
                                rpckKeyRing.RemoteSignerConnection(),
3✔
1994
                                // For the health check we might to be even
3✔
1995
                                // stricter than the initial/normal connect, so
3✔
1996
                                // we use the health check timeout.
3✔
1997
                                innerTimeout,
3✔
1998
                        ),
3✔
1999
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2000
                        outerTimeout,
3✔
2001
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2002
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2003
                )
3✔
2004
                checks = append(checks, rsConnectionCheck)
3✔
2005
        }
2006

2007
        // If we have a leader elector, we add a health check to ensure we are
2008
        // still the leader. During normal operation, we should always be the
2009
        // leader, but there are circumstances where this may change, such as
2010
        // when we lose network connectivity for long enough expiring out lease.
2011
        if leaderElector != nil {
3✔
2012
                leaderCheck := healthcheck.NewObservation(
×
2013
                        "leader status",
×
2014
                        func() error {
×
2015
                                // Check if we are still the leader. Note that
×
2016
                                // we don't need to use a timeout context here
×
2017
                                // as the healthcheck observer will handle the
×
2018
                                // timeout case for us.
×
2019
                                timeoutCtx, cancel := context.WithTimeout(
×
NEW
2020
                                        ctx,
×
2021
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2022
                                )
×
2023
                                defer cancel()
×
2024

×
2025
                                leader, err := leaderElector.IsLeader(
×
2026
                                        timeoutCtx,
×
2027
                                )
×
2028
                                if err != nil {
×
2029
                                        return fmt.Errorf("unable to check if "+
×
2030
                                                "still leader: %v", err)
×
2031
                                }
×
2032

2033
                                if !leader {
×
2034
                                        srvrLog.Debug("Not the current leader")
×
2035
                                        return fmt.Errorf("not the current " +
×
2036
                                                "leader")
×
2037
                                }
×
2038

2039
                                return nil
×
2040
                        },
2041
                        cfg.HealthChecks.LeaderCheck.Interval,
2042
                        cfg.HealthChecks.LeaderCheck.Timeout,
2043
                        cfg.HealthChecks.LeaderCheck.Backoff,
2044
                        cfg.HealthChecks.LeaderCheck.Attempts,
2045
                )
2046

2047
                checks = append(checks, leaderCheck)
×
2048
        }
2049

2050
        // If we have not disabled all of our health checks, we create a
2051
        // liveness monitor with our configured checks.
2052
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2053
                &healthcheck.Config{
3✔
2054
                        Checks:   checks,
3✔
2055
                        Shutdown: srvrLog.Criticalf,
3✔
2056
                },
3✔
2057
        )
3✔
2058

3✔
2059
        return nil
3✔
2060
}
2061

2062
// Started returns true if the server has been started, and false otherwise.
2063
// NOTE: This function is safe for concurrent access.
2064
func (s *server) Started() bool {
3✔
2065
        return atomic.LoadInt32(&s.active) != 0
3✔
2066
}
3✔
2067

2068
// cleaner is used to aggregate "cleanup" functions during an operation that
2069
// starts several subsystems. In case one of the subsystem fails to start
2070
// and a proper resource cleanup is required, the "run" method achieves this
2071
// by running all these added "cleanup" functions.
2072
type cleaner []func() error
2073

2074
// add is used to add a cleanup function to be called when
2075
// the run function is executed.
2076
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2077
        return append(c, cleanup)
3✔
2078
}
3✔
2079

2080
// run is used to run all the previousely added cleanup functions.
2081
func (c cleaner) run() {
×
2082
        for i := len(c) - 1; i >= 0; i-- {
×
2083
                if err := c[i](); err != nil {
×
2084
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2085
                }
×
2086
        }
2087
}
2088

2089
// Start starts the main daemon server, all requested listeners, and any helper
2090
// goroutines.
2091
// NOTE: This function is safe for concurrent access.
2092
//
2093
//nolint:funlen
2094
func (s *server) Start() error {
3✔
2095
        var startErr error
3✔
2096

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

3✔
2102
        s.start.Do(func() {
6✔
2103
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2104
                if err := s.customMessageServer.Start(); err != nil {
3✔
2105
                        startErr = err
×
2106
                        return
×
2107
                }
×
2108

2109
                if s.hostAnn != nil {
3✔
2110
                        cleanup = cleanup.add(s.hostAnn.Stop)
×
2111
                        if err := s.hostAnn.Start(); err != nil {
×
2112
                                startErr = err
×
2113
                                return
×
2114
                        }
×
2115
                }
2116

2117
                if s.livenessMonitor != nil {
6✔
2118
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2119
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2120
                                startErr = err
×
2121
                                return
×
2122
                        }
×
2123
                }
2124

2125
                ctx := context.TODO()
3✔
2126

3✔
2127
                cleanup = cleanup.add(s.remoteSignerClient.Stop)
3✔
2128
                if err := s.remoteSignerClient.Start(ctx); err != nil {
3✔
NEW
2129
                        startErr = err
×
NEW
2130
                        return
×
NEW
2131
                }
×
2132

2133
                // Start the notification server. This is used so channel
2134
                // management goroutines can be notified when a funding
2135
                // transaction reaches a sufficient number of confirmations, or
2136
                // when the input for the funding transaction is spent in an
2137
                // attempt at an uncooperative close by the counterparty.
2138
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2139
                if err := s.sigPool.Start(); err != nil {
3✔
2140
                        startErr = err
×
2141
                        return
×
2142
                }
×
2143

2144
                cleanup = cleanup.add(s.writePool.Stop)
3✔
2145
                if err := s.writePool.Start(); err != nil {
3✔
2146
                        startErr = err
×
2147
                        return
×
2148
                }
×
2149

2150
                cleanup = cleanup.add(s.readPool.Stop)
3✔
2151
                if err := s.readPool.Start(); err != nil {
3✔
2152
                        startErr = err
×
2153
                        return
×
2154
                }
×
2155

2156
                cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2157
                if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2158
                        startErr = err
×
2159
                        return
×
2160
                }
×
2161

2162
                cleanup = cleanup.add(s.cc.BestBlockTracker.Stop)
3✔
2163
                if err := s.cc.BestBlockTracker.Start(); err != nil {
3✔
2164
                        startErr = err
×
2165
                        return
×
2166
                }
×
2167

2168
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2169
                if err := s.channelNotifier.Start(); err != nil {
3✔
2170
                        startErr = err
×
2171
                        return
×
2172
                }
×
2173

2174
                cleanup = cleanup.add(func() error {
3✔
2175
                        return s.peerNotifier.Stop()
×
2176
                })
×
2177
                if err := s.peerNotifier.Start(); err != nil {
3✔
2178
                        startErr = err
×
2179
                        return
×
2180
                }
×
2181

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

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

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

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

2208
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2209
                if err := s.utxoNursery.Start(); err != nil {
3✔
2210
                        startErr = err
×
2211
                        return
×
2212
                }
×
2213

2214
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2215
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2216
                        startErr = err
×
2217
                        return
×
2218
                }
×
2219

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

2226
                // htlcSwitch must be started before chainArb since the latter
2227
                // relies on htlcSwitch to deliver resolution message upon
2228
                // start.
2229
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2230
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2231
                        startErr = err
×
2232
                        return
×
2233
                }
×
2234

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

2241
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2242
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
2243
                        startErr = err
×
2244
                        return
×
2245
                }
×
2246

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

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

2259
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2260
                if err := s.chanRouter.Start(); err != nil {
3✔
2261
                        startErr = err
×
2262
                        return
×
2263
                }
×
2264
                // The authGossiper depends on the chanRouter and therefore
2265
                // should be started after it.
2266
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2267
                if err := s.authGossiper.Start(); err != nil {
3✔
2268
                        startErr = err
×
2269
                        return
×
2270
                }
×
2271

2272
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2273
                if err := s.invoices.Start(); err != nil {
3✔
2274
                        startErr = err
×
2275
                        return
×
2276
                }
×
2277

2278
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2279
                if err := s.sphinx.Start(); err != nil {
3✔
2280
                        startErr = err
×
2281
                        return
×
2282
                }
×
2283

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

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

2296
                cleanup.add(func() error {
3✔
2297
                        s.missionController.StopStoreTickers()
×
2298
                        return nil
×
2299
                })
×
2300
                s.missionController.RunStoreTickers()
3✔
2301

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

2334
                // chanSubSwapper must be started after the `channelNotifier`
2335
                // because it depends on channel events as a synchronization
2336
                // point.
2337
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2338
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2339
                        startErr = err
×
2340
                        return
×
2341
                }
×
2342

2343
                if s.torController != nil {
3✔
2344
                        cleanup = cleanup.add(s.torController.Stop)
×
2345
                        if err := s.createNewHiddenService(); err != nil {
×
2346
                                startErr = err
×
2347
                                return
×
2348
                        }
×
2349
                }
2350

2351
                if s.natTraversal != nil {
3✔
2352
                        s.wg.Add(1)
×
2353
                        go s.watchExternalIP()
×
2354
                }
×
2355

2356
                // Start connmgr last to prevent connections before init.
2357
                cleanup = cleanup.add(func() error {
3✔
2358
                        s.connMgr.Stop()
×
2359
                        return nil
×
2360
                })
×
2361
                s.connMgr.Start()
3✔
2362

3✔
2363
                // If peers are specified as a config option, we'll add those
3✔
2364
                // peers first.
3✔
2365
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2366
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2367
                                peerAddrCfg,
3✔
2368
                        )
3✔
2369
                        if err != nil {
3✔
2370
                                startErr = fmt.Errorf("unable to parse peer "+
×
2371
                                        "pubkey from config: %v", err)
×
2372
                                return
×
2373
                        }
×
2374
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2375
                        if err != nil {
3✔
2376
                                startErr = fmt.Errorf("unable to parse peer "+
×
2377
                                        "address provided as a config option: "+
×
2378
                                        "%v", err)
×
2379
                                return
×
2380
                        }
×
2381

2382
                        peerAddr := &lnwire.NetAddress{
3✔
2383
                                IdentityKey: parsedPubkey,
3✔
2384
                                Address:     addr,
3✔
2385
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2386
                        }
3✔
2387

3✔
2388
                        err = s.ConnectToPeer(
3✔
2389
                                peerAddr, true,
3✔
2390
                                s.cfg.ConnectionTimeout,
3✔
2391
                        )
3✔
2392
                        if err != nil {
3✔
2393
                                startErr = fmt.Errorf("unable to connect to "+
×
2394
                                        "peer address provided as a config "+
×
2395
                                        "option: %v", err)
×
2396
                                return
×
2397
                        }
×
2398
                }
2399

2400
                // Subscribe to NodeAnnouncements that advertise new addresses
2401
                // our persistent peers.
2402
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2403
                        startErr = err
×
2404
                        return
×
2405
                }
×
2406

2407
                // With all the relevant sub-systems started, we'll now attempt
2408
                // to establish persistent connections to our direct channel
2409
                // collaborators within the network. Before doing so however,
2410
                // we'll prune our set of link nodes found within the database
2411
                // to ensure we don't reconnect to any nodes we no longer have
2412
                // open channels with.
2413
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2414
                        startErr = err
×
2415
                        return
×
2416
                }
×
2417
                if err := s.establishPersistentConnections(); err != nil {
3✔
2418
                        startErr = err
×
2419
                        return
×
2420
                }
×
2421

2422
                // setSeedList is a helper function that turns multiple DNS seed
2423
                // server tuples from the command line or config file into the
2424
                // data structure we need and does a basic formal sanity check
2425
                // in the process.
2426
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2427
                        if len(tuples) == 0 {
×
2428
                                return
×
2429
                        }
×
2430

2431
                        result := make([][2]string, len(tuples))
×
2432
                        for idx, tuple := range tuples {
×
2433
                                tuple = strings.TrimSpace(tuple)
×
2434
                                if len(tuple) == 0 {
×
2435
                                        return
×
2436
                                }
×
2437

2438
                                servers := strings.Split(tuple, ",")
×
2439
                                if len(servers) > 2 || len(servers) == 0 {
×
2440
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2441
                                                "seed tuple: %v", servers)
×
2442
                                        return
×
2443
                                }
×
2444

2445
                                copy(result[idx][:], servers)
×
2446
                        }
2447

2448
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2449
                }
2450

2451
                // Let users overwrite the DNS seed nodes. We only allow them
2452
                // for bitcoin mainnet/testnet/signet.
2453
                if s.cfg.Bitcoin.MainNet {
3✔
2454
                        setSeedList(
×
2455
                                s.cfg.Bitcoin.DNSSeeds,
×
2456
                                chainreg.BitcoinMainnetGenesis,
×
2457
                        )
×
2458
                }
×
2459
                if s.cfg.Bitcoin.TestNet3 {
3✔
2460
                        setSeedList(
×
2461
                                s.cfg.Bitcoin.DNSSeeds,
×
2462
                                chainreg.BitcoinTestnetGenesis,
×
2463
                        )
×
2464
                }
×
2465
                if s.cfg.Bitcoin.SigNet {
3✔
2466
                        setSeedList(
×
2467
                                s.cfg.Bitcoin.DNSSeeds,
×
2468
                                chainreg.BitcoinSignetGenesis,
×
2469
                        )
×
2470
                }
×
2471

2472
                // If network bootstrapping hasn't been disabled, then we'll
2473
                // configure the set of active bootstrappers, and launch a
2474
                // dedicated goroutine to maintain a set of persistent
2475
                // connections.
2476
                if shouldPeerBootstrap(s.cfg) {
3✔
2477
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2478
                        if err != nil {
×
2479
                                startErr = err
×
2480
                                return
×
2481
                        }
×
2482

2483
                        s.wg.Add(1)
×
2484
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2485
                } else {
3✔
2486
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2487
                }
3✔
2488

2489
                // Set the active flag now that we've completed the full
2490
                // startup.
2491
                atomic.StoreInt32(&s.active, 1)
3✔
2492
        })
2493

2494
        if startErr != nil {
3✔
2495
                cleanup.run()
×
2496
        }
×
2497
        return startErr
3✔
2498
}
2499

2500
// Stop gracefully shutsdown the main daemon server. This function will signal
2501
// any active goroutines, or helper objects to exit, then blocks until they've
2502
// all successfully exited. Additionally, any/all listeners are closed.
2503
// NOTE: This function is safe for concurrent access.
2504
func (s *server) Stop() error {
3✔
2505
        s.stop.Do(func() {
6✔
2506
                atomic.StoreInt32(&s.stopping, 1)
3✔
2507

3✔
2508
                close(s.quit)
3✔
2509

3✔
2510
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2511
                s.connMgr.Stop()
3✔
2512

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

2572
                // Update channel.backup file. Make sure to do it before
2573
                // stopping chanSubSwapper.
2574
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2575
                        s.chanStateDB, s.addrSource,
3✔
2576
                )
3✔
2577
                if err != nil {
3✔
2578
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2579
                                err)
×
2580
                } else {
3✔
2581
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2582
                        if err != nil {
6✔
2583
                                srvrLog.Warnf("Manual update of channel "+
3✔
2584
                                        "backup failed: %v", err)
3✔
2585
                        }
3✔
2586
                }
2587

2588
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2589
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2590
                }
×
2591
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2592
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2593
                }
×
2594
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2595
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2596
                                err)
×
2597
                }
×
2598
                if err := s.remoteSignerClient.Stop(); err != nil {
3✔
NEW
2599
                        srvrLog.Warnf("Unable to stop remote signer "+
×
NEW
2600
                                "client: %v", err)
×
NEW
2601
                }
×
2602
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2603
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2604
                                err)
×
2605
                }
×
2606
                s.missionController.StopStoreTickers()
3✔
2607

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

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

2631
                if s.hostAnn != nil {
3✔
2632
                        if err := s.hostAnn.Stop(); err != nil {
×
2633
                                srvrLog.Warnf("unable to shut down host "+
×
2634
                                        "annoucner: %v", err)
×
2635
                        }
×
2636
                }
2637

2638
                if s.livenessMonitor != nil {
6✔
2639
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2640
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2641
                                        "monitor: %v", err)
×
2642
                        }
×
2643
                }
2644

2645
                // Wait for all lingering goroutines to quit.
2646
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2647
                s.wg.Wait()
3✔
2648

3✔
2649
                srvrLog.Debug("Stopping buffer pools...")
3✔
2650
                s.sigPool.Stop()
3✔
2651
                s.writePool.Stop()
3✔
2652
                s.readPool.Stop()
3✔
2653
        })
2654

2655
        return nil
3✔
2656
}
2657

2658
// Stopped returns true if the server has been instructed to shutdown.
2659
// NOTE: This function is safe for concurrent access.
2660
func (s *server) Stopped() bool {
3✔
2661
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2662
}
3✔
2663

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

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

2683
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2684
                externalIPs = append(externalIPs, hostIP)
×
2685
        }
2686

2687
        return externalIPs, nil
×
2688
}
2689

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

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

×
2714
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2715
        // up by the server.
×
2716
        defer s.removePortForwarding()
×
2717

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

2725
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2726

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

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

2757
                        if ip.Equal(s.lastDetectedIP) {
×
2758
                                continue
×
2759
                        }
2760

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

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

2778
                                newAddrs = append(newAddrs, addr)
×
2779
                        }
2780

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

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

×
2797
                        for _, addr := range currentNodeAnn.Addresses {
×
2798
                                host, _, err := net.SplitHostPort(addr.String())
×
2799
                                if err != nil {
×
2800
                                        srvrLog.Debugf("Unable to determine "+
×
2801
                                                "host from address %v: %v",
×
2802
                                                addr, err)
×
2803
                                        continue
×
2804
                                }
2805

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

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

2826
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2827
                        if err != nil {
×
2828
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2829
                                        "announcement to peers: %v", err)
×
2830
                                continue
×
2831
                        }
2832

2833
                        // Finally, update the last IP seen to the current one.
2834
                        s.lastDetectedIP = ip
×
2835
                case <-s.quit:
×
2836
                        break out
×
2837
                }
2838
        }
2839
}
2840

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

×
2847
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2848

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

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

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

×
2870
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
2871
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
2872
                        )
×
2873
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
2874
                }
×
2875
        }
2876

2877
        return bootStrappers, nil
×
2878
}
2879

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

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

×
2892
        // We should ignore ourselves from bootstrapping.
×
2893
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
2894
        ignore[selfKey] = struct{}{}
×
2895

×
2896
        // Ignore all connected peers.
×
2897
        for _, peer := range s.peersByPub {
×
2898
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
2899
                ignore[nID] = struct{}{}
×
2900
        }
×
2901

2902
        // Ignore all persistent peers as they have a dedicated reconnecting
2903
        // process.
2904
        for pubKeyStr := range s.persistentPeers {
×
2905
                var nID autopilot.NodeID
×
2906
                copy(nID[:], []byte(pubKeyStr))
×
2907
                ignore[nID] = struct{}{}
×
2908
        }
×
2909

2910
        return ignore
×
2911
}
2912

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

×
2921
        defer s.wg.Done()
×
2922

×
2923
        // Before we continue, init the ignore peers map.
×
2924
        ignoreList := s.createBootstrapIgnorePeers()
×
2925

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

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

×
2937
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
2938
        // see if we've reached our minimum number of peers.
×
2939
        sampleTicker := time.NewTicker(backOff)
×
2940
        defer sampleTicker.Stop()
×
2941

×
2942
        // We'll use the number of attempts and errors to determine if we need
×
2943
        // to increase the time between discovery epochs.
×
2944
        var epochErrors uint32 // To be used atomically.
×
2945
        var epochAttempts uint32
×
2946

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

×
2958
                        // If we have enough peers, then we can loop back
×
2959
                        // around to the next round as we're done here.
×
2960
                        if numActivePeers >= numTargetPeers {
×
2961
                                continue
×
2962
                        }
2963

2964
                        // If all of our attempts failed during this last back
2965
                        // off period, then will increase our backoff to 5
2966
                        // minute ceiling to avoid an excessive number of
2967
                        // queries
2968
                        //
2969
                        // TODO(roasbeef): add reverse policy too?
2970

2971
                        if epochAttempts > 0 &&
×
2972
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
2973

×
2974
                                sampleTicker.Stop()
×
2975

×
2976
                                backOff *= 2
×
2977
                                if backOff > bootstrapBackOffCeiling {
×
2978
                                        backOff = bootstrapBackOffCeiling
×
2979
                                }
×
2980

2981
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
2982
                                        "%v", backOff)
×
2983
                                sampleTicker = time.NewTicker(backOff)
×
2984
                                continue
×
2985
                        }
2986

2987
                        atomic.StoreUint32(&epochErrors, 0)
×
2988
                        epochAttempts = 0
×
2989

×
2990
                        // Since we know need more peers, we'll compute the
×
2991
                        // exact number we need to reach our threshold.
×
2992
                        numNeeded := numTargetPeers - numActivePeers
×
2993

×
2994
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
2995
                                "peers", numNeeded)
×
2996

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

×
3005
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3006
                                ignoreList, numNeeded*2, bootstrappers...,
×
3007
                        )
×
3008
                        if err != nil {
×
3009
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3010
                                        "peers: %v", err)
×
3011
                                continue
×
3012
                        }
3013

3014
                        // Finally, we'll launch a new goroutine for each
3015
                        // prospective peer candidates.
3016
                        for _, addr := range peerAddrs {
×
3017
                                epochAttempts++
×
3018

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

3033
                                                srvrLog.Errorf("Unable to "+
×
3034
                                                        "connect to %v: %v",
×
3035
                                                        a, err)
×
3036
                                                atomic.AddUint32(&epochErrors, 1)
×
3037
                                        case <-s.quit:
×
3038
                                        }
3039
                                }(addr)
3040
                        }
3041
                case <-s.quit:
×
3042
                        return
×
3043
                }
3044
        }
3045
}
3046

3047
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3048
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3049
// query back off each time we encounter a failure.
3050
const bootstrapBackOffCeiling = time.Minute * 5
3051

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

×
3059
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3060
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3061

×
3062
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3063
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3064
        var delaySignal <-chan time.Time
×
3065
        delayTime := time.Second * 2
×
3066

×
3067
        // As want to be more aggressive, we'll use a lower back off celling
×
3068
        // then the main peer bootstrap logic.
×
3069
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3070

×
3071
        for attempts := 0; ; attempts++ {
×
3072
                // Check if the server has been requested to shut down in order
×
3073
                // to prevent blocking.
×
3074
                if s.Stopped() {
×
3075
                        return
×
3076
                }
×
3077

3078
                // We can exit our aggressive initial peer bootstrapping stage
3079
                // if we've reached out target number of peers.
3080
                s.mu.RLock()
×
3081
                numActivePeers := uint32(len(s.peersByPub))
×
3082
                s.mu.RUnlock()
×
3083

×
3084
                if numActivePeers >= numTargetPeers {
×
3085
                        return
×
3086
                }
×
3087

3088
                if attempts > 0 {
×
3089
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3090
                                "bootstrap peers (attempt #%v)", delayTime,
×
3091
                                attempts)
×
3092

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

3103
                        // After our delay, we'll double the time we wait up to
3104
                        // the max back off period.
3105
                        delayTime *= 2
×
3106
                        if delayTime > backOffCeiling {
×
3107
                                delayTime = backOffCeiling
×
3108
                        }
×
3109
                }
3110

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

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

×
3131
                                errChan := make(chan error, 1)
×
3132
                                go s.connectToPeer(
×
3133
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3134
                                )
×
3135

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

3159
                wg.Wait()
×
3160
        }
3161
}
3162

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

3175
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3176
        if err != nil {
×
3177
                return err
×
3178
        }
×
3179

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

×
3192
        switch {
×
3193
        case s.cfg.Tor.V2:
×
3194
                onionCfg.Type = tor.V2
×
3195
        case s.cfg.Tor.V3:
×
3196
                onionCfg.Type = tor.V3
×
3197
        }
3198

3199
        addr, err := s.torController.AddOnion(onionCfg)
×
3200
        if err != nil {
×
3201
                return err
×
3202
        }
×
3203

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

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

3234
        return nil
×
3235
}
3236

3237
// findChannel finds a channel given a public key and ChannelID. It is an
3238
// optimization that is quicker than seeking for a channel given only the
3239
// ChannelID.
3240
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3241
        *channeldb.OpenChannel, error) {
3✔
3242

3✔
3243
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3244
        if err != nil {
3✔
3245
                return nil, err
×
3246
        }
×
3247

3248
        for _, channel := range nodeChans {
6✔
3249
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3250
                        return channel, nil
3✔
3251
                }
3✔
3252
        }
3253

3254
        return nil, fmt.Errorf("unable to find channel")
3✔
3255
}
3256

3257
// getNodeAnnouncement fetches the current, fully signed node announcement.
3258
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3259
        s.mu.Lock()
3✔
3260
        defer s.mu.Unlock()
3✔
3261

3✔
3262
        return *s.currentNodeAnn
3✔
3263
}
3✔
3264

3265
// genNodeAnnouncement generates and returns the current fully signed node
3266
// announcement. The time stamp of the announcement will be updated in order
3267
// to ensure it propagates through the network.
3268
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3269
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3270

3✔
3271
        s.mu.Lock()
3✔
3272
        defer s.mu.Unlock()
3✔
3273

3✔
3274
        // First, try to update our feature manager with the updated set of
3✔
3275
        // features.
3✔
3276
        if features != nil {
6✔
3277
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3278
                        feature.SetNodeAnn: features,
3✔
3279
                }
3✔
3280
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3281
                if err != nil {
6✔
3282
                        return lnwire.NodeAnnouncement{}, err
3✔
3283
                }
3✔
3284

3285
                // If we could successfully update our feature manager, add
3286
                // an update modifier to include these new features to our
3287
                // set.
3288
                modifiers = append(
3✔
3289
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3290
                )
3✔
3291
        }
3292

3293
        // Always update the timestamp when refreshing to ensure the update
3294
        // propagates.
3295
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3296

3✔
3297
        // Apply the requested changes to the node announcement.
3✔
3298
        for _, modifier := range modifiers {
6✔
3299
                modifier(s.currentNodeAnn)
3✔
3300
        }
3✔
3301

3302
        // Sign a new update after applying all of the passed modifiers.
3303
        err := netann.SignNodeAnnouncement(
3✔
3304
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3305
        )
3✔
3306
        if err != nil {
3✔
3307
                return lnwire.NodeAnnouncement{}, err
×
3308
        }
×
3309

3310
        return *s.currentNodeAnn, nil
3✔
3311
}
3312

3313
// updateAndBroadcastSelfNode generates a new node announcement
3314
// applying the giving modifiers and updating the time stamp
3315
// to ensure it propagates through the network. Then it broadcasts
3316
// it to the network.
3317
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3318
        modifiers ...netann.NodeAnnModifier) error {
3✔
3319

3✔
3320
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3321
        if err != nil {
6✔
3322
                return fmt.Errorf("unable to generate new node "+
3✔
3323
                        "announcement: %v", err)
3✔
3324
        }
3✔
3325

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

3334
        selfNode.HaveNodeAnnouncement = true
3✔
3335
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3336
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3337
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3338
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3339
        selfNode.Color = newNodeAnn.RGBColor
3✔
3340
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3341

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

3✔
3344
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
3✔
3345
                return fmt.Errorf("can't set self node: %w", err)
×
3346
        }
×
3347

3348
        // Finally, propagate it to the nodes in the network.
3349
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3350
        if err != nil {
3✔
3351
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3352
                        "announcement to peers: %v", err)
×
3353
                return err
×
3354
        }
×
3355

3356
        return nil
3✔
3357
}
3358

3359
type nodeAddresses struct {
3360
        pubKey    *btcec.PublicKey
3361
        addresses []net.Addr
3362
}
3363

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

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

3390
        // After checking our previous connections for addresses to connect to,
3391
        // iterate through the nodes in our channel graph to find addresses
3392
        // that have been added via NodeAnnouncement messages.
3393
        sourceNode, err := s.graphDB.SourceNode()
3✔
3394
        if err != nil {
3✔
3395
                return err
×
3396
        }
×
3397

3398
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3399
        // each of the nodes.
3400
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3401
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3402
                tx kvdb.RTx,
3✔
3403
                chanInfo *models.ChannelEdgeInfo,
3✔
3404
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3405

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

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

3425
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3426

3✔
3427
                // Add all unique addresses from channel
3✔
3428
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3429
                // connect to for this peer.
3✔
3430
                addrSet := make(map[string]net.Addr)
3✔
3431
                for _, addr := range channelPeer.Addresses {
6✔
3432
                        switch addr.(type) {
3✔
3433
                        case *net.TCPAddr:
3✔
3434
                                addrSet[addr.String()] = addr
3✔
3435

3436
                        // We'll only attempt to connect to Tor addresses if Tor
3437
                        // outbound support is enabled.
3438
                        case *tor.OnionAddr:
×
3439
                                if s.cfg.Tor.Active {
×
3440
                                        addrSet[addr.String()] = addr
×
3441
                                }
×
3442
                        }
3443
                }
3444

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

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

3464
                // Construct a slice of the deduped addresses.
3465
                var addrs []net.Addr
3✔
3466
                for _, addr := range addrSet {
6✔
3467
                        addrs = append(addrs, addr)
3✔
3468
                }
3✔
3469

3470
                n := &nodeAddresses{
3✔
3471
                        addresses: addrs,
3✔
3472
                }
3✔
3473
                n.pubKey, err = channelPeer.PubKey()
3✔
3474
                if err != nil {
3✔
3475
                        return err
×
3476
                }
×
3477

3478
                nodeAddrsMap[pubStr] = n
3✔
3479
                return nil
3✔
3480
        })
3481
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3482
                return err
×
3483
        }
×
3484

3485
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3486
                len(nodeAddrsMap))
3✔
3487

3✔
3488
        // Acquire and hold server lock until all persistent connection requests
3✔
3489
        // have been recorded and sent to the connection manager.
3✔
3490
        s.mu.Lock()
3✔
3491
        defer s.mu.Unlock()
3✔
3492

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

3507
                for _, address := range nodeAddr.addresses {
6✔
3508
                        // Create a wrapper address which couples the IP and
3✔
3509
                        // the pubkey so the brontide authenticated connection
3✔
3510
                        // can be established.
3✔
3511
                        lnAddr := &lnwire.NetAddress{
3✔
3512
                                IdentityKey: nodeAddr.pubKey,
3✔
3513
                                Address:     address,
3✔
3514
                        }
3✔
3515

3✔
3516
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3517
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3518
                }
3✔
3519

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

3✔
3530
                        go s.connectToPersistentPeer(pubStr)
3✔
3531
                } else {
3✔
3532
                        go s.delayInitialReconnect(pubStr)
×
3533
                }
×
3534

3535
                numOutboundConns++
3✔
3536
        }
3537

3538
        return nil
3✔
3539
}
3540

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

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

3✔
3560
        s.mu.Lock()
3✔
3561
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3562
                delete(s.persistentPeers, pubKeyStr)
3✔
3563
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3564
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3565
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3566
                s.mu.Unlock()
3✔
3567

3✔
3568
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3569
                        "peer has no open channels", compressedPubKey)
3✔
3570

3✔
3571
                return
3✔
3572
        }
3✔
3573
        s.mu.Unlock()
3✔
3574
}
3575

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

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

3599
                peers = append(peers, sPeer)
3✔
3600
        }
3601
        s.mu.RUnlock()
3✔
3602

3✔
3603
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3604
        // all messages to each of peers.
3✔
3605
        var wg sync.WaitGroup
3✔
3606
        for _, sPeer := range peers {
6✔
3607
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3608
                        sPeer.PubKey())
3✔
3609

3✔
3610
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3611
                wg.Add(1)
3✔
3612
                s.wg.Add(1)
3✔
3613
                go func(p lnpeer.Peer) {
6✔
3614
                        defer s.wg.Done()
3✔
3615
                        defer wg.Done()
3✔
3616

3✔
3617
                        p.SendMessageLazy(false, msgs...)
3✔
3618
                }(sPeer)
3✔
3619
        }
3620

3621
        // Wait for all messages to have been dispatched before returning to
3622
        // caller.
3623
        wg.Wait()
3✔
3624

3✔
3625
        return nil
3✔
3626
}
3627

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

3✔
3635
        s.mu.Lock()
3✔
3636

3✔
3637
        // Compute the target peer's identifier.
3✔
3638
        pubStr := string(peerKey[:])
3✔
3639

3✔
3640
        // Check if peer is connected.
3✔
3641
        peer, ok := s.peersByPub[pubStr]
3✔
3642
        if ok {
6✔
3643
                // Unlock here so that the mutex isn't held while we are
3✔
3644
                // waiting for the peer to become active.
3✔
3645
                s.mu.Unlock()
3✔
3646

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

3662
                // Connected, can return early.
3663
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3664

3✔
3665
                select {
3✔
3666
                case peerChan <- peer:
3✔
3667
                case <-s.quit:
×
3668
                }
3669

3670
                return
3✔
3671
        }
3672

3673
        // Not connected, store this listener such that it can be notified when
3674
        // the peer comes online.
3675
        s.peerConnectedListeners[pubStr] = append(
3✔
3676
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3677
        )
3✔
3678
        s.mu.Unlock()
3✔
3679
}
3680

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

3✔
3688
        c := make(chan struct{})
3✔
3689

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

3699
        // Otherwise, the peer is online, so we'll keep track of the channel to
3700
        // trigger the notification once the server detects the peer
3701
        // disconnects.
3702
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3703
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3704
        )
3✔
3705

3✔
3706
        return c
3✔
3707
}
3708

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

3✔
3718
        pubStr := string(peerKey.SerializeCompressed())
3✔
3719

3✔
3720
        return s.findPeerByPubStr(pubStr)
3✔
3721
}
3✔
3722

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

3✔
3732
        return s.findPeerByPubStr(pubStr)
3✔
3733
}
3✔
3734

3735
// findPeerByPubStr is an internal method that retrieves the specified peer from
3736
// the server's internal state using.
3737
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3738
        peer, ok := s.peersByPub[pubStr]
3✔
3739
        if !ok {
6✔
3740
                return nil, ErrPeerNotConnected
3✔
3741
        }
3✔
3742

3743
        return peer, nil
3✔
3744
}
3745

3746
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3747
// exponential backoff. If no previous backoff was known, the default is
3748
// returned.
3749
func (s *server) nextPeerBackoff(pubStr string,
3750
        startTime time.Time) time.Duration {
3✔
3751

3✔
3752
        // Now, determine the appropriate backoff to use for the retry.
3✔
3753
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3754
        if !ok {
6✔
3755
                // If an existing backoff was unknown, use the default.
3✔
3756
                return s.cfg.MinBackoff
3✔
3757
        }
3✔
3758

3759
        // If the peer failed to start properly, we'll just use the previous
3760
        // backoff to compute the subsequent randomized exponential backoff
3761
        // duration. This will roughly double on average.
3762
        if startTime.IsZero() {
3✔
3763
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3764
        }
×
3765

3766
        // The peer succeeded in starting. If the connection didn't last long
3767
        // enough to be considered stable, we'll continue to back off retries
3768
        // with this peer.
3769
        connDuration := time.Since(startTime)
3✔
3770
        if connDuration < defaultStableConnDuration {
6✔
3771
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3772
        }
3✔
3773

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

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

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

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

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

3818
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3819
        pubSer := nodePub.SerializeCompressed()
3✔
3820
        pubStr := string(pubSer)
3✔
3821

3✔
3822
        var pubBytes [33]byte
3✔
3823
        copy(pubBytes[:], pubSer)
3✔
3824

3✔
3825
        s.mu.Lock()
3✔
3826
        defer s.mu.Unlock()
3✔
3827

3✔
3828
        // If the remote node's public key is banned, drop the connection.
3✔
3829
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3830
        if dcErr != nil {
3✔
3831
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3832
                        "peer: %v", dcErr)
×
3833
                conn.Close()
×
3834

×
3835
                return
×
3836
        }
×
3837

3838
        if shouldDc {
3✔
3839
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3840
                        "banned.", pubSer)
×
3841

×
3842
                conn.Close()
×
3843

×
3844
                return
×
3845
        }
×
3846

3847
        // If we already have an outbound connection to this peer, then ignore
3848
        // this new connection.
3849
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
3850
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
3851
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
3852
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3853

3✔
3854
                conn.Close()
3✔
3855
                return
3✔
3856
        }
3✔
3857

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

3868
        srvrLog.Infof("New inbound connection from %v", conn.RemoteAddr())
3✔
3869

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

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

×
3893
                        srvrLog.Warnf("Received inbound connection from "+
×
3894
                                "peer %v, but already have outbound "+
×
3895
                                "connection, dropping conn", connectedPeer)
×
3896
                        conn.Close()
×
3897
                        return
×
3898
                }
×
3899

3900
                // Otherwise, if we should drop the connection, then we'll
3901
                // disconnect our already connected peer.
3902
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
3903
                        connectedPeer)
×
3904

×
3905
                s.cancelConnReqs(pubStr, nil)
×
3906

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

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

3928
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3929
        pubSer := nodePub.SerializeCompressed()
3✔
3930
        pubStr := string(pubSer)
3✔
3931

3✔
3932
        var pubBytes [33]byte
3✔
3933
        copy(pubBytes[:], pubSer)
3✔
3934

3✔
3935
        s.mu.Lock()
3✔
3936
        defer s.mu.Unlock()
3✔
3937

3✔
3938
        // If the remote node's public key is banned, drop the connection.
3✔
3939
        shouldDc, dcErr := s.authGossiper.ShouldDisconnect(nodePub)
3✔
3940
        if dcErr != nil {
3✔
3941
                srvrLog.Errorf("Unable to check if we should disconnect "+
×
3942
                        "peer: %v", dcErr)
×
3943
                conn.Close()
×
3944

×
3945
                return
×
3946
        }
×
3947

3948
        if shouldDc {
3✔
3949
                srvrLog.Debugf("Dropping connection for %v since they are "+
×
3950
                        "banned.", pubSer)
×
3951

×
3952
                if connReq != nil {
×
3953
                        s.connMgr.Remove(connReq.ID())
×
3954
                }
×
3955

3956
                conn.Close()
×
3957

×
3958
                return
×
3959
        }
3960

3961
        // If we already have an inbound connection to this peer, then ignore
3962
        // this new connection.
3963
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
3964
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
3965
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
3966
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
3967

3✔
3968
                if connReq != nil {
6✔
3969
                        s.connMgr.Remove(connReq.ID())
3✔
3970
                }
3✔
3971
                conn.Close()
3✔
3972
                return
3✔
3973
        }
3974
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
3975
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
3976
                s.connMgr.Remove(connReq.ID())
×
3977
                conn.Close()
×
3978
                return
×
3979
        }
×
3980

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

×
3987
                if connReq != nil {
×
3988
                        s.connMgr.Remove(connReq.ID())
×
3989
                }
×
3990

3991
                conn.Close()
×
3992
                return
×
3993
        }
3994

3995
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
3996
                conn.RemoteAddr())
3✔
3997

3✔
3998
        if connReq != nil {
6✔
3999
                // A successful connection was returned by the connmgr.
3✔
4000
                // Immediately cancel all pending requests, excluding the
3✔
4001
                // outbound connection we just established.
3✔
4002
                ignore := connReq.ID()
3✔
4003
                s.cancelConnReqs(pubStr, &ignore)
3✔
4004
        } else {
6✔
4005
                // This was a successful connection made by some other
3✔
4006
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4007
                s.cancelConnReqs(pubStr, nil)
3✔
4008
        }
3✔
4009

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

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

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

4041
                // Otherwise, _their_ connection should be dropped. So we'll
4042
                // disconnect the peer and send the now obsolete peer to the
4043
                // server for garbage collection.
4044
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4045
                        connectedPeer)
×
4046

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

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

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

4078
        // Next, check to see if we have any outstanding persistent connection
4079
        // requests to this peer. If so, then we'll remove all of these
4080
        // connection requests, and also delete the entry from the map.
4081
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4082
        if !ok {
6✔
4083
                return
3✔
4084
        }
3✔
4085

4086
        for _, connReq := range connReqs {
6✔
4087
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4088

3✔
4089
                // Atomically capture the current request identifier.
3✔
4090
                connID := connReq.ID()
3✔
4091

3✔
4092
                // Skip any zero IDs, this indicates the request has not
3✔
4093
                // yet been schedule.
3✔
4094
                if connID == UnassignedConnID {
3✔
4095
                        continue
×
4096
                }
4097

4098
                // Skip a particular connection ID if instructed.
4099
                if skip != nil && connID == *skip {
6✔
4100
                        continue
3✔
4101
                }
4102

4103
                s.connMgr.Remove(connID)
3✔
4104
        }
4105

4106
        delete(s.persistentConnReqs, pubStr)
3✔
4107
}
4108

4109
// handleCustomMessage dispatches an incoming custom peers message to
4110
// subscribers.
4111
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4112
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4113
                peer, msg.Type)
3✔
4114

3✔
4115
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4116
                Peer: peer,
3✔
4117
                Msg:  msg,
3✔
4118
        })
3✔
4119
}
3✔
4120

4121
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4122
// messages.
4123
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4124
        return s.customMessageServer.Subscribe()
3✔
4125
}
3✔
4126

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

3✔
4134
        brontideConn := conn.(*brontide.Conn)
3✔
4135
        addr := conn.RemoteAddr()
3✔
4136
        pubKey := brontideConn.RemotePub()
3✔
4137

3✔
4138
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4139
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4140

3✔
4141
        peerAddr := &lnwire.NetAddress{
3✔
4142
                IdentityKey: pubKey,
3✔
4143
                Address:     addr,
3✔
4144
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4145
        }
3✔
4146

3✔
4147
        // With the brontide connection established, we'll now craft the feature
3✔
4148
        // vectors to advertise to the remote node.
3✔
4149
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4150
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4151

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

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

4176
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4177
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4178

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

3✔
4222
                        return s.genNodeAnnouncement(nil)
3✔
4223
                },
3✔
4224

4225
                PongBuf: s.pongBuf,
4226

4227
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4228

4229
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4230

4231
                FundingManager: s.fundingMgr,
4232

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

4262
                        return clock.NewDefaultClock().Now().Before(
3✔
4263
                                EndorsementExperimentEnd,
3✔
4264
                        )
3✔
4265
                },
4266
        }
4267

4268
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4269
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4270

3✔
4271
        p := peer.NewBrontide(pCfg)
3✔
4272

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

3✔
4276
        s.addPeer(p)
3✔
4277

3✔
4278
        // Once we have successfully added the peer to the server, we can
3✔
4279
        // delete the previous error buffer from the server's map of error
3✔
4280
        // buffers.
3✔
4281
        delete(s.peerErrors, pkStr)
3✔
4282

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

4290
// addPeer adds the passed peer to the server's global state of all active
4291
// peers.
4292
func (s *server) addPeer(p *peer.Brontide) {
3✔
4293
        if p == nil {
3✔
4294
                return
×
4295
        }
×
4296

4297
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4298

3✔
4299
        // Ignore new peers if we're shutting down.
3✔
4300
        if s.Stopped() {
3✔
4301
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4302
                        pubBytes)
×
4303
                p.Disconnect(ErrServerShuttingDown)
×
4304

×
4305
                return
×
4306
        }
×
4307

4308
        // Track the new peer in our indexes so we can quickly look it up either
4309
        // according to its public key, or its peer ID.
4310
        // TODO(roasbeef): pipe all requests through to the
4311
        // queryHandler/peerManager
4312

4313
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4314
        // be human-readable.
4315
        pubStr := string(pubBytes)
3✔
4316

3✔
4317
        s.peersByPub[pubStr] = p
3✔
4318

3✔
4319
        if p.Inbound() {
6✔
4320
                s.inboundPeers[pubStr] = p
3✔
4321
        } else {
6✔
4322
                s.outboundPeers[pubStr] = p
3✔
4323
        }
3✔
4324

4325
        // Inform the peer notifier of a peer online event so that it can be reported
4326
        // to clients listening for peer events.
4327
        var pubKey [33]byte
3✔
4328
        copy(pubKey[:], pubBytes)
3✔
4329

3✔
4330
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4331
}
4332

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

3✔
4345
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4346

3✔
4347
        // Avoid initializing peers while the server is exiting.
3✔
4348
        if s.Stopped() {
3✔
4349
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4350
                        pubBytes)
×
4351
                return
×
4352
        }
×
4353

4354
        // Create a channel that will be used to signal a successful start of
4355
        // the link. This prevents the peer termination watcher from beginning
4356
        // its duty too early.
4357
        ready := make(chan struct{})
3✔
4358

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

3✔
4368
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4369
        // will unblock the peerTerminationWatcher.
3✔
4370
        if err := p.Start(); err != nil {
3✔
UNCOV
4371
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
×
UNCOV
4372

×
UNCOV
4373
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
×
UNCOV
4374
                return
×
UNCOV
4375
        }
×
4376

4377
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4378
        // was successful, and to begin watching the peer's wait group.
4379
        close(ready)
3✔
4380

3✔
4381
        s.mu.Lock()
3✔
4382
        defer s.mu.Unlock()
3✔
4383

3✔
4384
        // Check if there are listeners waiting for this peer to come online.
3✔
4385
        srvrLog.Debugf("Notifying that peer %v is online", p)
3✔
4386

3✔
4387
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4388
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4389
        pubStr := string(pubBytes)
3✔
4390
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4391
                select {
3✔
4392
                case peerChan <- p:
3✔
4393
                case <-s.quit:
×
4394
                        return
×
4395
                }
4396
        }
4397
        delete(s.peerConnectedListeners, pubStr)
3✔
4398
}
4399

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

3✔
4414
        p.WaitForDisconnect(ready)
3✔
4415

3✔
4416
        srvrLog.Debugf("Peer %v has been disconnected", p)
3✔
4417

3✔
4418
        // If the server is exiting then we can bail out early ourselves as all
3✔
4419
        // the other sub-systems will already be shutting down.
3✔
4420
        if s.Stopped() {
6✔
4421
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4422
                return
3✔
4423
        }
3✔
4424

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

3✔
4431
        pubKey := p.IdentityKey()
3✔
4432

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

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

4447
        for _, link := range links {
6✔
4448
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4449
        }
3✔
4450

4451
        s.mu.Lock()
3✔
4452
        defer s.mu.Unlock()
3✔
4453

3✔
4454
        // If there were any notification requests for when this peer
3✔
4455
        // disconnected, we can trigger them now.
3✔
4456
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4457
        pubStr := string(pubKey.SerializeCompressed())
3✔
4458
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4459
                close(offlineChan)
3✔
4460
        }
3✔
4461
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4462

3✔
4463
        // If the server has already removed this peer, we can short circuit the
3✔
4464
        // peer termination watcher and skip cleanup.
3✔
4465
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4466
                delete(s.ignorePeerTermination, p)
×
4467

×
4468
                pubKey := p.PubKey()
×
4469
                pubStr := string(pubKey[:])
×
4470

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

4484
        // First, cleanup any remaining state the server has regarding the peer
4485
        // in question.
4486
        s.removePeer(p)
3✔
4487

3✔
4488
        // Next, check to see if this is a persistent peer or not.
3✔
4489
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4490
                return
3✔
4491
        }
3✔
4492

4493
        // Get the last address that we used to connect to the peer.
4494
        addrs := []net.Addr{
3✔
4495
                p.NetAddress().Address,
3✔
4496
        }
3✔
4497

3✔
4498
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4499
        // reconnection purposes.
3✔
4500
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4501
        switch {
3✔
4502
        // We found advertised addresses, so use them.
4503
        case err == nil:
3✔
4504
                addrs = advertisedAddrs
3✔
4505

4506
        // The peer doesn't have an advertised address.
4507
        case err == errNoAdvertisedAddr:
3✔
4508
                // If it is an outbound peer then we fall back to the existing
3✔
4509
                // peer address.
3✔
4510
                if !p.Inbound() {
6✔
4511
                        break
3✔
4512
                }
4513

4514
                // Fall back to the existing peer address if
4515
                // we're not accepting connections over Tor.
4516
                if s.torController == nil {
6✔
4517
                        break
3✔
4518
                }
4519

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

4530
        // We came across an error retrieving an advertised
4531
        // address, log it, and fall back to the existing peer
4532
        // address.
4533
        default:
3✔
4534
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4535
                        "address for node %x: %v", p.PubKey(),
3✔
4536
                        err)
3✔
4537
        }
4538

4539
        // Make an easy lookup map so that we can check if an address
4540
        // is already in the address list that we have stored for this peer.
4541
        existingAddrs := make(map[string]bool)
3✔
4542
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4543
                existingAddrs[addr.String()] = true
3✔
4544
        }
3✔
4545

4546
        // Add any missing addresses for this peer to persistentPeerAddr.
4547
        for _, addr := range addrs {
6✔
4548
                if existingAddrs[addr.String()] {
3✔
4549
                        continue
×
4550
                }
4551

4552
                s.persistentPeerAddrs[pubStr] = append(
3✔
4553
                        s.persistentPeerAddrs[pubStr],
3✔
4554
                        &lnwire.NetAddress{
3✔
4555
                                IdentityKey: p.IdentityKey(),
3✔
4556
                                Address:     addr,
3✔
4557
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4558
                        },
3✔
4559
                )
3✔
4560
        }
4561

4562
        // Record the computed backoff in the backoff map.
4563
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4564
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4565

3✔
4566
        // Initialize a retry canceller for this peer if one does not
3✔
4567
        // exist.
3✔
4568
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4569
        if !ok {
6✔
4570
                cancelChan = make(chan struct{})
3✔
4571
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4572
        }
3✔
4573

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

3✔
4582
                select {
3✔
4583
                case <-time.After(backoff):
3✔
4584
                case <-cancelChan:
3✔
4585
                        return
3✔
4586
                case <-s.quit:
3✔
4587
                        return
3✔
4588
                }
4589

4590
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4591
                        "connection to peer %x",
3✔
4592
                        p.IdentityKey().SerializeCompressed())
3✔
4593

3✔
4594
                s.connectToPersistentPeer(pubStr)
3✔
4595
        }()
4596
}
4597

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

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

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

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

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

4648
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4649

3✔
4650
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4651
        if !ok {
6✔
4652
                cancelChan = make(chan struct{})
3✔
4653
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4654
        }
3✔
4655

4656
        // Any addresses left in addrMap are new ones that we have not made
4657
        // connection requests for. So create new connection requests for those.
4658
        // If there is more than one address in the address map, stagger the
4659
        // creation of the connection requests for those.
4660
        go func() {
6✔
4661
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4662
                defer ticker.Stop()
3✔
4663

3✔
4664
                for _, addr := range addrMap {
6✔
4665
                        // Send the persistent connection request to the
3✔
4666
                        // connection manager, saving the request itself so we
3✔
4667
                        // can cancel/restart the process as needed.
3✔
4668
                        connReq := &connmgr.ConnReq{
3✔
4669
                                Addr:      addr,
3✔
4670
                                Permanent: true,
3✔
4671
                        }
3✔
4672

3✔
4673
                        s.mu.Lock()
3✔
4674
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4675
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4676
                        )
3✔
4677
                        s.mu.Unlock()
3✔
4678

3✔
4679
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4680
                                "channel peer %v", addr)
3✔
4681

3✔
4682
                        go s.connMgr.Connect(connReq)
3✔
4683

3✔
4684
                        select {
3✔
4685
                        case <-s.quit:
3✔
4686
                                return
3✔
4687
                        case <-cancelChan:
3✔
4688
                                return
3✔
4689
                        case <-ticker.C:
3✔
4690
                        }
4691
                }
4692
        }()
4693
}
4694

4695
// removePeer removes the passed peer from the server's state of all active
4696
// peers.
4697
func (s *server) removePeer(p *peer.Brontide) {
3✔
4698
        if p == nil {
3✔
4699
                return
×
4700
        }
×
4701

4702
        srvrLog.Debugf("removing peer %v", p)
3✔
4703

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

3✔
4708
        // If this peer had an active persistent connection request, remove it.
3✔
4709
        if p.ConnReq() != nil {
6✔
4710
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4711
        }
3✔
4712

4713
        // Ignore deleting peers if we're shutting down.
4714
        if s.Stopped() {
3✔
4715
                return
×
4716
        }
×
4717

4718
        pKey := p.PubKey()
3✔
4719
        pubSer := pKey[:]
3✔
4720
        pubStr := string(pubSer)
3✔
4721

3✔
4722
        delete(s.peersByPub, pubStr)
3✔
4723

3✔
4724
        if p.Inbound() {
6✔
4725
                delete(s.inboundPeers, pubStr)
3✔
4726
        } else {
6✔
4727
                delete(s.outboundPeers, pubStr)
3✔
4728
        }
3✔
4729

4730
        // Copy the peer's error buffer across to the server if it has any items
4731
        // in it so that we can restore peer errors across connections.
4732
        if p.ErrorBuffer().Total() > 0 {
6✔
4733
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4734
        }
3✔
4735

4736
        // Inform the peer notifier of a peer offline event so that it can be
4737
        // reported to clients listening for peer events.
4738
        var pubKey [33]byte
3✔
4739
        copy(pubKey[:], pubSer)
3✔
4740

3✔
4741
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4742
}
4743

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

3✔
4752
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4753

3✔
4754
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4755
        // better granularity.  In certain conditions, this method requires
3✔
4756
        // making an outbound connection to a remote peer, which requires the
3✔
4757
        // lock to be released, and subsequently reacquired.
3✔
4758
        s.mu.Lock()
3✔
4759

3✔
4760
        // Ensure we're not already connected to this peer.
3✔
4761
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4762
        if err == nil {
6✔
4763
                s.mu.Unlock()
3✔
4764
                return &errPeerAlreadyConnected{peer: peer}
3✔
4765
        }
3✔
4766

4767
        // Peer was not found, continue to pursue connection with peer.
4768

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

4777
        // If there's not already a pending or active connection to this node,
4778
        // then instruct the connection manager to attempt to establish a
4779
        // persistent connection to the peer.
4780
        srvrLog.Debugf("Connecting to %v", addr)
3✔
4781
        if perm {
6✔
4782
                connReq := &connmgr.ConnReq{
3✔
4783
                        Addr:      addr,
3✔
4784
                        Permanent: true,
3✔
4785
                }
3✔
4786

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

3✔
4800
                go s.connMgr.Connect(connReq)
3✔
4801

3✔
4802
                return nil
3✔
4803
        }
4804
        s.mu.Unlock()
3✔
4805

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

3✔
4813
        select {
3✔
4814
        case err := <-errChan:
3✔
4815
                return err
3✔
4816
        case <-s.quit:
×
4817
                return ErrServerShuttingDown
×
4818
        }
4819
}
4820

4821
// connectToPeer establishes a connection to a remote peer. errChan is used to
4822
// notify the caller if the connection attempt has failed. Otherwise, it will be
4823
// closed.
4824
func (s *server) connectToPeer(addr *lnwire.NetAddress,
4825
        errChan chan<- error, timeout time.Duration) {
3✔
4826

3✔
4827
        conn, err := brontide.Dial(
3✔
4828
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
4829
        )
3✔
4830
        if err != nil {
6✔
4831
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
4832
                select {
3✔
4833
                case errChan <- err:
3✔
4834
                case <-s.quit:
×
4835
                }
4836
                return
3✔
4837
        }
4838

4839
        close(errChan)
3✔
4840

3✔
4841
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
4842
                conn.LocalAddr(), conn.RemoteAddr())
3✔
4843

3✔
4844
        s.OutboundPeerConnected(nil, conn)
3✔
4845
}
4846

4847
// DisconnectPeer sends the request to server to close the connection with peer
4848
// identified by public key.
4849
//
4850
// NOTE: This function is safe for concurrent access.
4851
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
4852
        pubBytes := pubKey.SerializeCompressed()
3✔
4853
        pubStr := string(pubBytes)
3✔
4854

3✔
4855
        s.mu.Lock()
3✔
4856
        defer s.mu.Unlock()
3✔
4857

3✔
4858
        // Check that were actually connected to this peer. If not, then we'll
3✔
4859
        // exit in an error as we can't disconnect from a peer that we're not
3✔
4860
        // currently connected to.
3✔
4861
        peer, err := s.findPeerByPubStr(pubStr)
3✔
4862
        if err == ErrPeerNotConnected {
6✔
4863
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
4864
        }
3✔
4865

4866
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
4867

3✔
4868
        s.cancelConnReqs(pubStr, nil)
3✔
4869

3✔
4870
        // If this peer was formerly a persistent connection, then we'll remove
3✔
4871
        // them from this map so we don't attempt to re-connect after we
3✔
4872
        // disconnect.
3✔
4873
        delete(s.persistentPeers, pubStr)
3✔
4874
        delete(s.persistentPeersBackoff, pubStr)
3✔
4875

3✔
4876
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
4877
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
4878
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
4879

3✔
4880
        return nil
3✔
4881
}
4882

4883
// OpenChannel sends a request to the server to open a channel to the specified
4884
// peer identified by nodeKey with the passed channel funding parameters.
4885
//
4886
// NOTE: This function is safe for concurrent access.
4887
func (s *server) OpenChannel(
4888
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
4889

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

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

×
4904
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
4905
                return req.Updates, req.Err
×
4906
        }
×
4907
        req.Peer = peer
3✔
4908
        s.mu.RUnlock()
3✔
4909

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

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

×
4930
                return req.Updates, req.Err
×
4931
        }
×
4932

4933
        // Spawn a goroutine to send the funding workflow request to the funding
4934
        // manager. This allows the server to continue handling queries instead
4935
        // of blocking on this request which is exported as a synchronous
4936
        // request to the outside world.
4937
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
4938

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

4942
// Peers returns a slice of all active peers.
4943
//
4944
// NOTE: This function is safe for concurrent access.
4945
func (s *server) Peers() []*peer.Brontide {
3✔
4946
        s.mu.RLock()
3✔
4947
        defer s.mu.RUnlock()
3✔
4948

3✔
4949
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
4950
        for _, peer := range s.peersByPub {
6✔
4951
                peers = append(peers, peer)
3✔
4952
        }
3✔
4953

4954
        return peers
3✔
4955
}
4956

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

4968
        // Using 1/10 of our duration as a margin, compute a random offset to
4969
        // avoid the nodes entering connection cycles.
4970
        margin := nextBackoff / 10
3✔
4971

3✔
4972
        var wiggle big.Int
3✔
4973
        wiggle.SetUint64(uint64(margin))
3✔
4974
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
4975
                // Randomizing is not mission critical, so we'll just return the
×
4976
                // current backoff.
×
4977
                return nextBackoff
×
4978
        }
×
4979

4980
        // Otherwise add in our wiggle, but subtract out half of the margin so
4981
        // that the backoff can tweaked by 1/20 in either direction.
4982
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
4983
}
4984

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

4989
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
4990
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
4991
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
4992
        if err != nil {
3✔
4993
                return nil, err
×
4994
        }
×
4995

4996
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
4997
        if err != nil {
6✔
4998
                return nil, err
3✔
4999
        }
3✔
5000

5001
        if len(node.Addresses) == 0 {
6✔
5002
                return nil, errNoAdvertisedAddr
3✔
5003
        }
3✔
5004

5005
        return node.Addresses, nil
3✔
5006
}
5007

5008
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5009
// channel update for a target channel.
5010
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5011
        *lnwire.ChannelUpdate1, error) {
3✔
5012

3✔
5013
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5014
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5015
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5016
                if err != nil {
6✔
5017
                        return nil, err
3✔
5018
                }
3✔
5019

5020
                return netann.ExtractChannelUpdate(
3✔
5021
                        ourPubKey[:], info, edge1, edge2,
3✔
5022
                )
3✔
5023
        }
5024
}
5025

5026
// applyChannelUpdate applies the channel update to the different sub-systems of
5027
// the server. The useAlias boolean denotes whether or not to send an alias in
5028
// place of the real SCID.
5029
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5030
        op *wire.OutPoint, useAlias bool) error {
3✔
5031

3✔
5032
        var (
3✔
5033
                peerAlias    *lnwire.ShortChannelID
3✔
5034
                defaultAlias lnwire.ShortChannelID
3✔
5035
        )
3✔
5036

3✔
5037
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5038

3✔
5039
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5040
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5041
        if useAlias {
6✔
5042
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5043
                if foundAlias != defaultAlias {
6✔
5044
                        peerAlias = &foundAlias
3✔
5045
                }
3✔
5046
        }
5047

5048
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5049
                update, discovery.RemoteAlias(peerAlias),
3✔
5050
        )
3✔
5051
        select {
3✔
5052
        case err := <-errChan:
3✔
5053
                return err
3✔
5054
        case <-s.quit:
×
5055
                return ErrServerShuttingDown
×
5056
        }
5057
}
5058

5059
// SendCustomMessage sends a custom message to the peer with the specified
5060
// pubkey.
5061
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5062
        data []byte) error {
3✔
5063

3✔
5064
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5065
        if err != nil {
3✔
5066
                return err
×
5067
        }
×
5068

5069
        // We'll wait until the peer is active.
5070
        select {
3✔
5071
        case <-peer.ActiveSignal():
3✔
5072
        case <-peer.QuitSignal():
×
5073
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5074
        case <-s.quit:
×
5075
                return ErrServerShuttingDown
×
5076
        }
5077

5078
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5079
        if err != nil {
6✔
5080
                return err
3✔
5081
        }
3✔
5082

5083
        // Send the message as low-priority. For now we assume that all
5084
        // application-defined message are low priority.
5085
        return peer.SendMessageLazy(true, msg)
3✔
5086
}
5087

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

3✔
5096
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5097
                sweepAddr, err := wallet.NewAddress(
3✔
5098
                        lnwallet.TaprootPubkey, false,
3✔
5099
                        lnwallet.DefaultAccountName,
3✔
5100
                )
3✔
5101
                if err != nil {
3✔
5102
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5103
                }
×
5104

5105
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5106
                if err != nil {
3✔
5107
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5108
                }
×
5109

5110
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5111
                        wallet, netParams, addr,
3✔
5112
                )
3✔
5113
                if err != nil {
3✔
5114
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5115
                }
×
5116

5117
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5118
                        DeliveryAddress: addr,
3✔
5119
                        InternalKey:     internalKeyDesc,
3✔
5120
                })
3✔
5121
        }
5122
}
5123

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

9✔
5133
        // TODO(yy): remove the check on simnet/regtest such that the itest is
9✔
5134
        // covering the bootstrapping process.
9✔
5135
        return !cfg.NoNetBootstrap && !isDevNetwork
9✔
5136
}
9✔
5137

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

5148
        // Save the SCIDs in a map.
5149
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5150
        for _, c := range channels {
6✔
5151
                // If the channel is not pending, its FC has been finalized.
3✔
5152
                if !c.IsPending {
6✔
5153
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5154
                }
3✔
5155
        }
5156

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

5171
        for _, c := range pendings {
6✔
5172
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5173
                        continue
3✔
5174
                }
5175

5176
                // If the channel is still reported as pending, remove it from
5177
                // the map.
5178
                delete(closedSCIDs, c.ShortChannelID)
×
5179

×
5180
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5181
                        c.ShortChannelID)
×
5182
        }
5183

5184
        return closedSCIDs
3✔
5185
}
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