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

lightningnetwork / lnd / 14036036087

24 Mar 2025 01:06PM UTC coverage: 58.586% (-10.4%) from 68.989%
14036036087

Pull #9544

github

web-flow
Merge d2c82f00a into 5235f3b24
Pull Request #9544: graph: move graph cache out of CRUD layer

2370 of 3489 new or added lines in 9 files covered. (67.93%)

27658 existing lines in 444 files now uncovered.

96927 of 165445 relevant lines covered (58.59%)

1.82 hits per line

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

64.48
/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/chainio"
32
        "github.com/lightningnetwork/lnd/chainreg"
33
        "github.com/lightningnetwork/lnd/chanacceptor"
34
        "github.com/lightningnetwork/lnd/chanbackup"
35
        "github.com/lightningnetwork/lnd/chanfitness"
36
        "github.com/lightningnetwork/lnd/channeldb"
37
        "github.com/lightningnetwork/lnd/channelnotifier"
38
        "github.com/lightningnetwork/lnd/clock"
39
        "github.com/lightningnetwork/lnd/cluster"
40
        "github.com/lightningnetwork/lnd/contractcourt"
41
        "github.com/lightningnetwork/lnd/discovery"
42
        "github.com/lightningnetwork/lnd/feature"
43
        "github.com/lightningnetwork/lnd/fn/v2"
44
        "github.com/lightningnetwork/lnd/funding"
45
        "github.com/lightningnetwork/lnd/graph"
46
        graphdb "github.com/lightningnetwork/lnd/graph/db"
47
        "github.com/lightningnetwork/lnd/graph/db/models"
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
        // ErrGossiperBan is one of the errors that can be returned when we
145
        // attempt to finalize a connection to a remote peer.
146
        ErrGossiperBan = errors.New("gossiper has banned remote's key")
147

148
        // ErrNoMoreRestrictedAccessSlots is one of the errors that can be
149
        // returned when we attempt to finalize a connection. It means that
150
        // this peer has no pending-open, open, or closed channels with us and
151
        // are already at our connection ceiling for a peer with this access
152
        // status.
153
        ErrNoMoreRestrictedAccessSlots = errors.New("no more restricted slots")
154

155
        // ErrNoPeerScore is returned when we expect to find a score in
156
        // peerScores, but one does not exist.
157
        ErrNoPeerScore = errors.New("peer score not found")
158

159
        // ErrNoPendingPeerInfo is returned when we couldn't find any pending
160
        // peer info.
161
        ErrNoPendingPeerInfo = errors.New("no pending peer info")
162
)
163

164
// errPeerAlreadyConnected is an error returned by the server when we're
165
// commanded to connect to a peer, but they're already connected.
166
type errPeerAlreadyConnected struct {
167
        peer *peer.Brontide
168
}
169

170
// Error returns the human readable version of this error type.
171
//
172
// NOTE: Part of the error interface.
173
func (e *errPeerAlreadyConnected) Error() string {
3✔
174
        return fmt.Sprintf("already connected to peer: %v", e.peer)
3✔
175
}
3✔
176

177
// peerAccessStatus denotes the p2p access status of a given peer. This will be
178
// used to assign peer ban scores that determine an action the server will
179
// take.
180
type peerAccessStatus int
181

182
const (
183
        // peerStatusRestricted indicates that the peer only has access to the
184
        // limited number of "free" reserved slots.
185
        peerStatusRestricted peerAccessStatus = iota
186

187
        // peerStatusTemporary indicates that the peer only has temporary p2p
188
        // access to the server.
189
        peerStatusTemporary
190

191
        // peerStatusProtected indicates that the peer has been granted
192
        // permanent p2p access to the server. The peer can still have its
193
        // access revoked.
194
        peerStatusProtected
195
)
196

197
// peerSlotStatus determines whether a peer gets access to one of our free
198
// slots or gets to bypass this safety mechanism.
199
type peerSlotStatus struct {
200
        // state determines which privileges the peer has with our server.
201
        state peerAccessStatus
202
}
203

204
// server is the main server of the Lightning Network Daemon. The server houses
205
// global state pertaining to the wallet, database, and the rpcserver.
206
// Additionally, the server is also used as a central messaging bus to interact
207
// with any of its companion objects.
208
type server struct {
209
        active   int32 // atomic
210
        stopping int32 // atomic
211

212
        start sync.Once
213
        stop  sync.Once
214

215
        cfg *Config
216

217
        implCfg *ImplementationCfg
218

219
        // identityECDH is an ECDH capable wrapper for the private key used
220
        // to authenticate any incoming connections.
221
        identityECDH keychain.SingleKeyECDH
222

223
        // identityKeyLoc is the key locator for the above wrapped identity key.
224
        identityKeyLoc keychain.KeyLocator
225

226
        // nodeSigner is an implementation of the MessageSigner implementation
227
        // that's backed by the identity private key of the running lnd node.
228
        nodeSigner *netann.NodeSigner
229

230
        chanStatusMgr *netann.ChanStatusManager
231

232
        // listenAddrs is the list of addresses the server is currently
233
        // listening on.
234
        listenAddrs []net.Addr
235

236
        // torController is a client that will communicate with a locally
237
        // running Tor server. This client will handle initiating and
238
        // authenticating the connection to the Tor server, automatically
239
        // creating and setting up onion services, etc.
240
        torController *tor.Controller
241

242
        // natTraversal is the specific NAT traversal technique used to
243
        // automatically set up port forwarding rules in order to advertise to
244
        // the network that the node is accepting inbound connections.
245
        natTraversal nat.Traversal
246

247
        // lastDetectedIP is the last IP detected by the NAT traversal technique
248
        // above. This IP will be watched periodically in a goroutine in order
249
        // to handle dynamic IP changes.
250
        lastDetectedIP net.IP
251

252
        mu sync.RWMutex
253

254
        // peersByPub is a map of the active peers.
255
        //
256
        // NOTE: The key used here is the raw bytes of the peer's public key to
257
        // string conversion, which means it cannot be printed using `%s` as it
258
        // will just print the binary.
259
        //
260
        // TODO(yy): Use the hex string instead.
261
        peersByPub map[string]*peer.Brontide
262

263
        inboundPeers  map[string]*peer.Brontide
264
        outboundPeers map[string]*peer.Brontide
265

266
        peerConnectedListeners    map[string][]chan<- lnpeer.Peer
267
        peerDisconnectedListeners map[string][]chan<- struct{}
268

269
        // TODO(yy): the Brontide.Start doesn't know this value, which means it
270
        // will continue to send messages even if there are no active channels
271
        // and the value below is false. Once it's pruned, all its connections
272
        // will be closed, thus the Brontide.Start will return an error.
273
        persistentPeers        map[string]bool
274
        persistentPeersBackoff map[string]time.Duration
275
        persistentPeerAddrs    map[string][]*lnwire.NetAddress
276
        persistentConnReqs     map[string][]*connmgr.ConnReq
277
        persistentRetryCancels map[string]chan struct{}
278

279
        // peerErrors keeps a set of peer error buffers for peers that have
280
        // disconnected from us. This allows us to track historic peer errors
281
        // over connections. The string of the peer's compressed pubkey is used
282
        // as a key for this map.
283
        peerErrors map[string]*queue.CircularBuffer
284

285
        // ignorePeerTermination tracks peers for which the server has initiated
286
        // a disconnect. Adding a peer to this map causes the peer termination
287
        // watcher to short circuit in the event that peers are purposefully
288
        // disconnected.
289
        ignorePeerTermination map[*peer.Brontide]struct{}
290

291
        // scheduledPeerConnection maps a pubkey string to a callback that
292
        // should be executed in the peerTerminationWatcher the prior peer with
293
        // the same pubkey exits.  This allows the server to wait until the
294
        // prior peer has cleaned up successfully, before adding the new peer
295
        // intended to replace it.
296
        scheduledPeerConnection map[string]func()
297

298
        // pongBuf is a shared pong reply buffer we'll use across all active
299
        // peer goroutines. We know the max size of a pong message
300
        // (lnwire.MaxPongBytes), so we can allocate this ahead of time, and
301
        // avoid allocations each time we need to send a pong message.
302
        pongBuf []byte
303

304
        cc *chainreg.ChainControl
305

306
        fundingMgr *funding.Manager
307

308
        graphDB *graphdb.ChannelGraph
309

310
        chanStateDB *channeldb.ChannelStateDB
311

312
        addrSource channeldb.AddrSource
313

314
        // miscDB is the DB that contains all "other" databases within the main
315
        // channel DB that haven't been separated out yet.
316
        miscDB *channeldb.DB
317

318
        invoicesDB invoices.InvoiceDB
319

320
        aliasMgr *aliasmgr.Manager
321

322
        htlcSwitch *htlcswitch.Switch
323

324
        interceptableSwitch *htlcswitch.InterceptableSwitch
325

326
        invoices *invoices.InvoiceRegistry
327

328
        invoiceHtlcModifier *invoices.HtlcModificationInterceptor
329

330
        channelNotifier *channelnotifier.ChannelNotifier
331

332
        peerNotifier *peernotifier.PeerNotifier
333

334
        htlcNotifier *htlcswitch.HtlcNotifier
335

336
        witnessBeacon contractcourt.WitnessBeacon
337

338
        breachArbitrator *contractcourt.BreachArbitrator
339

340
        missionController *routing.MissionController
341
        defaultMC         *routing.MissionControl
342

343
        graphBuilder *graph.Builder
344

345
        chanRouter *routing.ChannelRouter
346

347
        controlTower routing.ControlTower
348

349
        authGossiper *discovery.AuthenticatedGossiper
350

351
        localChanMgr *localchans.Manager
352

353
        utxoNursery *contractcourt.UtxoNursery
354

355
        sweeper *sweep.UtxoSweeper
356

357
        chainArb *contractcourt.ChainArbitrator
358

359
        sphinx *hop.OnionProcessor
360

361
        towerClientMgr *wtclient.Manager
362

363
        connMgr *connmgr.ConnManager
364

365
        sigPool *lnwallet.SigPool
366

367
        writePool *pool.Write
368

369
        readPool *pool.Read
370

371
        tlsManager *TLSManager
372

373
        // featureMgr dispatches feature vectors for various contexts within the
374
        // daemon.
375
        featureMgr *feature.Manager
376

377
        // currentNodeAnn is the node announcement that has been broadcast to
378
        // the network upon startup, if the attributes of the node (us) has
379
        // changed since last start.
380
        currentNodeAnn *lnwire.NodeAnnouncement
381

382
        // chansToRestore is the set of channels that upon starting, the server
383
        // should attempt to restore/recover.
384
        chansToRestore walletunlocker.ChannelsToRecover
385

386
        // chanSubSwapper is a sub-system that will ensure our on-disk channel
387
        // backups are consistent at all times. It interacts with the
388
        // channelNotifier to be notified of newly opened and closed channels.
389
        chanSubSwapper *chanbackup.SubSwapper
390

391
        // chanEventStore tracks the behaviour of channels and their remote peers to
392
        // provide insights into their health and performance.
393
        chanEventStore *chanfitness.ChannelEventStore
394

395
        hostAnn *netann.HostAnnouncer
396

397
        // livenessMonitor monitors that lnd has access to critical resources.
398
        livenessMonitor *healthcheck.Monitor
399

400
        customMessageServer *subscribe.Server
401

402
        // txPublisher is a publisher with fee-bumping capability.
403
        txPublisher *sweep.TxPublisher
404

405
        // blockbeatDispatcher is a block dispatcher that notifies subscribers
406
        // of new blocks.
407
        blockbeatDispatcher *chainio.BlockbeatDispatcher
408

409
        // peerAccessMan implements peer access controls.
410
        peerAccessMan *accessMan
411

412
        quit chan struct{}
413

414
        wg sync.WaitGroup
415
}
416

417
// updatePersistentPeerAddrs subscribes to topology changes and stores
418
// advertised addresses for any NodeAnnouncements from our persisted peers.
419
func (s *server) updatePersistentPeerAddrs() error {
3✔
420
        graphSub, err := s.graphDB.SubscribeTopology()
3✔
421
        if err != nil {
3✔
422
                return err
×
423
        }
×
424

425
        s.wg.Add(1)
3✔
426
        go func() {
6✔
427
                defer func() {
6✔
428
                        graphSub.Cancel()
3✔
429
                        s.wg.Done()
3✔
430
                }()
3✔
431

432
                for {
6✔
433
                        select {
3✔
434
                        case <-s.quit:
3✔
435
                                return
3✔
436

437
                        case topChange, ok := <-graphSub.TopologyChanges:
3✔
438
                                // If the router is shutting down, then we will
3✔
439
                                // as well.
3✔
440
                                if !ok {
3✔
441
                                        return
×
442
                                }
×
443

444
                                for _, update := range topChange.NodeUpdates {
6✔
445
                                        pubKeyStr := string(
3✔
446
                                                update.IdentityKey.
3✔
447
                                                        SerializeCompressed(),
3✔
448
                                        )
3✔
449

3✔
450
                                        // We only care about updates from
3✔
451
                                        // our persistentPeers.
3✔
452
                                        s.mu.RLock()
3✔
453
                                        _, ok := s.persistentPeers[pubKeyStr]
3✔
454
                                        s.mu.RUnlock()
3✔
455
                                        if !ok {
6✔
456
                                                continue
3✔
457
                                        }
458

459
                                        addrs := make([]*lnwire.NetAddress, 0,
3✔
460
                                                len(update.Addresses))
3✔
461

3✔
462
                                        for _, addr := range update.Addresses {
6✔
463
                                                addrs = append(addrs,
3✔
464
                                                        &lnwire.NetAddress{
3✔
465
                                                                IdentityKey: update.IdentityKey,
3✔
466
                                                                Address:     addr,
3✔
467
                                                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
468
                                                        },
3✔
469
                                                )
3✔
470
                                        }
3✔
471

472
                                        s.mu.Lock()
3✔
473

3✔
474
                                        // Update the stored addresses for this
3✔
475
                                        // to peer to reflect the new set.
3✔
476
                                        s.persistentPeerAddrs[pubKeyStr] = addrs
3✔
477

3✔
478
                                        // If there are no outstanding
3✔
479
                                        // connection requests for this peer
3✔
480
                                        // then our work is done since we are
3✔
481
                                        // not currently trying to connect to
3✔
482
                                        // them.
3✔
483
                                        if len(s.persistentConnReqs[pubKeyStr]) == 0 {
6✔
484
                                                s.mu.Unlock()
3✔
485
                                                continue
3✔
486
                                        }
487

488
                                        s.mu.Unlock()
3✔
489

3✔
490
                                        s.connectToPersistentPeer(pubKeyStr)
3✔
491
                                }
492
                        }
493
                }
494
        }()
495

496
        return nil
3✔
497
}
498

499
// CustomMessage is a custom message that is received from a peer.
500
type CustomMessage struct {
501
        // Peer is the peer pubkey
502
        Peer [33]byte
503

504
        // Msg is the custom wire message.
505
        Msg *lnwire.Custom
506
}
507

508
// parseAddr parses an address from its string format to a net.Addr.
509
func parseAddr(address string, netCfg tor.Net) (net.Addr, error) {
3✔
510
        var (
3✔
511
                host string
3✔
512
                port int
3✔
513
        )
3✔
514

3✔
515
        // Split the address into its host and port components.
3✔
516
        h, p, err := net.SplitHostPort(address)
3✔
517
        if err != nil {
3✔
518
                // If a port wasn't specified, we'll assume the address only
×
519
                // contains the host so we'll use the default port.
×
520
                host = address
×
521
                port = defaultPeerPort
×
522
        } else {
3✔
523
                // Otherwise, we'll note both the host and ports.
3✔
524
                host = h
3✔
525
                portNum, err := strconv.Atoi(p)
3✔
526
                if err != nil {
3✔
527
                        return nil, err
×
528
                }
×
529
                port = portNum
3✔
530
        }
531

532
        if tor.IsOnionHost(host) {
3✔
533
                return &tor.OnionAddr{OnionService: host, Port: port}, nil
×
534
        }
×
535

536
        // If the host is part of a TCP address, we'll use the network
537
        // specific ResolveTCPAddr function in order to resolve these
538
        // addresses over Tor in order to prevent leaking your real IP
539
        // address.
540
        hostPort := net.JoinHostPort(host, strconv.Itoa(port))
3✔
541
        return netCfg.ResolveTCPAddr("tcp", hostPort)
3✔
542
}
543

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

3✔
549
        return func(a net.Addr) (net.Conn, error) {
6✔
550
                lnAddr := a.(*lnwire.NetAddress)
3✔
551
                return brontide.Dial(idKey, lnAddr, timeout, netCfg.Dial)
3✔
552
        }
3✔
553
}
554

555
// newServer creates a new instance of the server which is to listen using the
556
// passed listener address.
557
func newServer(cfg *Config, listenAddrs []net.Addr,
558
        dbs *DatabaseInstances, cc *chainreg.ChainControl,
559
        nodeKeyDesc *keychain.KeyDescriptor,
560
        chansToRestore walletunlocker.ChannelsToRecover,
561
        chanPredicate chanacceptor.ChannelAcceptor,
562
        torController *tor.Controller, tlsManager *TLSManager,
563
        leaderElector cluster.LeaderElector,
564
        implCfg *ImplementationCfg) (*server, error) {
3✔
565

3✔
566
        var (
3✔
567
                err         error
3✔
568
                nodeKeyECDH = keychain.NewPubKeyECDH(*nodeKeyDesc, cc.KeyRing)
3✔
569

3✔
570
                // We just derived the full descriptor, so we know the public
3✔
571
                // key is set on it.
3✔
572
                nodeKeySigner = keychain.NewPubKeyMessageSigner(
3✔
573
                        nodeKeyDesc.PubKey, nodeKeyDesc.KeyLocator, cc.KeyRing,
3✔
574
                )
3✔
575
        )
3✔
576

3✔
577
        var serializedPubKey [33]byte
3✔
578
        copy(serializedPubKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
579

3✔
580
        netParams := cfg.ActiveNetParams.Params
3✔
581

3✔
582
        // Initialize the sphinx router.
3✔
583
        replayLog := htlcswitch.NewDecayedLog(
3✔
584
                dbs.DecayedLogDB, cc.ChainNotifier,
3✔
585
        )
3✔
586
        sphinxRouter := sphinx.NewRouter(nodeKeyECDH, replayLog)
3✔
587

3✔
588
        writeBufferPool := pool.NewWriteBuffer(
3✔
589
                pool.DefaultWriteBufferGCInterval,
3✔
590
                pool.DefaultWriteBufferExpiryInterval,
3✔
591
        )
3✔
592

3✔
593
        writePool := pool.NewWrite(
3✔
594
                writeBufferPool, cfg.Workers.Write, pool.DefaultWorkerTimeout,
3✔
595
        )
3✔
596

3✔
597
        readBufferPool := pool.NewReadBuffer(
3✔
598
                pool.DefaultReadBufferGCInterval,
3✔
599
                pool.DefaultReadBufferExpiryInterval,
3✔
600
        )
3✔
601

3✔
602
        readPool := pool.NewRead(
3✔
603
                readBufferPool, cfg.Workers.Read, pool.DefaultWorkerTimeout,
3✔
604
        )
3✔
605

3✔
606
        // If the taproot overlay flag is set, but we don't have an aux funding
3✔
607
        // controller, then we'll exit as this is incompatible.
3✔
608
        if cfg.ProtocolOptions.TaprootOverlayChans &&
3✔
609
                implCfg.AuxFundingController.IsNone() {
3✔
610

×
611
                return nil, fmt.Errorf("taproot overlay flag set, but not " +
×
612
                        "aux controllers")
×
613
        }
×
614

615
        // For now, the RBF coop close flag and the taproot channel type cannot
616
        // be used together.
617
        //
618
        // TODO(roasbeef): fix
619
        if cfg.ProtocolOptions.RbfCoopClose &&
3✔
620
                cfg.ProtocolOptions.TaprootChans {
3✔
621

×
622
                return nil, fmt.Errorf("RBF coop close and taproot " +
×
623
                        "channels cannot be used together")
×
624
        }
×
625

626
        //nolint:ll
627
        featureMgr, err := feature.NewManager(feature.Config{
3✔
628
                NoTLVOnion:                cfg.ProtocolOptions.LegacyOnion(),
3✔
629
                NoStaticRemoteKey:         cfg.ProtocolOptions.NoStaticRemoteKey(),
3✔
630
                NoAnchors:                 cfg.ProtocolOptions.NoAnchorCommitments(),
3✔
631
                NoWumbo:                   !cfg.ProtocolOptions.Wumbo(),
3✔
632
                NoScriptEnforcementLease:  cfg.ProtocolOptions.NoScriptEnforcementLease(),
3✔
633
                NoKeysend:                 !cfg.AcceptKeySend,
3✔
634
                NoOptionScidAlias:         !cfg.ProtocolOptions.ScidAlias(),
3✔
635
                NoZeroConf:                !cfg.ProtocolOptions.ZeroConf(),
3✔
636
                NoAnySegwit:               cfg.ProtocolOptions.NoAnySegwit(),
3✔
637
                CustomFeatures:            cfg.ProtocolOptions.CustomFeatures(),
3✔
638
                NoTaprootChans:            !cfg.ProtocolOptions.TaprootChans,
3✔
639
                NoTaprootOverlay:          !cfg.ProtocolOptions.TaprootOverlayChans,
3✔
640
                NoRouteBlinding:           cfg.ProtocolOptions.NoRouteBlinding(),
3✔
641
                NoExperimentalEndorsement: cfg.ProtocolOptions.NoExperimentalEndorsement(),
3✔
642
                NoQuiescence:              cfg.ProtocolOptions.NoQuiescence(),
3✔
643
                NoRbfCoopClose:            !cfg.ProtocolOptions.RbfCoopClose,
3✔
644
        })
3✔
645
        if err != nil {
3✔
646
                return nil, err
×
647
        }
×
648

649
        invoiceHtlcModifier := invoices.NewHtlcModificationInterceptor()
3✔
650
        registryConfig := invoices.RegistryConfig{
3✔
651
                FinalCltvRejectDelta:        lncfg.DefaultFinalCltvRejectDelta,
3✔
652
                HtlcHoldDuration:            invoices.DefaultHtlcHoldDuration,
3✔
653
                Clock:                       clock.NewDefaultClock(),
3✔
654
                AcceptKeySend:               cfg.AcceptKeySend,
3✔
655
                AcceptAMP:                   cfg.AcceptAMP,
3✔
656
                GcCanceledInvoicesOnStartup: cfg.GcCanceledInvoicesOnStartup,
3✔
657
                GcCanceledInvoicesOnTheFly:  cfg.GcCanceledInvoicesOnTheFly,
3✔
658
                KeysendHoldTime:             cfg.KeysendHoldTime,
3✔
659
                HtlcInterceptor:             invoiceHtlcModifier,
3✔
660
        }
3✔
661

3✔
662
        addrSource := channeldb.NewMultiAddrSource(dbs.ChanStateDB, dbs.GraphDB)
3✔
663

3✔
664
        s := &server{
3✔
665
                cfg:            cfg,
3✔
666
                implCfg:        implCfg,
3✔
667
                graphDB:        dbs.GraphDB,
3✔
668
                chanStateDB:    dbs.ChanStateDB.ChannelStateDB(),
3✔
669
                addrSource:     addrSource,
3✔
670
                miscDB:         dbs.ChanStateDB,
3✔
671
                invoicesDB:     dbs.InvoiceDB,
3✔
672
                cc:             cc,
3✔
673
                sigPool:        lnwallet.NewSigPool(cfg.Workers.Sig, cc.Signer),
3✔
674
                writePool:      writePool,
3✔
675
                readPool:       readPool,
3✔
676
                chansToRestore: chansToRestore,
3✔
677

3✔
678
                blockbeatDispatcher: chainio.NewBlockbeatDispatcher(
3✔
679
                        cc.ChainNotifier,
3✔
680
                ),
3✔
681
                channelNotifier: channelnotifier.New(
3✔
682
                        dbs.ChanStateDB.ChannelStateDB(),
3✔
683
                ),
3✔
684

3✔
685
                identityECDH:   nodeKeyECDH,
3✔
686
                identityKeyLoc: nodeKeyDesc.KeyLocator,
3✔
687
                nodeSigner:     netann.NewNodeSigner(nodeKeySigner),
3✔
688

3✔
689
                listenAddrs: listenAddrs,
3✔
690

3✔
691
                // TODO(roasbeef): derive proper onion key based on rotation
3✔
692
                // schedule
3✔
693
                sphinx: hop.NewOnionProcessor(sphinxRouter),
3✔
694

3✔
695
                torController: torController,
3✔
696

3✔
697
                persistentPeers:         make(map[string]bool),
3✔
698
                persistentPeersBackoff:  make(map[string]time.Duration),
3✔
699
                persistentConnReqs:      make(map[string][]*connmgr.ConnReq),
3✔
700
                persistentPeerAddrs:     make(map[string][]*lnwire.NetAddress),
3✔
701
                persistentRetryCancels:  make(map[string]chan struct{}),
3✔
702
                peerErrors:              make(map[string]*queue.CircularBuffer),
3✔
703
                ignorePeerTermination:   make(map[*peer.Brontide]struct{}),
3✔
704
                scheduledPeerConnection: make(map[string]func()),
3✔
705
                pongBuf:                 make([]byte, lnwire.MaxPongBytes),
3✔
706

3✔
707
                peersByPub:                make(map[string]*peer.Brontide),
3✔
708
                inboundPeers:              make(map[string]*peer.Brontide),
3✔
709
                outboundPeers:             make(map[string]*peer.Brontide),
3✔
710
                peerConnectedListeners:    make(map[string][]chan<- lnpeer.Peer),
3✔
711
                peerDisconnectedListeners: make(map[string][]chan<- struct{}),
3✔
712

3✔
713
                invoiceHtlcModifier: invoiceHtlcModifier,
3✔
714

3✔
715
                customMessageServer: subscribe.NewServer(),
3✔
716

3✔
717
                tlsManager: tlsManager,
3✔
718

3✔
719
                featureMgr: featureMgr,
3✔
720
                quit:       make(chan struct{}),
3✔
721
        }
3✔
722

3✔
723
        // Start the low-level services once they are initialized.
3✔
724
        //
3✔
725
        // TODO(yy): break the server startup into four steps,
3✔
726
        // 1. init the low-level services.
3✔
727
        // 2. start the low-level services.
3✔
728
        // 3. init the high-level services.
3✔
729
        // 4. start the high-level services.
3✔
730
        if err := s.startLowLevelServices(); err != nil {
3✔
731
                return nil, err
×
732
        }
×
733

734
        currentHash, currentHeight, err := s.cc.ChainIO.GetBestBlock()
3✔
735
        if err != nil {
3✔
736
                return nil, err
×
737
        }
×
738

739
        expiryWatcher := invoices.NewInvoiceExpiryWatcher(
3✔
740
                clock.NewDefaultClock(), cfg.Invoices.HoldExpiryDelta,
3✔
741
                uint32(currentHeight), currentHash, cc.ChainNotifier,
3✔
742
        )
3✔
743
        s.invoices = invoices.NewRegistry(
3✔
744
                dbs.InvoiceDB, expiryWatcher, &registryConfig,
3✔
745
        )
3✔
746

3✔
747
        s.htlcNotifier = htlcswitch.NewHtlcNotifier(time.Now)
3✔
748

3✔
749
        thresholdSats := btcutil.Amount(cfg.MaxFeeExposure)
3✔
750
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
751

3✔
752
        linkUpdater := func(shortID lnwire.ShortChannelID) error {
6✔
753
                link, err := s.htlcSwitch.GetLinkByShortID(shortID)
3✔
754
                if err != nil {
3✔
755
                        return err
×
756
                }
×
757

758
                s.htlcSwitch.UpdateLinkAliases(link)
3✔
759

3✔
760
                return nil
3✔
761
        }
762

763
        s.aliasMgr, err = aliasmgr.NewManager(dbs.ChanStateDB, linkUpdater)
3✔
764
        if err != nil {
3✔
765
                return nil, err
×
766
        }
×
767

768
        s.htlcSwitch, err = htlcswitch.New(htlcswitch.Config{
3✔
769
                DB:                   dbs.ChanStateDB,
3✔
770
                FetchAllOpenChannels: s.chanStateDB.FetchAllOpenChannels,
3✔
771
                FetchAllChannels:     s.chanStateDB.FetchAllChannels,
3✔
772
                FetchClosedChannels:  s.chanStateDB.FetchClosedChannels,
3✔
773
                LocalChannelClose: func(pubKey []byte,
3✔
774
                        request *htlcswitch.ChanClose) {
6✔
775

3✔
776
                        peer, err := s.FindPeerByPubStr(string(pubKey))
3✔
777
                        if err != nil {
3✔
778
                                srvrLog.Errorf("unable to close channel, peer"+
×
779
                                        " with %v id can't be found: %v",
×
780
                                        pubKey, err,
×
781
                                )
×
782
                                return
×
783
                        }
×
784

785
                        peer.HandleLocalCloseChanReqs(request)
3✔
786
                },
787
                FwdingLog:              dbs.ChanStateDB.ForwardingLog(),
788
                SwitchPackager:         channeldb.NewSwitchPackager(),
789
                ExtractErrorEncrypter:  s.sphinx.ExtractErrorEncrypter,
790
                FetchLastChannelUpdate: s.fetchLastChanUpdate(),
791
                Notifier:               s.cc.ChainNotifier,
792
                HtlcNotifier:           s.htlcNotifier,
793
                FwdEventTicker:         ticker.New(htlcswitch.DefaultFwdEventInterval),
794
                LogEventTicker:         ticker.New(htlcswitch.DefaultLogInterval),
795
                AckEventTicker:         ticker.New(htlcswitch.DefaultAckInterval),
796
                AllowCircularRoute:     cfg.AllowCircularRoute,
797
                RejectHTLC:             cfg.RejectHTLC,
798
                Clock:                  clock.NewDefaultClock(),
799
                MailboxDeliveryTimeout: cfg.Htlcswitch.MailboxDeliveryTimeout,
800
                MaxFeeExposure:         thresholdMSats,
801
                SignAliasUpdate:        s.signAliasUpdate,
802
                IsAlias:                aliasmgr.IsAlias,
803
        }, uint32(currentHeight))
804
        if err != nil {
3✔
805
                return nil, err
×
806
        }
×
807
        s.interceptableSwitch, err = htlcswitch.NewInterceptableSwitch(
3✔
808
                &htlcswitch.InterceptableSwitchConfig{
3✔
809
                        Switch:             s.htlcSwitch,
3✔
810
                        CltvRejectDelta:    lncfg.DefaultFinalCltvRejectDelta,
3✔
811
                        CltvInterceptDelta: lncfg.DefaultCltvInterceptDelta,
3✔
812
                        RequireInterceptor: s.cfg.RequireInterceptor,
3✔
813
                        Notifier:           s.cc.ChainNotifier,
3✔
814
                },
3✔
815
        )
3✔
816
        if err != nil {
3✔
817
                return nil, err
×
818
        }
×
819

820
        s.witnessBeacon = newPreimageBeacon(
3✔
821
                dbs.ChanStateDB.NewWitnessCache(),
3✔
822
                s.interceptableSwitch.ForwardPacket,
3✔
823
        )
3✔
824

3✔
825
        chanStatusMgrCfg := &netann.ChanStatusConfig{
3✔
826
                ChanStatusSampleInterval: cfg.ChanStatusSampleInterval,
3✔
827
                ChanEnableTimeout:        cfg.ChanEnableTimeout,
3✔
828
                ChanDisableTimeout:       cfg.ChanDisableTimeout,
3✔
829
                OurPubKey:                nodeKeyDesc.PubKey,
3✔
830
                OurKeyLoc:                nodeKeyDesc.KeyLocator,
3✔
831
                MessageSigner:            s.nodeSigner,
3✔
832
                IsChannelActive:          s.htlcSwitch.HasActiveLink,
3✔
833
                ApplyChannelUpdate:       s.applyChannelUpdate,
3✔
834
                DB:                       s.chanStateDB,
3✔
835
                Graph:                    dbs.GraphDB,
3✔
836
        }
3✔
837

3✔
838
        chanStatusMgr, err := netann.NewChanStatusManager(chanStatusMgrCfg)
3✔
839
        if err != nil {
3✔
840
                return nil, err
×
841
        }
×
842
        s.chanStatusMgr = chanStatusMgr
3✔
843

3✔
844
        // If enabled, use either UPnP or NAT-PMP to automatically configure
3✔
845
        // port forwarding for users behind a NAT.
3✔
846
        if cfg.NAT {
3✔
847
                srvrLog.Info("Scanning local network for a UPnP enabled device")
×
848

×
849
                discoveryTimeout := time.Duration(10 * time.Second)
×
850

×
851
                ctx, cancel := context.WithTimeout(
×
852
                        context.Background(), discoveryTimeout,
×
853
                )
×
854
                defer cancel()
×
855
                upnp, err := nat.DiscoverUPnP(ctx)
×
856
                if err == nil {
×
857
                        s.natTraversal = upnp
×
858
                } else {
×
859
                        // If we were not able to discover a UPnP enabled device
×
860
                        // on the local network, we'll fall back to attempting
×
861
                        // to discover a NAT-PMP enabled device.
×
862
                        srvrLog.Errorf("Unable to discover a UPnP enabled "+
×
863
                                "device on the local network: %v", err)
×
864

×
865
                        srvrLog.Info("Scanning local network for a NAT-PMP " +
×
866
                                "enabled device")
×
867

×
868
                        pmp, err := nat.DiscoverPMP(discoveryTimeout)
×
869
                        if err != nil {
×
870
                                err := fmt.Errorf("unable to discover a "+
×
871
                                        "NAT-PMP enabled device on the local "+
×
872
                                        "network: %v", err)
×
873
                                srvrLog.Error(err)
×
874
                                return nil, err
×
875
                        }
×
876

877
                        s.natTraversal = pmp
×
878
                }
879
        }
880

881
        // If we were requested to automatically configure port forwarding,
882
        // we'll use the ports that the server will be listening on.
883
        externalIPStrings := make([]string, len(cfg.ExternalIPs))
3✔
884
        for idx, ip := range cfg.ExternalIPs {
6✔
885
                externalIPStrings[idx] = ip.String()
3✔
886
        }
3✔
887
        if s.natTraversal != nil {
3✔
888
                listenPorts := make([]uint16, 0, len(listenAddrs))
×
889
                for _, listenAddr := range listenAddrs {
×
890
                        // At this point, the listen addresses should have
×
891
                        // already been normalized, so it's safe to ignore the
×
892
                        // errors.
×
893
                        _, portStr, _ := net.SplitHostPort(listenAddr.String())
×
894
                        port, _ := strconv.Atoi(portStr)
×
895

×
896
                        listenPorts = append(listenPorts, uint16(port))
×
897
                }
×
898

899
                ips, err := s.configurePortForwarding(listenPorts...)
×
900
                if err != nil {
×
901
                        srvrLog.Errorf("Unable to automatically set up port "+
×
902
                                "forwarding using %s: %v",
×
903
                                s.natTraversal.Name(), err)
×
904
                } else {
×
905
                        srvrLog.Infof("Automatically set up port forwarding "+
×
906
                                "using %s to advertise external IP",
×
907
                                s.natTraversal.Name())
×
908
                        externalIPStrings = append(externalIPStrings, ips...)
×
909
                }
×
910
        }
911

912
        // If external IP addresses have been specified, add those to the list
913
        // of this server's addresses.
914
        externalIPs, err := lncfg.NormalizeAddresses(
3✔
915
                externalIPStrings, strconv.Itoa(defaultPeerPort),
3✔
916
                cfg.net.ResolveTCPAddr,
3✔
917
        )
3✔
918
        if err != nil {
3✔
919
                return nil, err
×
920
        }
×
921

922
        selfAddrs := make([]net.Addr, 0, len(externalIPs))
3✔
923
        selfAddrs = append(selfAddrs, externalIPs...)
3✔
924

3✔
925
        // We'll now reconstruct a node announcement based on our current
3✔
926
        // configuration so we can send it out as a sort of heart beat within
3✔
927
        // the network.
3✔
928
        //
3✔
929
        // We'll start by parsing the node color from configuration.
3✔
930
        color, err := lncfg.ParseHexColor(cfg.Color)
3✔
931
        if err != nil {
3✔
932
                srvrLog.Errorf("unable to parse color: %v\n", err)
×
933
                return nil, err
×
934
        }
×
935

936
        // If no alias is provided, default to first 10 characters of public
937
        // key.
938
        alias := cfg.Alias
3✔
939
        if alias == "" {
6✔
940
                alias = hex.EncodeToString(serializedPubKey[:10])
3✔
941
        }
3✔
942
        nodeAlias, err := lnwire.NewNodeAlias(alias)
3✔
943
        if err != nil {
3✔
944
                return nil, err
×
945
        }
×
946
        selfNode := &models.LightningNode{
3✔
947
                HaveNodeAnnouncement: true,
3✔
948
                LastUpdate:           time.Now(),
3✔
949
                Addresses:            selfAddrs,
3✔
950
                Alias:                nodeAlias.String(),
3✔
951
                Features:             s.featureMgr.Get(feature.SetNodeAnn),
3✔
952
                Color:                color,
3✔
953
        }
3✔
954
        copy(selfNode.PubKeyBytes[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
955

3✔
956
        // Based on the disk representation of the node announcement generated
3✔
957
        // above, we'll generate a node announcement that can go out on the
3✔
958
        // network so we can properly sign it.
3✔
959
        nodeAnn, err := selfNode.NodeAnnouncement(false)
3✔
960
        if err != nil {
3✔
961
                return nil, fmt.Errorf("unable to gen self node ann: %w", err)
×
962
        }
×
963

964
        // With the announcement generated, we'll sign it to properly
965
        // authenticate the message on the network.
966
        authSig, err := netann.SignAnnouncement(
3✔
967
                s.nodeSigner, nodeKeyDesc.KeyLocator, nodeAnn,
3✔
968
        )
3✔
969
        if err != nil {
3✔
970
                return nil, fmt.Errorf("unable to generate signature for "+
×
971
                        "self node announcement: %v", err)
×
972
        }
×
973
        selfNode.AuthSigBytes = authSig.Serialize()
3✔
974
        nodeAnn.Signature, err = lnwire.NewSigFromECDSARawSignature(
3✔
975
                selfNode.AuthSigBytes,
3✔
976
        )
3✔
977
        if err != nil {
3✔
978
                return nil, err
×
979
        }
×
980

981
        // Finally, we'll update the representation on disk, and update our
982
        // cached in-memory version as well.
983
        if err := dbs.GraphDB.SetSourceNode(selfNode); err != nil {
3✔
984
                return nil, fmt.Errorf("can't set self node: %w", err)
×
985
        }
×
986
        s.currentNodeAnn = nodeAnn
3✔
987

3✔
988
        // The router will get access to the payment ID sequencer, such that it
3✔
989
        // can generate unique payment IDs.
3✔
990
        sequencer, err := htlcswitch.NewPersistentSequencer(dbs.ChanStateDB)
3✔
991
        if err != nil {
3✔
992
                return nil, err
×
993
        }
×
994

995
        // Instantiate mission control with config from the sub server.
996
        //
997
        // TODO(joostjager): When we are further in the process of moving to sub
998
        // servers, the mission control instance itself can be moved there too.
999
        routingConfig := routerrpc.GetRoutingConfig(cfg.SubRPCServers.RouterRPC)
3✔
1000

3✔
1001
        // We only initialize a probability estimator if there's no custom one.
3✔
1002
        var estimator routing.Estimator
3✔
1003
        if cfg.Estimator != nil {
3✔
1004
                estimator = cfg.Estimator
×
1005
        } else {
3✔
1006
                switch routingConfig.ProbabilityEstimatorType {
3✔
1007
                case routing.AprioriEstimatorName:
3✔
1008
                        aCfg := routingConfig.AprioriConfig
3✔
1009
                        aprioriConfig := routing.AprioriConfig{
3✔
1010
                                AprioriHopProbability: aCfg.HopProbability,
3✔
1011
                                PenaltyHalfLife:       aCfg.PenaltyHalfLife,
3✔
1012
                                AprioriWeight:         aCfg.Weight,
3✔
1013
                                CapacityFraction:      aCfg.CapacityFraction,
3✔
1014
                        }
3✔
1015

3✔
1016
                        estimator, err = routing.NewAprioriEstimator(
3✔
1017
                                aprioriConfig,
3✔
1018
                        )
3✔
1019
                        if err != nil {
3✔
1020
                                return nil, err
×
1021
                        }
×
1022

1023
                case routing.BimodalEstimatorName:
×
1024
                        bCfg := routingConfig.BimodalConfig
×
1025
                        bimodalConfig := routing.BimodalConfig{
×
1026
                                BimodalNodeWeight: bCfg.NodeWeight,
×
1027
                                BimodalScaleMsat: lnwire.MilliSatoshi(
×
1028
                                        bCfg.Scale,
×
1029
                                ),
×
1030
                                BimodalDecayTime: bCfg.DecayTime,
×
1031
                        }
×
1032

×
1033
                        estimator, err = routing.NewBimodalEstimator(
×
1034
                                bimodalConfig,
×
1035
                        )
×
1036
                        if err != nil {
×
1037
                                return nil, err
×
1038
                        }
×
1039

1040
                default:
×
1041
                        return nil, fmt.Errorf("unknown estimator type %v",
×
1042
                                routingConfig.ProbabilityEstimatorType)
×
1043
                }
1044
        }
1045

1046
        mcCfg := &routing.MissionControlConfig{
3✔
1047
                OnConfigUpdate:          fn.Some(s.UpdateRoutingConfig),
3✔
1048
                Estimator:               estimator,
3✔
1049
                MaxMcHistory:            routingConfig.MaxMcHistory,
3✔
1050
                McFlushInterval:         routingConfig.McFlushInterval,
3✔
1051
                MinFailureRelaxInterval: routing.DefaultMinFailureRelaxInterval,
3✔
1052
        }
3✔
1053

3✔
1054
        s.missionController, err = routing.NewMissionController(
3✔
1055
                dbs.ChanStateDB, selfNode.PubKeyBytes, mcCfg,
3✔
1056
        )
3✔
1057
        if err != nil {
3✔
1058
                return nil, fmt.Errorf("can't create mission control "+
×
1059
                        "manager: %w", err)
×
1060
        }
×
1061
        s.defaultMC, err = s.missionController.GetNamespacedStore(
3✔
1062
                routing.DefaultMissionControlNamespace,
3✔
1063
        )
3✔
1064
        if err != nil {
3✔
1065
                return nil, fmt.Errorf("can't create mission control in the "+
×
1066
                        "default namespace: %w", err)
×
1067
        }
×
1068

1069
        srvrLog.Debugf("Instantiating payment session source with config: "+
3✔
1070
                "AttemptCost=%v + %v%%, MinRouteProbability=%v",
3✔
1071
                int64(routingConfig.AttemptCost),
3✔
1072
                float64(routingConfig.AttemptCostPPM)/10000,
3✔
1073
                routingConfig.MinRouteProbability)
3✔
1074

3✔
1075
        pathFindingConfig := routing.PathFindingConfig{
3✔
1076
                AttemptCost: lnwire.NewMSatFromSatoshis(
3✔
1077
                        routingConfig.AttemptCost,
3✔
1078
                ),
3✔
1079
                AttemptCostPPM: routingConfig.AttemptCostPPM,
3✔
1080
                MinProbability: routingConfig.MinRouteProbability,
3✔
1081
        }
3✔
1082

3✔
1083
        sourceNode, err := dbs.GraphDB.SourceNode()
3✔
1084
        if err != nil {
3✔
1085
                return nil, fmt.Errorf("error getting source node: %w", err)
×
1086
        }
×
1087
        paymentSessionSource := &routing.SessionSource{
3✔
1088
                GraphSessionFactory: dbs.GraphDB,
3✔
1089
                SourceNode:          sourceNode,
3✔
1090
                MissionControl:      s.defaultMC,
3✔
1091
                GetLink:             s.htlcSwitch.GetLinkByShortID,
3✔
1092
                PathFindingConfig:   pathFindingConfig,
3✔
1093
        }
3✔
1094

3✔
1095
        paymentControl := channeldb.NewPaymentControl(dbs.ChanStateDB)
3✔
1096

3✔
1097
        s.controlTower = routing.NewControlTower(paymentControl)
3✔
1098

3✔
1099
        strictPruning := cfg.Bitcoin.Node == "neutrino" ||
3✔
1100
                cfg.Routing.StrictZombiePruning
3✔
1101

3✔
1102
        s.graphBuilder, err = graph.NewBuilder(&graph.Config{
3✔
1103
                SelfNode:            selfNode.PubKeyBytes,
3✔
1104
                Graph:               dbs.GraphDB,
3✔
1105
                Chain:               cc.ChainIO,
3✔
1106
                ChainView:           cc.ChainView,
3✔
1107
                Notifier:            cc.ChainNotifier,
3✔
1108
                ChannelPruneExpiry:  graph.DefaultChannelPruneExpiry,
3✔
1109
                GraphPruneInterval:  time.Hour,
3✔
1110
                FirstTimePruneDelay: graph.DefaultFirstTimePruneDelay,
3✔
1111
                AssumeChannelValid:  cfg.Routing.AssumeChannelValid,
3✔
1112
                StrictZombiePruning: strictPruning,
3✔
1113
                IsAlias:             aliasmgr.IsAlias,
3✔
1114
        })
3✔
1115
        if err != nil {
3✔
1116
                return nil, fmt.Errorf("can't create graph builder: %w", err)
×
1117
        }
×
1118

1119
        s.chanRouter, err = routing.New(routing.Config{
3✔
1120
                SelfNode:           selfNode.PubKeyBytes,
3✔
1121
                RoutingGraph:       dbs.GraphDB,
3✔
1122
                Chain:              cc.ChainIO,
3✔
1123
                Payer:              s.htlcSwitch,
3✔
1124
                Control:            s.controlTower,
3✔
1125
                MissionControl:     s.defaultMC,
3✔
1126
                SessionSource:      paymentSessionSource,
3✔
1127
                GetLink:            s.htlcSwitch.GetLinkByShortID,
3✔
1128
                NextPaymentID:      sequencer.NextID,
3✔
1129
                PathFindingConfig:  pathFindingConfig,
3✔
1130
                Clock:              clock.NewDefaultClock(),
3✔
1131
                ApplyChannelUpdate: s.graphBuilder.ApplyChannelUpdate,
3✔
1132
                ClosedSCIDs:        s.fetchClosedChannelSCIDs(),
3✔
1133
                TrafficShaper:      implCfg.TrafficShaper,
3✔
1134
        })
3✔
1135
        if err != nil {
3✔
1136
                return nil, fmt.Errorf("can't create router: %w", err)
×
1137
        }
×
1138

1139
        chanSeries := discovery.NewChanSeries(s.graphDB)
3✔
1140
        gossipMessageStore, err := discovery.NewMessageStore(dbs.ChanStateDB)
3✔
1141
        if err != nil {
3✔
1142
                return nil, err
×
1143
        }
×
1144
        waitingProofStore, err := channeldb.NewWaitingProofStore(dbs.ChanStateDB)
3✔
1145
        if err != nil {
3✔
1146
                return nil, err
×
1147
        }
×
1148

1149
        scidCloserMan := discovery.NewScidCloserMan(s.graphDB, s.chanStateDB)
3✔
1150

3✔
1151
        s.authGossiper = discovery.New(discovery.Config{
3✔
1152
                Graph:                 s.graphBuilder,
3✔
1153
                ChainIO:               s.cc.ChainIO,
3✔
1154
                Notifier:              s.cc.ChainNotifier,
3✔
1155
                ChainHash:             *s.cfg.ActiveNetParams.GenesisHash,
3✔
1156
                Broadcast:             s.BroadcastMessage,
3✔
1157
                ChanSeries:            chanSeries,
3✔
1158
                NotifyWhenOnline:      s.NotifyWhenOnline,
3✔
1159
                NotifyWhenOffline:     s.NotifyWhenOffline,
3✔
1160
                FetchSelfAnnouncement: s.getNodeAnnouncement,
3✔
1161
                UpdateSelfAnnouncement: func() (lnwire.NodeAnnouncement,
3✔
1162
                        error) {
3✔
1163

×
1164
                        return s.genNodeAnnouncement(nil)
×
1165
                },
×
1166
                ProofMatureDelta:        cfg.Gossip.AnnouncementConf,
1167
                TrickleDelay:            time.Millisecond * time.Duration(cfg.TrickleDelay),
1168
                RetransmitTicker:        ticker.New(time.Minute * 30),
1169
                RebroadcastInterval:     time.Hour * 24,
1170
                WaitingProofStore:       waitingProofStore,
1171
                MessageStore:            gossipMessageStore,
1172
                AnnSigner:               s.nodeSigner,
1173
                RotateTicker:            ticker.New(discovery.DefaultSyncerRotationInterval),
1174
                HistoricalSyncTicker:    ticker.New(cfg.HistoricalSyncInterval),
1175
                NumActiveSyncers:        cfg.NumGraphSyncPeers,
1176
                NoTimestampQueries:      cfg.ProtocolOptions.NoTimestampQueryOption, //nolint:ll
1177
                MinimumBatchSize:        10,
1178
                SubBatchDelay:           cfg.Gossip.SubBatchDelay,
1179
                IgnoreHistoricalFilters: cfg.IgnoreHistoricalGossipFilters,
1180
                PinnedSyncers:           cfg.Gossip.PinnedSyncers,
1181
                MaxChannelUpdateBurst:   cfg.Gossip.MaxChannelUpdateBurst,
1182
                ChannelUpdateInterval:   cfg.Gossip.ChannelUpdateInterval,
1183
                IsAlias:                 aliasmgr.IsAlias,
1184
                SignAliasUpdate:         s.signAliasUpdate,
1185
                FindBaseByAlias:         s.aliasMgr.FindBaseSCID,
1186
                GetAlias:                s.aliasMgr.GetPeerAlias,
1187
                FindChannel:             s.findChannel,
1188
                IsStillZombieChannel:    s.graphBuilder.IsZombieChannel,
1189
                ScidCloser:              scidCloserMan,
1190
                AssumeChannelValid:      cfg.Routing.AssumeChannelValid,
1191
        }, nodeKeyDesc)
1192

1193
        accessCfg := &accessManConfig{
3✔
1194
                initAccessPerms: func() (map[string]channeldb.ChanCount,
3✔
1195
                        error) {
6✔
1196

3✔
1197
                        genesisHash := *s.cfg.ActiveNetParams.GenesisHash
3✔
1198
                        return s.chanStateDB.FetchPermAndTempPeers(
3✔
1199
                                genesisHash[:],
3✔
1200
                        )
3✔
1201
                },
3✔
1202
                shouldDisconnect:   s.authGossiper.ShouldDisconnect,
1203
                maxRestrictedSlots: int64(s.cfg.NumRestrictedSlots),
1204
        }
1205

1206
        peerAccessMan, err := newAccessMan(accessCfg)
3✔
1207
        if err != nil {
3✔
1208
                return nil, err
×
1209
        }
×
1210

1211
        s.peerAccessMan = peerAccessMan
3✔
1212

3✔
1213
        selfVertex := route.Vertex(nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1214
        //nolint:ll
3✔
1215
        s.localChanMgr = &localchans.Manager{
3✔
1216
                SelfPub:              nodeKeyDesc.PubKey,
3✔
1217
                DefaultRoutingPolicy: cc.RoutingPolicy,
3✔
1218
                ForAllOutgoingChannels: func(cb func(*models.ChannelEdgeInfo,
3✔
1219
                        *models.ChannelEdgePolicy) error) error {
6✔
1220

3✔
1221
                        return s.graphDB.ForEachNodeChannel(selfVertex,
3✔
1222
                                func(_ kvdb.RTx, c *models.ChannelEdgeInfo,
3✔
1223
                                        e *models.ChannelEdgePolicy,
3✔
1224
                                        _ *models.ChannelEdgePolicy) error {
6✔
1225

3✔
1226
                                        // NOTE: The invoked callback here may
3✔
1227
                                        // receive a nil channel policy.
3✔
1228
                                        return cb(c, e)
3✔
1229
                                },
3✔
1230
                        )
1231
                },
1232
                PropagateChanPolicyUpdate: s.authGossiper.PropagateChanPolicyUpdate,
1233
                UpdateForwardingPolicies:  s.htlcSwitch.UpdateForwardingPolicies,
1234
                FetchChannel:              s.chanStateDB.FetchChannel,
1235
                AddEdge: func(edge *models.ChannelEdgeInfo) error {
×
1236
                        return s.graphBuilder.AddEdge(edge)
×
1237
                },
×
1238
        }
1239

1240
        utxnStore, err := contractcourt.NewNurseryStore(
3✔
1241
                s.cfg.ActiveNetParams.GenesisHash, dbs.ChanStateDB,
3✔
1242
        )
3✔
1243
        if err != nil {
3✔
1244
                srvrLog.Errorf("unable to create nursery store: %v", err)
×
1245
                return nil, err
×
1246
        }
×
1247

1248
        sweeperStore, err := sweep.NewSweeperStore(
3✔
1249
                dbs.ChanStateDB, s.cfg.ActiveNetParams.GenesisHash,
3✔
1250
        )
3✔
1251
        if err != nil {
3✔
1252
                srvrLog.Errorf("unable to create sweeper store: %v", err)
×
1253
                return nil, err
×
1254
        }
×
1255

1256
        aggregator := sweep.NewBudgetAggregator(
3✔
1257
                cc.FeeEstimator, sweep.DefaultMaxInputsPerTx,
3✔
1258
                s.implCfg.AuxSweeper,
3✔
1259
        )
3✔
1260

3✔
1261
        s.txPublisher = sweep.NewTxPublisher(sweep.TxPublisherConfig{
3✔
1262
                Signer:     cc.Wallet.Cfg.Signer,
3✔
1263
                Wallet:     cc.Wallet,
3✔
1264
                Estimator:  cc.FeeEstimator,
3✔
1265
                Notifier:   cc.ChainNotifier,
3✔
1266
                AuxSweeper: s.implCfg.AuxSweeper,
3✔
1267
        })
3✔
1268

3✔
1269
        s.sweeper = sweep.New(&sweep.UtxoSweeperConfig{
3✔
1270
                FeeEstimator: cc.FeeEstimator,
3✔
1271
                GenSweepScript: newSweepPkScriptGen(
3✔
1272
                        cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1273
                ),
3✔
1274
                Signer:               cc.Wallet.Cfg.Signer,
3✔
1275
                Wallet:               newSweeperWallet(cc.Wallet),
3✔
1276
                Mempool:              cc.MempoolNotifier,
3✔
1277
                Notifier:             cc.ChainNotifier,
3✔
1278
                Store:                sweeperStore,
3✔
1279
                MaxInputsPerTx:       sweep.DefaultMaxInputsPerTx,
3✔
1280
                MaxFeeRate:           cfg.Sweeper.MaxFeeRate,
3✔
1281
                Aggregator:           aggregator,
3✔
1282
                Publisher:            s.txPublisher,
3✔
1283
                NoDeadlineConfTarget: cfg.Sweeper.NoDeadlineConfTarget,
3✔
1284
        })
3✔
1285

3✔
1286
        s.utxoNursery = contractcourt.NewUtxoNursery(&contractcourt.NurseryConfig{
3✔
1287
                ChainIO:             cc.ChainIO,
3✔
1288
                ConfDepth:           1,
3✔
1289
                FetchClosedChannels: s.chanStateDB.FetchClosedChannels,
3✔
1290
                FetchClosedChannel:  s.chanStateDB.FetchClosedChannel,
3✔
1291
                Notifier:            cc.ChainNotifier,
3✔
1292
                PublishTransaction:  cc.Wallet.PublishTransaction,
3✔
1293
                Store:               utxnStore,
3✔
1294
                SweepInput:          s.sweeper.SweepInput,
3✔
1295
                Budget:              s.cfg.Sweeper.Budget,
3✔
1296
        })
3✔
1297

3✔
1298
        // Construct a closure that wraps the htlcswitch's CloseLink method.
3✔
1299
        closeLink := func(chanPoint *wire.OutPoint,
3✔
1300
                closureType contractcourt.ChannelCloseType) {
6✔
1301
                // TODO(conner): Properly respect the update and error channels
3✔
1302
                // returned by CloseLink.
3✔
1303

3✔
1304
                // Instruct the switch to close the channel.  Provide no close out
3✔
1305
                // delivery script or target fee per kw because user input is not
3✔
1306
                // available when the remote peer closes the channel.
3✔
1307
                s.htlcSwitch.CloseLink(
3✔
1308
                        context.Background(), chanPoint, closureType, 0, 0, nil,
3✔
1309
                )
3✔
1310
        }
3✔
1311

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

3✔
1316
        s.breachArbitrator = contractcourt.NewBreachArbitrator(
3✔
1317
                &contractcourt.BreachConfig{
3✔
1318
                        CloseLink: closeLink,
3✔
1319
                        DB:        s.chanStateDB,
3✔
1320
                        Estimator: s.cc.FeeEstimator,
3✔
1321
                        GenSweepScript: newSweepPkScriptGen(
3✔
1322
                                cc.Wallet, s.cfg.ActiveNetParams.Params,
3✔
1323
                        ),
3✔
1324
                        Notifier:           cc.ChainNotifier,
3✔
1325
                        PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1326
                        ContractBreaches:   contractBreaches,
3✔
1327
                        Signer:             cc.Wallet.Cfg.Signer,
3✔
1328
                        Store: contractcourt.NewRetributionStore(
3✔
1329
                                dbs.ChanStateDB,
3✔
1330
                        ),
3✔
1331
                        AuxSweeper: s.implCfg.AuxSweeper,
3✔
1332
                },
3✔
1333
        )
3✔
1334

3✔
1335
        //nolint:ll
3✔
1336
        s.chainArb = contractcourt.NewChainArbitrator(contractcourt.ChainArbitratorConfig{
3✔
1337
                ChainHash:              *s.cfg.ActiveNetParams.GenesisHash,
3✔
1338
                IncomingBroadcastDelta: lncfg.DefaultIncomingBroadcastDelta,
3✔
1339
                OutgoingBroadcastDelta: lncfg.DefaultOutgoingBroadcastDelta,
3✔
1340
                NewSweepAddr: func() ([]byte, error) {
3✔
1341
                        addr, err := newSweepPkScriptGen(
×
1342
                                cc.Wallet, netParams,
×
1343
                        )().Unpack()
×
1344
                        if err != nil {
×
1345
                                return nil, err
×
1346
                        }
×
1347

1348
                        return addr.DeliveryAddress, nil
×
1349
                },
1350
                PublishTx: cc.Wallet.PublishTransaction,
1351
                DeliverResolutionMsg: func(msgs ...contractcourt.ResolutionMsg) error {
3✔
1352
                        for _, msg := range msgs {
6✔
1353
                                err := s.htlcSwitch.ProcessContractResolution(msg)
3✔
1354
                                if err != nil {
3✔
1355
                                        return err
×
1356
                                }
×
1357
                        }
1358
                        return nil
3✔
1359
                },
1360
                IncubateOutputs: func(chanPoint wire.OutPoint,
1361
                        outHtlcRes fn.Option[lnwallet.OutgoingHtlcResolution],
1362
                        inHtlcRes fn.Option[lnwallet.IncomingHtlcResolution],
1363
                        broadcastHeight uint32,
1364
                        deadlineHeight fn.Option[int32]) error {
3✔
1365

3✔
1366
                        return s.utxoNursery.IncubateOutputs(
3✔
1367
                                chanPoint, outHtlcRes, inHtlcRes,
3✔
1368
                                broadcastHeight, deadlineHeight,
3✔
1369
                        )
3✔
1370
                },
3✔
1371
                PreimageDB:   s.witnessBeacon,
1372
                Notifier:     cc.ChainNotifier,
1373
                Mempool:      cc.MempoolNotifier,
1374
                Signer:       cc.Wallet.Cfg.Signer,
1375
                FeeEstimator: cc.FeeEstimator,
1376
                ChainIO:      cc.ChainIO,
1377
                MarkLinkInactive: func(chanPoint wire.OutPoint) error {
3✔
1378
                        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1379
                        s.htlcSwitch.RemoveLink(chanID)
3✔
1380
                        return nil
3✔
1381
                },
3✔
1382
                IsOurAddress: cc.Wallet.IsOurAddress,
1383
                ContractBreach: func(chanPoint wire.OutPoint,
1384
                        breachRet *lnwallet.BreachRetribution) error {
3✔
1385

3✔
1386
                        // processACK will handle the BreachArbitrator ACKing
3✔
1387
                        // the event.
3✔
1388
                        finalErr := make(chan error, 1)
3✔
1389
                        processACK := func(brarErr error) {
6✔
1390
                                if brarErr != nil {
3✔
1391
                                        finalErr <- brarErr
×
1392
                                        return
×
1393
                                }
×
1394

1395
                                // If the BreachArbitrator successfully handled
1396
                                // the event, we can signal that the handoff
1397
                                // was successful.
1398
                                finalErr <- nil
3✔
1399
                        }
1400

1401
                        event := &contractcourt.ContractBreachEvent{
3✔
1402
                                ChanPoint:         chanPoint,
3✔
1403
                                ProcessACK:        processACK,
3✔
1404
                                BreachRetribution: breachRet,
3✔
1405
                        }
3✔
1406

3✔
1407
                        // Send the contract breach event to the
3✔
1408
                        // BreachArbitrator.
3✔
1409
                        select {
3✔
1410
                        case contractBreaches <- event:
3✔
1411
                        case <-s.quit:
×
1412
                                return ErrServerShuttingDown
×
1413
                        }
1414

1415
                        // We'll wait for a final error to be available from
1416
                        // the BreachArbitrator.
1417
                        select {
3✔
1418
                        case err := <-finalErr:
3✔
1419
                                return err
3✔
1420
                        case <-s.quit:
×
1421
                                return ErrServerShuttingDown
×
1422
                        }
1423
                },
1424
                DisableChannel: func(chanPoint wire.OutPoint) error {
3✔
1425
                        return s.chanStatusMgr.RequestDisable(chanPoint, false)
3✔
1426
                },
3✔
1427
                Sweeper:                       s.sweeper,
1428
                Registry:                      s.invoices,
1429
                NotifyClosedChannel:           s.channelNotifier.NotifyClosedChannelEvent,
1430
                NotifyFullyResolvedChannel:    s.channelNotifier.NotifyFullyResolvedChannelEvent,
1431
                OnionProcessor:                s.sphinx,
1432
                PaymentsExpirationGracePeriod: cfg.PaymentsExpirationGracePeriod,
1433
                IsForwardedHTLC:               s.htlcSwitch.IsForwardedHTLC,
1434
                Clock:                         clock.NewDefaultClock(),
1435
                SubscribeBreachComplete:       s.breachArbitrator.SubscribeBreachComplete,
1436
                PutFinalHtlcOutcome:           s.chanStateDB.PutOnchainFinalHtlcOutcome,
1437
                HtlcNotifier:                  s.htlcNotifier,
1438
                Budget:                        *s.cfg.Sweeper.Budget,
1439

1440
                // TODO(yy): remove this hack once PaymentCircuit is interfaced.
1441
                QueryIncomingCircuit: func(
1442
                        circuit models.CircuitKey) *models.CircuitKey {
3✔
1443

3✔
1444
                        // Get the circuit map.
3✔
1445
                        circuits := s.htlcSwitch.CircuitLookup()
3✔
1446

3✔
1447
                        // Lookup the outgoing circuit.
3✔
1448
                        pc := circuits.LookupOpenCircuit(circuit)
3✔
1449
                        if pc == nil {
5✔
1450
                                return nil
2✔
1451
                        }
2✔
1452

1453
                        return &pc.Incoming
3✔
1454
                },
1455
                AuxLeafStore: implCfg.AuxLeafStore,
1456
                AuxSigner:    implCfg.AuxSigner,
1457
                AuxResolver:  implCfg.AuxContractResolver,
1458
        }, dbs.ChanStateDB)
1459

1460
        // Select the configuration and funding parameters for Bitcoin.
1461
        chainCfg := cfg.Bitcoin
3✔
1462
        minRemoteDelay := funding.MinBtcRemoteDelay
3✔
1463
        maxRemoteDelay := funding.MaxBtcRemoteDelay
3✔
1464

3✔
1465
        var chanIDSeed [32]byte
3✔
1466
        if _, err := rand.Read(chanIDSeed[:]); err != nil {
3✔
1467
                return nil, err
×
1468
        }
×
1469

1470
        // Wrap the DeleteChannelEdges method so that the funding manager can
1471
        // use it without depending on several layers of indirection.
1472
        deleteAliasEdge := func(scid lnwire.ShortChannelID) (
3✔
1473
                *models.ChannelEdgePolicy, error) {
6✔
1474

3✔
1475
                info, e1, e2, err := s.graphDB.FetchChannelEdgesByID(
3✔
1476
                        scid.ToUint64(),
3✔
1477
                )
3✔
1478
                if errors.Is(err, graphdb.ErrEdgeNotFound) {
3✔
1479
                        // This is unlikely but there is a slim chance of this
×
1480
                        // being hit if lnd was killed via SIGKILL and the
×
1481
                        // funding manager was stepping through the delete
×
1482
                        // alias edge logic.
×
1483
                        return nil, nil
×
1484
                } else if err != nil {
3✔
1485
                        return nil, err
×
1486
                }
×
1487

1488
                // Grab our key to find our policy.
1489
                var ourKey [33]byte
3✔
1490
                copy(ourKey[:], nodeKeyDesc.PubKey.SerializeCompressed())
3✔
1491

3✔
1492
                var ourPolicy *models.ChannelEdgePolicy
3✔
1493
                if info != nil && info.NodeKey1Bytes == ourKey {
6✔
1494
                        ourPolicy = e1
3✔
1495
                } else {
6✔
1496
                        ourPolicy = e2
3✔
1497
                }
3✔
1498

1499
                if ourPolicy == nil {
3✔
1500
                        // Something is wrong, so return an error.
×
1501
                        return nil, fmt.Errorf("we don't have an edge")
×
1502
                }
×
1503

1504
                err = s.graphDB.DeleteChannelEdges(
3✔
1505
                        false, false, scid.ToUint64(),
3✔
1506
                )
3✔
1507
                return ourPolicy, err
3✔
1508
        }
1509

1510
        // For the reservationTimeout and the zombieSweeperInterval different
1511
        // values are set in case we are in a dev environment so enhance test
1512
        // capacilities.
1513
        reservationTimeout := chanfunding.DefaultReservationTimeout
3✔
1514
        zombieSweeperInterval := lncfg.DefaultZombieSweeperInterval
3✔
1515

3✔
1516
        // Get the development config for funding manager. If we are not in
3✔
1517
        // development mode, this would be nil.
3✔
1518
        var devCfg *funding.DevConfig
3✔
1519
        if lncfg.IsDevBuild() {
6✔
1520
                devCfg = &funding.DevConfig{
3✔
1521
                        ProcessChannelReadyWait: cfg.Dev.ChannelReadyWait(),
3✔
1522
                        MaxWaitNumBlocksFundingConf: cfg.Dev.
3✔
1523
                                GetMaxWaitNumBlocksFundingConf(),
3✔
1524
                }
3✔
1525

3✔
1526
                reservationTimeout = cfg.Dev.GetReservationTimeout()
3✔
1527
                zombieSweeperInterval = cfg.Dev.GetZombieSweeperInterval()
3✔
1528

3✔
1529
                srvrLog.Debugf("Using the dev config for the fundingMgr: %v, "+
3✔
1530
                        "reservationTimeout=%v, zombieSweeperInterval=%v",
3✔
1531
                        devCfg, reservationTimeout, zombieSweeperInterval)
3✔
1532
        }
3✔
1533

1534
        //nolint:ll
1535
        s.fundingMgr, err = funding.NewFundingManager(funding.Config{
3✔
1536
                Dev:                devCfg,
3✔
1537
                NoWumboChans:       !cfg.ProtocolOptions.Wumbo(),
3✔
1538
                IDKey:              nodeKeyDesc.PubKey,
3✔
1539
                IDKeyLoc:           nodeKeyDesc.KeyLocator,
3✔
1540
                Wallet:             cc.Wallet,
3✔
1541
                PublishTransaction: cc.Wallet.PublishTransaction,
3✔
1542
                UpdateLabel: func(hash chainhash.Hash, label string) error {
6✔
1543
                        return cc.Wallet.LabelTransaction(hash, label, true)
3✔
1544
                },
3✔
1545
                Notifier:     cc.ChainNotifier,
1546
                ChannelDB:    s.chanStateDB,
1547
                FeeEstimator: cc.FeeEstimator,
1548
                SignMessage:  cc.MsgSigner.SignMessage,
1549
                CurrentNodeAnnouncement: func() (lnwire.NodeAnnouncement,
1550
                        error) {
3✔
1551

3✔
1552
                        return s.genNodeAnnouncement(nil)
3✔
1553
                },
3✔
1554
                SendAnnouncement:     s.authGossiper.ProcessLocalAnnouncement,
1555
                NotifyWhenOnline:     s.NotifyWhenOnline,
1556
                TempChanIDSeed:       chanIDSeed,
1557
                FindChannel:          s.findChannel,
1558
                DefaultRoutingPolicy: cc.RoutingPolicy,
1559
                DefaultMinHtlcIn:     cc.MinHtlcIn,
1560
                NumRequiredConfs: func(chanAmt btcutil.Amount,
1561
                        pushAmt lnwire.MilliSatoshi) uint16 {
3✔
1562
                        // For large channels we increase the number
3✔
1563
                        // of confirmations we require for the
3✔
1564
                        // channel to be considered open. As it is
3✔
1565
                        // always the responder that gets to choose
3✔
1566
                        // value, the pushAmt is value being pushed
3✔
1567
                        // to us. This means we have more to lose
3✔
1568
                        // in the case this gets re-orged out, and
3✔
1569
                        // we will require more confirmations before
3✔
1570
                        // we consider it open.
3✔
1571

3✔
1572
                        // In case the user has explicitly specified
3✔
1573
                        // a default value for the number of
3✔
1574
                        // confirmations, we use it.
3✔
1575
                        defaultConf := uint16(chainCfg.DefaultNumChanConfs)
3✔
1576
                        if defaultConf != 0 {
6✔
1577
                                return defaultConf
3✔
1578
                        }
3✔
1579

1580
                        minConf := uint64(3)
×
1581
                        maxConf := uint64(6)
×
1582

×
1583
                        // If this is a wumbo channel, then we'll require the
×
1584
                        // max amount of confirmations.
×
1585
                        if chanAmt > MaxFundingAmount {
×
1586
                                return uint16(maxConf)
×
1587
                        }
×
1588

1589
                        // If not we return a value scaled linearly
1590
                        // between 3 and 6, depending on channel size.
1591
                        // TODO(halseth): Use 1 as minimum?
1592
                        maxChannelSize := uint64(
×
1593
                                lnwire.NewMSatFromSatoshis(MaxFundingAmount))
×
1594
                        stake := lnwire.NewMSatFromSatoshis(chanAmt) + pushAmt
×
1595
                        conf := maxConf * uint64(stake) / maxChannelSize
×
1596
                        if conf < minConf {
×
1597
                                conf = minConf
×
1598
                        }
×
1599
                        if conf > maxConf {
×
1600
                                conf = maxConf
×
1601
                        }
×
1602
                        return uint16(conf)
×
1603
                },
1604
                RequiredRemoteDelay: func(chanAmt btcutil.Amount) uint16 {
3✔
1605
                        // We scale the remote CSV delay (the time the
3✔
1606
                        // remote have to claim funds in case of a unilateral
3✔
1607
                        // close) linearly from minRemoteDelay blocks
3✔
1608
                        // for small channels, to maxRemoteDelay blocks
3✔
1609
                        // for channels of size MaxFundingAmount.
3✔
1610

3✔
1611
                        // In case the user has explicitly specified
3✔
1612
                        // a default value for the remote delay, we
3✔
1613
                        // use it.
3✔
1614
                        defaultDelay := uint16(chainCfg.DefaultRemoteDelay)
3✔
1615
                        if defaultDelay > 0 {
6✔
1616
                                return defaultDelay
3✔
1617
                        }
3✔
1618

1619
                        // If this is a wumbo channel, then we'll require the
1620
                        // max value.
1621
                        if chanAmt > MaxFundingAmount {
×
1622
                                return maxRemoteDelay
×
1623
                        }
×
1624

1625
                        // If not we scale according to channel size.
1626
                        delay := uint16(btcutil.Amount(maxRemoteDelay) *
×
1627
                                chanAmt / MaxFundingAmount)
×
1628
                        if delay < minRemoteDelay {
×
1629
                                delay = minRemoteDelay
×
1630
                        }
×
1631
                        if delay > maxRemoteDelay {
×
1632
                                delay = maxRemoteDelay
×
1633
                        }
×
1634
                        return delay
×
1635
                },
1636
                WatchNewChannel: func(channel *channeldb.OpenChannel,
1637
                        peerKey *btcec.PublicKey) error {
3✔
1638

3✔
1639
                        // First, we'll mark this new peer as a persistent peer
3✔
1640
                        // for re-connection purposes. If the peer is not yet
3✔
1641
                        // tracked or the user hasn't requested it to be perm,
3✔
1642
                        // we'll set false to prevent the server from continuing
3✔
1643
                        // to connect to this peer even if the number of
3✔
1644
                        // channels with this peer is zero.
3✔
1645
                        s.mu.Lock()
3✔
1646
                        pubStr := string(peerKey.SerializeCompressed())
3✔
1647
                        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
1648
                                s.persistentPeers[pubStr] = false
3✔
1649
                        }
3✔
1650
                        s.mu.Unlock()
3✔
1651

3✔
1652
                        // With that taken care of, we'll send this channel to
3✔
1653
                        // the chain arb so it can react to on-chain events.
3✔
1654
                        return s.chainArb.WatchNewChannel(channel)
3✔
1655
                },
1656
                ReportShortChanID: func(chanPoint wire.OutPoint) error {
3✔
1657
                        cid := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
1658
                        return s.htlcSwitch.UpdateShortChanID(cid)
3✔
1659
                },
3✔
1660
                RequiredRemoteChanReserve: func(chanAmt,
1661
                        dustLimit btcutil.Amount) btcutil.Amount {
3✔
1662

3✔
1663
                        // By default, we'll require the remote peer to maintain
3✔
1664
                        // at least 1% of the total channel capacity at all
3✔
1665
                        // times. If this value ends up dipping below the dust
3✔
1666
                        // limit, then we'll use the dust limit itself as the
3✔
1667
                        // reserve as required by BOLT #2.
3✔
1668
                        reserve := chanAmt / 100
3✔
1669
                        if reserve < dustLimit {
6✔
1670
                                reserve = dustLimit
3✔
1671
                        }
3✔
1672

1673
                        return reserve
3✔
1674
                },
1675
                RequiredRemoteMaxValue: func(chanAmt btcutil.Amount) lnwire.MilliSatoshi {
3✔
1676
                        // By default, we'll allow the remote peer to fully
3✔
1677
                        // utilize the full bandwidth of the channel, minus our
3✔
1678
                        // required reserve.
3✔
1679
                        reserve := lnwire.NewMSatFromSatoshis(chanAmt / 100)
3✔
1680
                        return lnwire.NewMSatFromSatoshis(chanAmt) - reserve
3✔
1681
                },
3✔
1682
                RequiredRemoteMaxHTLCs: func(chanAmt btcutil.Amount) uint16 {
3✔
1683
                        if cfg.DefaultRemoteMaxHtlcs > 0 {
6✔
1684
                                return cfg.DefaultRemoteMaxHtlcs
3✔
1685
                        }
3✔
1686

1687
                        // By default, we'll permit them to utilize the full
1688
                        // channel bandwidth.
1689
                        return uint16(input.MaxHTLCNumber / 2)
×
1690
                },
1691
                ZombieSweeperInterval:         zombieSweeperInterval,
1692
                ReservationTimeout:            reservationTimeout,
1693
                MinChanSize:                   btcutil.Amount(cfg.MinChanSize),
1694
                MaxChanSize:                   btcutil.Amount(cfg.MaxChanSize),
1695
                MaxPendingChannels:            cfg.MaxPendingChannels,
1696
                RejectPush:                    cfg.RejectPush,
1697
                MaxLocalCSVDelay:              chainCfg.MaxLocalDelay,
1698
                NotifyOpenChannelEvent:        s.notifyOpenChannelPeerEvent,
1699
                OpenChannelPredicate:          chanPredicate,
1700
                NotifyPendingOpenChannelEvent: s.notifyPendingOpenChannelPeerEvent,
1701
                NotifyFundingTimeout:          s.notifyFundingTimeoutPeerEvent,
1702
                EnableUpfrontShutdown:         cfg.EnableUpfrontShutdown,
1703
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
1704
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
1705
                DeleteAliasEdge:      deleteAliasEdge,
1706
                AliasManager:         s.aliasMgr,
1707
                IsSweeperOutpoint:    s.sweeper.IsSweeperOutpoint,
1708
                AuxFundingController: implCfg.AuxFundingController,
1709
                AuxSigner:            implCfg.AuxSigner,
1710
                AuxResolver:          implCfg.AuxContractResolver,
1711
        })
1712
        if err != nil {
3✔
1713
                return nil, err
×
1714
        }
×
1715

1716
        // Next, we'll assemble the sub-system that will maintain an on-disk
1717
        // static backup of the latest channel state.
1718
        chanNotifier := &channelNotifier{
3✔
1719
                chanNotifier: s.channelNotifier,
3✔
1720
                addrs:        s.addrSource,
3✔
1721
        }
3✔
1722
        backupFile := chanbackup.NewMultiFile(
3✔
1723
                cfg.BackupFilePath, cfg.NoBackupArchive,
3✔
1724
        )
3✔
1725
        startingChans, err := chanbackup.FetchStaticChanBackups(
3✔
1726
                s.chanStateDB, s.addrSource,
3✔
1727
        )
3✔
1728
        if err != nil {
3✔
1729
                return nil, err
×
1730
        }
×
1731
        s.chanSubSwapper, err = chanbackup.NewSubSwapper(
3✔
1732
                startingChans, chanNotifier, s.cc.KeyRing, backupFile,
3✔
1733
        )
3✔
1734
        if err != nil {
3✔
1735
                return nil, err
×
1736
        }
×
1737

1738
        // Assemble a peer notifier which will provide clients with subscriptions
1739
        // to peer online and offline events.
1740
        s.peerNotifier = peernotifier.New()
3✔
1741

3✔
1742
        // Create a channel event store which monitors all open channels.
3✔
1743
        s.chanEventStore = chanfitness.NewChannelEventStore(&chanfitness.Config{
3✔
1744
                SubscribeChannelEvents: func() (subscribe.Subscription, error) {
6✔
1745
                        return s.channelNotifier.SubscribeChannelEvents()
3✔
1746
                },
3✔
1747
                SubscribePeerEvents: func() (subscribe.Subscription, error) {
3✔
1748
                        return s.peerNotifier.SubscribePeerEvents()
3✔
1749
                },
3✔
1750
                GetOpenChannels: s.chanStateDB.FetchAllOpenChannels,
1751
                Clock:           clock.NewDefaultClock(),
1752
                ReadFlapCount:   s.miscDB.ReadFlapCount,
1753
                WriteFlapCount:  s.miscDB.WriteFlapCounts,
1754
                FlapCountTicker: ticker.New(chanfitness.FlapCountFlushRate),
1755
        })
1756

1757
        if cfg.WtClient.Active {
6✔
1758
                policy := wtpolicy.DefaultPolicy()
3✔
1759
                policy.MaxUpdates = cfg.WtClient.MaxUpdates
3✔
1760

3✔
1761
                // We expose the sweep fee rate in sat/vbyte, but the tower
3✔
1762
                // protocol operations on sat/kw.
3✔
1763
                sweepRateSatPerVByte := chainfee.SatPerKVByte(
3✔
1764
                        1000 * cfg.WtClient.SweepFeeRate,
3✔
1765
                )
3✔
1766

3✔
1767
                policy.SweepFeeRate = sweepRateSatPerVByte.FeePerKWeight()
3✔
1768

3✔
1769
                if err := policy.Validate(); err != nil {
3✔
1770
                        return nil, err
×
1771
                }
×
1772

1773
                // authDial is the wrapper around the btrontide.Dial for the
1774
                // watchtower.
1775
                authDial := func(localKey keychain.SingleKeyECDH,
3✔
1776
                        netAddr *lnwire.NetAddress,
3✔
1777
                        dialer tor.DialFunc) (wtserver.Peer, error) {
6✔
1778

3✔
1779
                        return brontide.Dial(
3✔
1780
                                localKey, netAddr, cfg.ConnectionTimeout, dialer,
3✔
1781
                        )
3✔
1782
                }
3✔
1783

1784
                // buildBreachRetribution is a call-back that can be used to
1785
                // query the BreachRetribution info and channel type given a
1786
                // channel ID and commitment height.
1787
                buildBreachRetribution := func(chanID lnwire.ChannelID,
3✔
1788
                        commitHeight uint64) (*lnwallet.BreachRetribution,
3✔
1789
                        channeldb.ChannelType, error) {
6✔
1790

3✔
1791
                        channel, err := s.chanStateDB.FetchChannelByID(
3✔
1792
                                nil, chanID,
3✔
1793
                        )
3✔
1794
                        if err != nil {
3✔
1795
                                return nil, 0, err
×
1796
                        }
×
1797

1798
                        br, err := lnwallet.NewBreachRetribution(
3✔
1799
                                channel, commitHeight, 0, nil,
3✔
1800
                                implCfg.AuxLeafStore,
3✔
1801
                                implCfg.AuxContractResolver,
3✔
1802
                        )
3✔
1803
                        if err != nil {
3✔
1804
                                return nil, 0, err
×
1805
                        }
×
1806

1807
                        return br, channel.ChanType, nil
3✔
1808
                }
1809

1810
                fetchClosedChannel := s.chanStateDB.FetchClosedChannelForID
3✔
1811

3✔
1812
                // Copy the policy for legacy channels and set the blob flag
3✔
1813
                // signalling support for anchor channels.
3✔
1814
                anchorPolicy := policy
3✔
1815
                anchorPolicy.BlobType |= blob.Type(blob.FlagAnchorChannel)
3✔
1816

3✔
1817
                // Copy the policy for legacy channels and set the blob flag
3✔
1818
                // signalling support for taproot channels.
3✔
1819
                taprootPolicy := policy
3✔
1820
                taprootPolicy.TxPolicy.BlobType |= blob.Type(
3✔
1821
                        blob.FlagTaprootChannel,
3✔
1822
                )
3✔
1823

3✔
1824
                s.towerClientMgr, err = wtclient.NewManager(&wtclient.Config{
3✔
1825
                        FetchClosedChannel:     fetchClosedChannel,
3✔
1826
                        BuildBreachRetribution: buildBreachRetribution,
3✔
1827
                        SessionCloseRange:      cfg.WtClient.SessionCloseRange,
3✔
1828
                        ChainNotifier:          s.cc.ChainNotifier,
3✔
1829
                        SubscribeChannelEvents: func() (subscribe.Subscription,
3✔
1830
                                error) {
6✔
1831

3✔
1832
                                return s.channelNotifier.
3✔
1833
                                        SubscribeChannelEvents()
3✔
1834
                        },
3✔
1835
                        Signer: cc.Wallet.Cfg.Signer,
1836
                        NewAddress: func() ([]byte, error) {
3✔
1837
                                addr, err := newSweepPkScriptGen(
3✔
1838
                                        cc.Wallet, netParams,
3✔
1839
                                )().Unpack()
3✔
1840
                                if err != nil {
3✔
1841
                                        return nil, err
×
1842
                                }
×
1843

1844
                                return addr.DeliveryAddress, nil
3✔
1845
                        },
1846
                        SecretKeyRing:      s.cc.KeyRing,
1847
                        Dial:               cfg.net.Dial,
1848
                        AuthDial:           authDial,
1849
                        DB:                 dbs.TowerClientDB,
1850
                        ChainHash:          *s.cfg.ActiveNetParams.GenesisHash,
1851
                        MinBackoff:         10 * time.Second,
1852
                        MaxBackoff:         5 * time.Minute,
1853
                        MaxTasksInMemQueue: cfg.WtClient.MaxTasksInMemQueue,
1854
                }, policy, anchorPolicy, taprootPolicy)
1855
                if err != nil {
3✔
1856
                        return nil, err
×
1857
                }
×
1858
        }
1859

1860
        if len(cfg.ExternalHosts) != 0 {
3✔
1861
                advertisedIPs := make(map[string]struct{})
×
1862
                for _, addr := range s.currentNodeAnn.Addresses {
×
1863
                        advertisedIPs[addr.String()] = struct{}{}
×
1864
                }
×
1865

1866
                s.hostAnn = netann.NewHostAnnouncer(netann.HostAnnouncerConfig{
×
1867
                        Hosts:         cfg.ExternalHosts,
×
1868
                        RefreshTicker: ticker.New(defaultHostSampleInterval),
×
1869
                        LookupHost: func(host string) (net.Addr, error) {
×
1870
                                return lncfg.ParseAddressString(
×
1871
                                        host, strconv.Itoa(defaultPeerPort),
×
1872
                                        cfg.net.ResolveTCPAddr,
×
1873
                                )
×
1874
                        },
×
1875
                        AdvertisedIPs: advertisedIPs,
1876
                        AnnounceNewIPs: netann.IPAnnouncer(
1877
                                func(modifier ...netann.NodeAnnModifier) (
1878
                                        lnwire.NodeAnnouncement, error) {
×
1879

×
1880
                                        return s.genNodeAnnouncement(
×
1881
                                                nil, modifier...,
×
1882
                                        )
×
1883
                                }),
×
1884
                })
1885
        }
1886

1887
        // Create liveness monitor.
1888
        s.createLivenessMonitor(cfg, cc, leaderElector)
3✔
1889

3✔
1890
        listeners := make([]net.Listener, len(listenAddrs))
3✔
1891
        for i, listenAddr := range listenAddrs {
6✔
1892
                // Note: though brontide.NewListener uses ResolveTCPAddr, it
3✔
1893
                // doesn't need to call the general lndResolveTCP function
3✔
1894
                // since we are resolving a local address.
3✔
1895

3✔
1896
                // RESOLVE: We are actually partially accepting inbound
3✔
1897
                // connection requests when we call NewListener.
3✔
1898
                listeners[i], err = brontide.NewListener(
3✔
1899
                        nodeKeyECDH, listenAddr.String(),
3✔
1900
                        s.peerAccessMan.checkIncomingConnBanScore,
3✔
1901
                )
3✔
1902
                if err != nil {
3✔
1903
                        return nil, err
×
1904
                }
×
1905
        }
1906

1907
        // Create the connection manager which will be responsible for
1908
        // maintaining persistent outbound connections and also accepting new
1909
        // incoming connections
1910
        cmgr, err := connmgr.New(&connmgr.Config{
3✔
1911
                Listeners:      listeners,
3✔
1912
                OnAccept:       s.InboundPeerConnected,
3✔
1913
                RetryDuration:  time.Second * 5,
3✔
1914
                TargetOutbound: 100,
3✔
1915
                Dial: noiseDial(
3✔
1916
                        nodeKeyECDH, s.cfg.net, s.cfg.ConnectionTimeout,
3✔
1917
                ),
3✔
1918
                OnConnection: s.OutboundPeerConnected,
3✔
1919
        })
3✔
1920
        if err != nil {
3✔
1921
                return nil, err
×
1922
        }
×
1923
        s.connMgr = cmgr
3✔
1924

3✔
1925
        // Finally, register the subsystems in blockbeat.
3✔
1926
        s.registerBlockConsumers()
3✔
1927

3✔
1928
        return s, nil
3✔
1929
}
1930

1931
// UpdateRoutingConfig is a callback function to update the routing config
1932
// values in the main cfg.
1933
func (s *server) UpdateRoutingConfig(cfg *routing.MissionControlConfig) {
3✔
1934
        routerCfg := s.cfg.SubRPCServers.RouterRPC
3✔
1935

3✔
1936
        switch c := cfg.Estimator.Config().(type) {
3✔
1937
        case routing.AprioriConfig:
3✔
1938
                routerCfg.ProbabilityEstimatorType =
3✔
1939
                        routing.AprioriEstimatorName
3✔
1940

3✔
1941
                targetCfg := routerCfg.AprioriConfig
3✔
1942
                targetCfg.PenaltyHalfLife = c.PenaltyHalfLife
3✔
1943
                targetCfg.Weight = c.AprioriWeight
3✔
1944
                targetCfg.CapacityFraction = c.CapacityFraction
3✔
1945
                targetCfg.HopProbability = c.AprioriHopProbability
3✔
1946

1947
        case routing.BimodalConfig:
3✔
1948
                routerCfg.ProbabilityEstimatorType =
3✔
1949
                        routing.BimodalEstimatorName
3✔
1950

3✔
1951
                targetCfg := routerCfg.BimodalConfig
3✔
1952
                targetCfg.Scale = int64(c.BimodalScaleMsat)
3✔
1953
                targetCfg.NodeWeight = c.BimodalNodeWeight
3✔
1954
                targetCfg.DecayTime = c.BimodalDecayTime
3✔
1955
        }
1956

1957
        routerCfg.MaxMcHistory = cfg.MaxMcHistory
3✔
1958
}
1959

1960
// registerBlockConsumers registers the subsystems that consume block events.
1961
// By calling `RegisterQueue`, a list of subsystems are registered in the
1962
// blockbeat for block notifications. When a new block arrives, the subsystems
1963
// in the same queue are notified sequentially, and different queues are
1964
// notified concurrently.
1965
//
1966
// NOTE: To put a subsystem in a different queue, create a slice and pass it to
1967
// a new `RegisterQueue` call.
1968
func (s *server) registerBlockConsumers() {
3✔
1969
        // In this queue, when a new block arrives, it will be received and
3✔
1970
        // processed in this order: chainArb -> sweeper -> txPublisher.
3✔
1971
        consumers := []chainio.Consumer{
3✔
1972
                s.chainArb,
3✔
1973
                s.sweeper,
3✔
1974
                s.txPublisher,
3✔
1975
        }
3✔
1976
        s.blockbeatDispatcher.RegisterQueue(consumers)
3✔
1977
}
3✔
1978

1979
// signAliasUpdate takes a ChannelUpdate and returns the signature. This is
1980
// used for option_scid_alias channels where the ChannelUpdate to be sent back
1981
// may differ from what is on disk.
1982
func (s *server) signAliasUpdate(u *lnwire.ChannelUpdate1) (*ecdsa.Signature,
1983
        error) {
3✔
1984

3✔
1985
        data, err := u.DataToSign()
3✔
1986
        if err != nil {
3✔
1987
                return nil, err
×
1988
        }
×
1989

1990
        return s.cc.MsgSigner.SignMessage(s.identityKeyLoc, data, true)
3✔
1991
}
1992

1993
// createLivenessMonitor creates a set of health checks using our configured
1994
// values and uses these checks to create a liveness monitor. Available
1995
// health checks,
1996
//   - chainHealthCheck (will be disabled for --nochainbackend mode)
1997
//   - diskCheck
1998
//   - tlsHealthCheck
1999
//   - torController, only created when tor is enabled.
2000
//
2001
// If a health check has been disabled by setting attempts to 0, our monitor
2002
// will not run it.
2003
func (s *server) createLivenessMonitor(cfg *Config, cc *chainreg.ChainControl,
2004
        leaderElector cluster.LeaderElector) {
3✔
2005

3✔
2006
        chainBackendAttempts := cfg.HealthChecks.ChainCheck.Attempts
3✔
2007
        if cfg.Bitcoin.Node == "nochainbackend" {
3✔
2008
                srvrLog.Info("Disabling chain backend checks for " +
×
2009
                        "nochainbackend mode")
×
2010

×
2011
                chainBackendAttempts = 0
×
2012
        }
×
2013

2014
        chainHealthCheck := healthcheck.NewObservation(
3✔
2015
                "chain backend",
3✔
2016
                cc.HealthCheck,
3✔
2017
                cfg.HealthChecks.ChainCheck.Interval,
3✔
2018
                cfg.HealthChecks.ChainCheck.Timeout,
3✔
2019
                cfg.HealthChecks.ChainCheck.Backoff,
3✔
2020
                chainBackendAttempts,
3✔
2021
        )
3✔
2022

3✔
2023
        diskCheck := healthcheck.NewObservation(
3✔
2024
                "disk space",
3✔
2025
                func() error {
3✔
2026
                        free, err := healthcheck.AvailableDiskSpaceRatio(
×
2027
                                cfg.LndDir,
×
2028
                        )
×
2029
                        if err != nil {
×
2030
                                return err
×
2031
                        }
×
2032

2033
                        // If we have more free space than we require,
2034
                        // we return a nil error.
2035
                        if free > cfg.HealthChecks.DiskCheck.RequiredRemaining {
×
2036
                                return nil
×
2037
                        }
×
2038

2039
                        return fmt.Errorf("require: %v free space, got: %v",
×
2040
                                cfg.HealthChecks.DiskCheck.RequiredRemaining,
×
2041
                                free)
×
2042
                },
2043
                cfg.HealthChecks.DiskCheck.Interval,
2044
                cfg.HealthChecks.DiskCheck.Timeout,
2045
                cfg.HealthChecks.DiskCheck.Backoff,
2046
                cfg.HealthChecks.DiskCheck.Attempts,
2047
        )
2048

2049
        tlsHealthCheck := healthcheck.NewObservation(
3✔
2050
                "tls",
3✔
2051
                func() error {
3✔
2052
                        expired, expTime, err := s.tlsManager.IsCertExpired(
×
2053
                                s.cc.KeyRing,
×
2054
                        )
×
2055
                        if err != nil {
×
2056
                                return err
×
2057
                        }
×
2058
                        if expired {
×
2059
                                return fmt.Errorf("TLS certificate is "+
×
2060
                                        "expired as of %v", expTime)
×
2061
                        }
×
2062

2063
                        // If the certificate is not outdated, no error needs
2064
                        // to be returned
2065
                        return nil
×
2066
                },
2067
                cfg.HealthChecks.TLSCheck.Interval,
2068
                cfg.HealthChecks.TLSCheck.Timeout,
2069
                cfg.HealthChecks.TLSCheck.Backoff,
2070
                cfg.HealthChecks.TLSCheck.Attempts,
2071
        )
2072

2073
        checks := []*healthcheck.Observation{
3✔
2074
                chainHealthCheck, diskCheck, tlsHealthCheck,
3✔
2075
        }
3✔
2076

3✔
2077
        // If Tor is enabled, add the healthcheck for tor connection.
3✔
2078
        if s.torController != nil {
3✔
2079
                torConnectionCheck := healthcheck.NewObservation(
×
2080
                        "tor connection",
×
2081
                        func() error {
×
2082
                                return healthcheck.CheckTorServiceStatus(
×
2083
                                        s.torController,
×
2084
                                        s.createNewHiddenService,
×
2085
                                )
×
2086
                        },
×
2087
                        cfg.HealthChecks.TorConnection.Interval,
2088
                        cfg.HealthChecks.TorConnection.Timeout,
2089
                        cfg.HealthChecks.TorConnection.Backoff,
2090
                        cfg.HealthChecks.TorConnection.Attempts,
2091
                )
2092
                checks = append(checks, torConnectionCheck)
×
2093
        }
2094

2095
        // If remote signing is enabled, add the healthcheck for the remote
2096
        // signing RPC interface.
2097
        if s.cfg.RemoteSigner != nil && s.cfg.RemoteSigner.Enable {
6✔
2098
                // Because we have two cascading timeouts here, we need to add
3✔
2099
                // some slack to the "outer" one of them in case the "inner"
3✔
2100
                // returns exactly on time.
3✔
2101
                overhead := time.Millisecond * 10
3✔
2102

3✔
2103
                remoteSignerConnectionCheck := healthcheck.NewObservation(
3✔
2104
                        "remote signer connection",
3✔
2105
                        rpcwallet.HealthCheck(
3✔
2106
                                s.cfg.RemoteSigner,
3✔
2107

3✔
2108
                                // For the health check we might to be even
3✔
2109
                                // stricter than the initial/normal connect, so
3✔
2110
                                // we use the health check timeout here.
3✔
2111
                                cfg.HealthChecks.RemoteSigner.Timeout,
3✔
2112
                        ),
3✔
2113
                        cfg.HealthChecks.RemoteSigner.Interval,
3✔
2114
                        cfg.HealthChecks.RemoteSigner.Timeout+overhead,
3✔
2115
                        cfg.HealthChecks.RemoteSigner.Backoff,
3✔
2116
                        cfg.HealthChecks.RemoteSigner.Attempts,
3✔
2117
                )
3✔
2118
                checks = append(checks, remoteSignerConnectionCheck)
3✔
2119
        }
3✔
2120

2121
        // If we have a leader elector, we add a health check to ensure we are
2122
        // still the leader. During normal operation, we should always be the
2123
        // leader, but there are circumstances where this may change, such as
2124
        // when we lose network connectivity for long enough expiring out lease.
2125
        if leaderElector != nil {
3✔
2126
                leaderCheck := healthcheck.NewObservation(
×
2127
                        "leader status",
×
2128
                        func() error {
×
2129
                                // Check if we are still the leader. Note that
×
2130
                                // we don't need to use a timeout context here
×
2131
                                // as the healthcheck observer will handle the
×
2132
                                // timeout case for us.
×
2133
                                timeoutCtx, cancel := context.WithTimeout(
×
2134
                                        context.Background(),
×
2135
                                        cfg.HealthChecks.LeaderCheck.Timeout,
×
2136
                                )
×
2137
                                defer cancel()
×
2138

×
2139
                                leader, err := leaderElector.IsLeader(
×
2140
                                        timeoutCtx,
×
2141
                                )
×
2142
                                if err != nil {
×
2143
                                        return fmt.Errorf("unable to check if "+
×
2144
                                                "still leader: %v", err)
×
2145
                                }
×
2146

2147
                                if !leader {
×
2148
                                        srvrLog.Debug("Not the current leader")
×
2149
                                        return fmt.Errorf("not the current " +
×
2150
                                                "leader")
×
2151
                                }
×
2152

2153
                                return nil
×
2154
                        },
2155
                        cfg.HealthChecks.LeaderCheck.Interval,
2156
                        cfg.HealthChecks.LeaderCheck.Timeout,
2157
                        cfg.HealthChecks.LeaderCheck.Backoff,
2158
                        cfg.HealthChecks.LeaderCheck.Attempts,
2159
                )
2160

2161
                checks = append(checks, leaderCheck)
×
2162
        }
2163

2164
        // If we have not disabled all of our health checks, we create a
2165
        // liveness monitor with our configured checks.
2166
        s.livenessMonitor = healthcheck.NewMonitor(
3✔
2167
                &healthcheck.Config{
3✔
2168
                        Checks:   checks,
3✔
2169
                        Shutdown: srvrLog.Criticalf,
3✔
2170
                },
3✔
2171
        )
3✔
2172
}
2173

2174
// Started returns true if the server has been started, and false otherwise.
2175
// NOTE: This function is safe for concurrent access.
2176
func (s *server) Started() bool {
3✔
2177
        return atomic.LoadInt32(&s.active) != 0
3✔
2178
}
3✔
2179

2180
// cleaner is used to aggregate "cleanup" functions during an operation that
2181
// starts several subsystems. In case one of the subsystem fails to start
2182
// and a proper resource cleanup is required, the "run" method achieves this
2183
// by running all these added "cleanup" functions.
2184
type cleaner []func() error
2185

2186
// add is used to add a cleanup function to be called when
2187
// the run function is executed.
2188
func (c cleaner) add(cleanup func() error) cleaner {
3✔
2189
        return append(c, cleanup)
3✔
2190
}
3✔
2191

2192
// run is used to run all the previousely added cleanup functions.
2193
func (c cleaner) run() {
×
2194
        for i := len(c) - 1; i >= 0; i-- {
×
2195
                if err := c[i](); err != nil {
×
2196
                        srvrLog.Infof("Cleanup failed: %v", err)
×
2197
                }
×
2198
        }
2199
}
2200

2201
// startLowLevelServices starts the low-level services of the server. These
2202
// services must be started successfully before running the main server. The
2203
// services are,
2204
// 1. the chain notifier.
2205
//
2206
// TODO(yy): identify and add more low-level services here.
2207
func (s *server) startLowLevelServices() error {
3✔
2208
        var startErr error
3✔
2209

3✔
2210
        cleanup := cleaner{}
3✔
2211

3✔
2212
        cleanup = cleanup.add(s.cc.ChainNotifier.Stop)
3✔
2213
        if err := s.cc.ChainNotifier.Start(); err != nil {
3✔
2214
                startErr = err
×
2215
        }
×
2216

2217
        if startErr != nil {
3✔
2218
                cleanup.run()
×
2219
        }
×
2220

2221
        return startErr
3✔
2222
}
2223

2224
// Start starts the main daemon server, all requested listeners, and any helper
2225
// goroutines.
2226
// NOTE: This function is safe for concurrent access.
2227
//
2228
//nolint:funlen
2229
func (s *server) Start() error {
3✔
2230
        // Get the current blockbeat.
3✔
2231
        beat, err := s.getStartingBeat()
3✔
2232
        if err != nil {
3✔
2233
                return err
×
2234
        }
×
2235

2236
        var startErr error
3✔
2237

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

3✔
2243
        s.start.Do(func() {
6✔
2244
                cleanup = cleanup.add(s.customMessageServer.Stop)
3✔
2245
                if err := s.customMessageServer.Start(); err != nil {
3✔
2246
                        startErr = err
×
2247
                        return
×
2248
                }
×
2249

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

2258
                if s.livenessMonitor != nil {
6✔
2259
                        cleanup = cleanup.add(s.livenessMonitor.Stop)
3✔
2260
                        if err := s.livenessMonitor.Start(); err != nil {
3✔
2261
                                startErr = err
×
2262
                                return
×
2263
                        }
×
2264
                }
2265

2266
                // Start the notification server. This is used so channel
2267
                // management goroutines can be notified when a funding
2268
                // transaction reaches a sufficient number of confirmations, or
2269
                // when the input for the funding transaction is spent in an
2270
                // attempt at an uncooperative close by the counterparty.
2271
                cleanup = cleanup.add(s.sigPool.Stop)
3✔
2272
                if err := s.sigPool.Start(); err != nil {
3✔
2273
                        startErr = err
×
2274
                        return
×
2275
                }
×
2276

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

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

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

2295
                cleanup = cleanup.add(s.channelNotifier.Stop)
3✔
2296
                if err := s.channelNotifier.Start(); err != nil {
3✔
2297
                        startErr = err
×
2298
                        return
×
2299
                }
×
2300

2301
                cleanup = cleanup.add(func() error {
3✔
2302
                        return s.peerNotifier.Stop()
×
2303
                })
×
2304
                if err := s.peerNotifier.Start(); err != nil {
3✔
2305
                        startErr = err
×
2306
                        return
×
2307
                }
×
2308

2309
                cleanup = cleanup.add(s.htlcNotifier.Stop)
3✔
2310
                if err := s.htlcNotifier.Start(); err != nil {
3✔
2311
                        startErr = err
×
2312
                        return
×
2313
                }
×
2314

2315
                if s.towerClientMgr != nil {
6✔
2316
                        cleanup = cleanup.add(s.towerClientMgr.Stop)
3✔
2317
                        if err := s.towerClientMgr.Start(); err != nil {
3✔
2318
                                startErr = err
×
2319
                                return
×
2320
                        }
×
2321
                }
2322

2323
                cleanup = cleanup.add(s.txPublisher.Stop)
3✔
2324
                if err := s.txPublisher.Start(beat); err != nil {
3✔
2325
                        startErr = err
×
2326
                        return
×
2327
                }
×
2328

2329
                cleanup = cleanup.add(s.sweeper.Stop)
3✔
2330
                if err := s.sweeper.Start(beat); err != nil {
3✔
2331
                        startErr = err
×
2332
                        return
×
2333
                }
×
2334

2335
                cleanup = cleanup.add(s.utxoNursery.Stop)
3✔
2336
                if err := s.utxoNursery.Start(); err != nil {
3✔
2337
                        startErr = err
×
2338
                        return
×
2339
                }
×
2340

2341
                cleanup = cleanup.add(s.breachArbitrator.Stop)
3✔
2342
                if err := s.breachArbitrator.Start(); err != nil {
3✔
2343
                        startErr = err
×
2344
                        return
×
2345
                }
×
2346

2347
                cleanup = cleanup.add(s.fundingMgr.Stop)
3✔
2348
                if err := s.fundingMgr.Start(); err != nil {
3✔
2349
                        startErr = err
×
2350
                        return
×
2351
                }
×
2352

2353
                // htlcSwitch must be started before chainArb since the latter
2354
                // relies on htlcSwitch to deliver resolution message upon
2355
                // start.
2356
                cleanup = cleanup.add(s.htlcSwitch.Stop)
3✔
2357
                if err := s.htlcSwitch.Start(); err != nil {
3✔
2358
                        startErr = err
×
2359
                        return
×
2360
                }
×
2361

2362
                cleanup = cleanup.add(s.interceptableSwitch.Stop)
3✔
2363
                if err := s.interceptableSwitch.Start(); err != nil {
3✔
2364
                        startErr = err
×
2365
                        return
×
2366
                }
×
2367

2368
                cleanup = cleanup.add(s.invoiceHtlcModifier.Stop)
3✔
2369
                if err := s.invoiceHtlcModifier.Start(); err != nil {
3✔
2370
                        startErr = err
×
2371
                        return
×
2372
                }
×
2373

2374
                cleanup = cleanup.add(s.chainArb.Stop)
3✔
2375
                if err := s.chainArb.Start(beat); err != nil {
3✔
2376
                        startErr = err
×
2377
                        return
×
2378
                }
×
2379

2380
                cleanup = cleanup.add(s.graphDB.Stop)
3✔
2381
                if err := s.graphDB.Start(); err != nil {
3✔
NEW
2382
                        startErr = err
×
NEW
2383
                        return
×
NEW
2384
                }
×
2385

2386
                cleanup = cleanup.add(s.graphBuilder.Stop)
3✔
2387
                if err := s.graphBuilder.Start(); err != nil {
3✔
2388
                        startErr = err
×
2389
                        return
×
2390
                }
×
2391

2392
                cleanup = cleanup.add(s.chanRouter.Stop)
3✔
2393
                if err := s.chanRouter.Start(); err != nil {
3✔
2394
                        startErr = err
×
2395
                        return
×
2396
                }
×
2397
                // The authGossiper depends on the chanRouter and therefore
2398
                // should be started after it.
2399
                cleanup = cleanup.add(s.authGossiper.Stop)
3✔
2400
                if err := s.authGossiper.Start(); err != nil {
3✔
2401
                        startErr = err
×
2402
                        return
×
2403
                }
×
2404

2405
                cleanup = cleanup.add(s.invoices.Stop)
3✔
2406
                if err := s.invoices.Start(); err != nil {
3✔
2407
                        startErr = err
×
2408
                        return
×
2409
                }
×
2410

2411
                cleanup = cleanup.add(s.sphinx.Stop)
3✔
2412
                if err := s.sphinx.Start(); err != nil {
3✔
2413
                        startErr = err
×
2414
                        return
×
2415
                }
×
2416

2417
                cleanup = cleanup.add(s.chanStatusMgr.Stop)
3✔
2418
                if err := s.chanStatusMgr.Start(); err != nil {
3✔
2419
                        startErr = err
×
2420
                        return
×
2421
                }
×
2422

2423
                cleanup = cleanup.add(s.chanEventStore.Stop)
3✔
2424
                if err := s.chanEventStore.Start(); err != nil {
3✔
2425
                        startErr = err
×
2426
                        return
×
2427
                }
×
2428

2429
                cleanup.add(func() error {
3✔
2430
                        s.missionController.StopStoreTickers()
×
2431
                        return nil
×
2432
                })
×
2433
                s.missionController.RunStoreTickers()
3✔
2434

3✔
2435
                // Before we start the connMgr, we'll check to see if we have
3✔
2436
                // any backups to recover. We do this now as we want to ensure
3✔
2437
                // that have all the information we need to handle channel
3✔
2438
                // recovery _before_ we even accept connections from any peers.
3✔
2439
                chanRestorer := &chanDBRestorer{
3✔
2440
                        db:         s.chanStateDB,
3✔
2441
                        secretKeys: s.cc.KeyRing,
3✔
2442
                        chainArb:   s.chainArb,
3✔
2443
                }
3✔
2444
                if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
3✔
2445
                        _, err := chanbackup.UnpackAndRecoverSingles(
×
2446
                                s.chansToRestore.PackedSingleChanBackups,
×
2447
                                s.cc.KeyRing, chanRestorer, s,
×
2448
                        )
×
2449
                        if err != nil {
×
2450
                                startErr = fmt.Errorf("unable to unpack single "+
×
2451
                                        "backups: %v", err)
×
2452
                                return
×
2453
                        }
×
2454
                }
2455
                if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
6✔
2456
                        _, err := chanbackup.UnpackAndRecoverMulti(
3✔
2457
                                s.chansToRestore.PackedMultiChanBackup,
3✔
2458
                                s.cc.KeyRing, chanRestorer, s,
3✔
2459
                        )
3✔
2460
                        if err != nil {
3✔
2461
                                startErr = fmt.Errorf("unable to unpack chan "+
×
2462
                                        "backup: %v", err)
×
2463
                                return
×
2464
                        }
×
2465
                }
2466

2467
                // chanSubSwapper must be started after the `channelNotifier`
2468
                // because it depends on channel events as a synchronization
2469
                // point.
2470
                cleanup = cleanup.add(s.chanSubSwapper.Stop)
3✔
2471
                if err := s.chanSubSwapper.Start(); err != nil {
3✔
2472
                        startErr = err
×
2473
                        return
×
2474
                }
×
2475

2476
                if s.torController != nil {
3✔
2477
                        cleanup = cleanup.add(s.torController.Stop)
×
2478
                        if err := s.createNewHiddenService(); err != nil {
×
2479
                                startErr = err
×
2480
                                return
×
2481
                        }
×
2482
                }
2483

2484
                if s.natTraversal != nil {
3✔
2485
                        s.wg.Add(1)
×
2486
                        go s.watchExternalIP()
×
2487
                }
×
2488

2489
                // Start connmgr last to prevent connections before init.
2490
                cleanup = cleanup.add(func() error {
3✔
2491
                        s.connMgr.Stop()
×
2492
                        return nil
×
2493
                })
×
2494

2495
                // RESOLVE: s.connMgr.Start() is called here, but
2496
                // brontide.NewListener() is called in newServer. This means
2497
                // that we are actually listening and partially accepting
2498
                // inbound connections even before the connMgr starts.
2499
                s.connMgr.Start()
3✔
2500

3✔
2501
                // If peers are specified as a config option, we'll add those
3✔
2502
                // peers first.
3✔
2503
                for _, peerAddrCfg := range s.cfg.AddPeers {
6✔
2504
                        parsedPubkey, parsedHost, err := lncfg.ParseLNAddressPubkey(
3✔
2505
                                peerAddrCfg,
3✔
2506
                        )
3✔
2507
                        if err != nil {
3✔
2508
                                startErr = fmt.Errorf("unable to parse peer "+
×
2509
                                        "pubkey from config: %v", err)
×
2510
                                return
×
2511
                        }
×
2512
                        addr, err := parseAddr(parsedHost, s.cfg.net)
3✔
2513
                        if err != nil {
3✔
2514
                                startErr = fmt.Errorf("unable to parse peer "+
×
2515
                                        "address provided as a config option: "+
×
2516
                                        "%v", err)
×
2517
                                return
×
2518
                        }
×
2519

2520
                        peerAddr := &lnwire.NetAddress{
3✔
2521
                                IdentityKey: parsedPubkey,
3✔
2522
                                Address:     addr,
3✔
2523
                                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
2524
                        }
3✔
2525

3✔
2526
                        err = s.ConnectToPeer(
3✔
2527
                                peerAddr, true,
3✔
2528
                                s.cfg.ConnectionTimeout,
3✔
2529
                        )
3✔
2530
                        if err != nil {
3✔
2531
                                startErr = fmt.Errorf("unable to connect to "+
×
2532
                                        "peer address provided as a config "+
×
2533
                                        "option: %v", err)
×
2534
                                return
×
2535
                        }
×
2536
                }
2537

2538
                // Subscribe to NodeAnnouncements that advertise new addresses
2539
                // our persistent peers.
2540
                if err := s.updatePersistentPeerAddrs(); err != nil {
3✔
2541
                        startErr = err
×
2542
                        return
×
2543
                }
×
2544

2545
                // With all the relevant sub-systems started, we'll now attempt
2546
                // to establish persistent connections to our direct channel
2547
                // collaborators within the network. Before doing so however,
2548
                // we'll prune our set of link nodes found within the database
2549
                // to ensure we don't reconnect to any nodes we no longer have
2550
                // open channels with.
2551
                if err := s.chanStateDB.PruneLinkNodes(); err != nil {
3✔
2552
                        startErr = err
×
2553
                        return
×
2554
                }
×
2555
                if err := s.establishPersistentConnections(); err != nil {
3✔
2556
                        startErr = err
×
2557
                        return
×
2558
                }
×
2559

2560
                // setSeedList is a helper function that turns multiple DNS seed
2561
                // server tuples from the command line or config file into the
2562
                // data structure we need and does a basic formal sanity check
2563
                // in the process.
2564
                setSeedList := func(tuples []string, genesisHash chainhash.Hash) {
3✔
2565
                        if len(tuples) == 0 {
×
2566
                                return
×
2567
                        }
×
2568

2569
                        result := make([][2]string, len(tuples))
×
2570
                        for idx, tuple := range tuples {
×
2571
                                tuple = strings.TrimSpace(tuple)
×
2572
                                if len(tuple) == 0 {
×
2573
                                        return
×
2574
                                }
×
2575

2576
                                servers := strings.Split(tuple, ",")
×
2577
                                if len(servers) > 2 || len(servers) == 0 {
×
2578
                                        srvrLog.Warnf("Ignoring invalid DNS "+
×
2579
                                                "seed tuple: %v", servers)
×
2580
                                        return
×
2581
                                }
×
2582

2583
                                copy(result[idx][:], servers)
×
2584
                        }
2585

2586
                        chainreg.ChainDNSSeeds[genesisHash] = result
×
2587
                }
2588

2589
                // Let users overwrite the DNS seed nodes. We only allow them
2590
                // for bitcoin mainnet/testnet/signet.
2591
                if s.cfg.Bitcoin.MainNet {
3✔
2592
                        setSeedList(
×
2593
                                s.cfg.Bitcoin.DNSSeeds,
×
2594
                                chainreg.BitcoinMainnetGenesis,
×
2595
                        )
×
2596
                }
×
2597
                if s.cfg.Bitcoin.TestNet3 {
3✔
2598
                        setSeedList(
×
2599
                                s.cfg.Bitcoin.DNSSeeds,
×
2600
                                chainreg.BitcoinTestnetGenesis,
×
2601
                        )
×
2602
                }
×
2603
                if s.cfg.Bitcoin.SigNet {
3✔
2604
                        setSeedList(
×
2605
                                s.cfg.Bitcoin.DNSSeeds,
×
2606
                                chainreg.BitcoinSignetGenesis,
×
2607
                        )
×
2608
                }
×
2609

2610
                // If network bootstrapping hasn't been disabled, then we'll
2611
                // configure the set of active bootstrappers, and launch a
2612
                // dedicated goroutine to maintain a set of persistent
2613
                // connections.
2614
                if shouldPeerBootstrap(s.cfg) {
3✔
2615
                        bootstrappers, err := initNetworkBootstrappers(s)
×
2616
                        if err != nil {
×
2617
                                startErr = err
×
2618
                                return
×
2619
                        }
×
2620

2621
                        s.wg.Add(1)
×
2622
                        go s.peerBootstrapper(defaultMinPeers, bootstrappers)
×
2623
                } else {
3✔
2624
                        srvrLog.Infof("Auto peer bootstrapping is disabled")
3✔
2625
                }
3✔
2626

2627
                // Start the blockbeat after all other subsystems have been
2628
                // started so they are ready to receive new blocks.
2629
                cleanup = cleanup.add(func() error {
3✔
2630
                        s.blockbeatDispatcher.Stop()
×
2631
                        return nil
×
2632
                })
×
2633
                if err := s.blockbeatDispatcher.Start(); err != nil {
3✔
2634
                        startErr = err
×
2635
                        return
×
2636
                }
×
2637

2638
                // Set the active flag now that we've completed the full
2639
                // startup.
2640
                atomic.StoreInt32(&s.active, 1)
3✔
2641
        })
2642

2643
        if startErr != nil {
3✔
2644
                cleanup.run()
×
2645
        }
×
2646
        return startErr
3✔
2647
}
2648

2649
// Stop gracefully shutsdown the main daemon server. This function will signal
2650
// any active goroutines, or helper objects to exit, then blocks until they've
2651
// all successfully exited. Additionally, any/all listeners are closed.
2652
// NOTE: This function is safe for concurrent access.
2653
func (s *server) Stop() error {
3✔
2654
        s.stop.Do(func() {
6✔
2655
                atomic.StoreInt32(&s.stopping, 1)
3✔
2656

3✔
2657
                close(s.quit)
3✔
2658

3✔
2659
                // Shutdown connMgr first to prevent conns during shutdown.
3✔
2660
                s.connMgr.Stop()
3✔
2661

3✔
2662
                // Stop dispatching blocks to other systems immediately.
3✔
2663
                s.blockbeatDispatcher.Stop()
3✔
2664

3✔
2665
                // Shutdown the wallet, funding manager, and the rpc server.
3✔
2666
                if err := s.chanStatusMgr.Stop(); err != nil {
3✔
2667
                        srvrLog.Warnf("failed to stop chanStatusMgr: %v", err)
×
2668
                }
×
2669
                if err := s.htlcSwitch.Stop(); err != nil {
3✔
2670
                        srvrLog.Warnf("failed to stop htlcSwitch: %v", err)
×
2671
                }
×
2672
                if err := s.sphinx.Stop(); err != nil {
3✔
2673
                        srvrLog.Warnf("failed to stop sphinx: %v", err)
×
2674
                }
×
2675
                if err := s.invoices.Stop(); err != nil {
3✔
2676
                        srvrLog.Warnf("failed to stop invoices: %v", err)
×
2677
                }
×
2678
                if err := s.interceptableSwitch.Stop(); err != nil {
3✔
2679
                        srvrLog.Warnf("failed to stop interceptable "+
×
2680
                                "switch: %v", err)
×
2681
                }
×
2682
                if err := s.invoiceHtlcModifier.Stop(); err != nil {
3✔
2683
                        srvrLog.Warnf("failed to stop htlc invoices "+
×
2684
                                "modifier: %v", err)
×
2685
                }
×
2686
                if err := s.chanRouter.Stop(); err != nil {
3✔
2687
                        srvrLog.Warnf("failed to stop chanRouter: %v", err)
×
2688
                }
×
2689
                if err := s.graphBuilder.Stop(); err != nil {
3✔
2690
                        srvrLog.Warnf("failed to stop graphBuilder %v", err)
×
2691
                }
×
2692
                if err := s.graphDB.Stop(); err != nil {
3✔
NEW
2693
                        srvrLog.Warnf("failed to stop graphDB %v", err)
×
NEW
2694
                }
×
2695
                if err := s.chainArb.Stop(); err != nil {
3✔
2696
                        srvrLog.Warnf("failed to stop chainArb: %v", err)
×
2697
                }
×
2698
                if err := s.fundingMgr.Stop(); err != nil {
3✔
2699
                        srvrLog.Warnf("failed to stop fundingMgr: %v", err)
×
2700
                }
×
2701
                if err := s.breachArbitrator.Stop(); err != nil {
3✔
2702
                        srvrLog.Warnf("failed to stop breachArbitrator: %v",
×
2703
                                err)
×
2704
                }
×
2705
                if err := s.utxoNursery.Stop(); err != nil {
3✔
2706
                        srvrLog.Warnf("failed to stop utxoNursery: %v", err)
×
2707
                }
×
2708
                if err := s.authGossiper.Stop(); err != nil {
3✔
2709
                        srvrLog.Warnf("failed to stop authGossiper: %v", err)
×
2710
                }
×
2711
                if err := s.sweeper.Stop(); err != nil {
3✔
2712
                        srvrLog.Warnf("failed to stop sweeper: %v", err)
×
2713
                }
×
2714
                if err := s.txPublisher.Stop(); err != nil {
3✔
2715
                        srvrLog.Warnf("failed to stop txPublisher: %v", err)
×
2716
                }
×
2717
                if err := s.channelNotifier.Stop(); err != nil {
3✔
2718
                        srvrLog.Warnf("failed to stop channelNotifier: %v", err)
×
2719
                }
×
2720
                if err := s.peerNotifier.Stop(); err != nil {
3✔
2721
                        srvrLog.Warnf("failed to stop peerNotifier: %v", err)
×
2722
                }
×
2723
                if err := s.htlcNotifier.Stop(); err != nil {
3✔
2724
                        srvrLog.Warnf("failed to stop htlcNotifier: %v", err)
×
2725
                }
×
2726

2727
                // Update channel.backup file. Make sure to do it before
2728
                // stopping chanSubSwapper.
2729
                singles, err := chanbackup.FetchStaticChanBackups(
3✔
2730
                        s.chanStateDB, s.addrSource,
3✔
2731
                )
3✔
2732
                if err != nil {
3✔
2733
                        srvrLog.Warnf("failed to fetch channel states: %v",
×
2734
                                err)
×
2735
                } else {
3✔
2736
                        err := s.chanSubSwapper.ManualUpdate(singles)
3✔
2737
                        if err != nil {
6✔
2738
                                srvrLog.Warnf("Manual update of channel "+
3✔
2739
                                        "backup failed: %v", err)
3✔
2740
                        }
3✔
2741
                }
2742

2743
                if err := s.chanSubSwapper.Stop(); err != nil {
3✔
2744
                        srvrLog.Warnf("failed to stop chanSubSwapper: %v", err)
×
2745
                }
×
2746
                if err := s.cc.ChainNotifier.Stop(); err != nil {
3✔
2747
                        srvrLog.Warnf("Unable to stop ChainNotifier: %v", err)
×
2748
                }
×
2749
                if err := s.cc.BestBlockTracker.Stop(); err != nil {
3✔
2750
                        srvrLog.Warnf("Unable to stop BestBlockTracker: %v",
×
2751
                                err)
×
2752
                }
×
2753
                if err := s.chanEventStore.Stop(); err != nil {
3✔
2754
                        srvrLog.Warnf("Unable to stop ChannelEventStore: %v",
×
2755
                                err)
×
2756
                }
×
2757
                s.missionController.StopStoreTickers()
3✔
2758

3✔
2759
                // Disconnect from each active peers to ensure that
3✔
2760
                // peerTerminationWatchers signal completion to each peer.
3✔
2761
                for _, peer := range s.Peers() {
6✔
2762
                        err := s.DisconnectPeer(peer.IdentityKey())
3✔
2763
                        if err != nil {
3✔
2764
                                srvrLog.Warnf("could not disconnect peer: %v"+
×
2765
                                        "received error: %v", peer.IdentityKey(),
×
2766
                                        err,
×
2767
                                )
×
2768
                        }
×
2769
                }
2770

2771
                // Now that all connections have been torn down, stop the tower
2772
                // client which will reliably flush all queued states to the
2773
                // tower. If this is halted for any reason, the force quit timer
2774
                // will kick in and abort to allow this method to return.
2775
                if s.towerClientMgr != nil {
6✔
2776
                        if err := s.towerClientMgr.Stop(); err != nil {
3✔
2777
                                srvrLog.Warnf("Unable to shut down tower "+
×
2778
                                        "client manager: %v", err)
×
2779
                        }
×
2780
                }
2781

2782
                if s.hostAnn != nil {
3✔
2783
                        if err := s.hostAnn.Stop(); err != nil {
×
2784
                                srvrLog.Warnf("unable to shut down host "+
×
2785
                                        "annoucner: %v", err)
×
2786
                        }
×
2787
                }
2788

2789
                if s.livenessMonitor != nil {
6✔
2790
                        if err := s.livenessMonitor.Stop(); err != nil {
3✔
2791
                                srvrLog.Warnf("unable to shutdown liveness "+
×
2792
                                        "monitor: %v", err)
×
2793
                        }
×
2794
                }
2795

2796
                // Wait for all lingering goroutines to quit.
2797
                srvrLog.Debug("Waiting for server to shutdown...")
3✔
2798
                s.wg.Wait()
3✔
2799

3✔
2800
                srvrLog.Debug("Stopping buffer pools...")
3✔
2801
                s.sigPool.Stop()
3✔
2802
                s.writePool.Stop()
3✔
2803
                s.readPool.Stop()
3✔
2804
        })
2805

2806
        return nil
3✔
2807
}
2808

2809
// Stopped returns true if the server has been instructed to shutdown.
2810
// NOTE: This function is safe for concurrent access.
2811
func (s *server) Stopped() bool {
3✔
2812
        return atomic.LoadInt32(&s.stopping) != 0
3✔
2813
}
3✔
2814

2815
// configurePortForwarding attempts to set up port forwarding for the different
2816
// ports that the server will be listening on.
2817
//
2818
// NOTE: This should only be used when using some kind of NAT traversal to
2819
// automatically set up forwarding rules.
2820
func (s *server) configurePortForwarding(ports ...uint16) ([]string, error) {
×
2821
        ip, err := s.natTraversal.ExternalIP()
×
2822
        if err != nil {
×
2823
                return nil, err
×
2824
        }
×
2825
        s.lastDetectedIP = ip
×
2826

×
2827
        externalIPs := make([]string, 0, len(ports))
×
2828
        for _, port := range ports {
×
2829
                if err := s.natTraversal.AddPortMapping(port); err != nil {
×
2830
                        srvrLog.Debugf("Unable to forward port %d: %v", port, err)
×
2831
                        continue
×
2832
                }
2833

2834
                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2835
                externalIPs = append(externalIPs, hostIP)
×
2836
        }
2837

2838
        return externalIPs, nil
×
2839
}
2840

2841
// removePortForwarding attempts to clear the forwarding rules for the different
2842
// ports the server is currently listening on.
2843
//
2844
// NOTE: This should only be used when using some kind of NAT traversal to
2845
// automatically set up forwarding rules.
2846
func (s *server) removePortForwarding() {
×
2847
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2848
        for _, port := range forwardedPorts {
×
2849
                if err := s.natTraversal.DeletePortMapping(port); err != nil {
×
2850
                        srvrLog.Errorf("Unable to remove forwarding rules for "+
×
2851
                                "port %d: %v", port, err)
×
2852
                }
×
2853
        }
2854
}
2855

2856
// watchExternalIP continuously checks for an updated external IP address every
2857
// 15 minutes. Once a new IP address has been detected, it will automatically
2858
// handle port forwarding rules and send updated node announcements to the
2859
// currently connected peers.
2860
//
2861
// NOTE: This MUST be run as a goroutine.
2862
func (s *server) watchExternalIP() {
×
2863
        defer s.wg.Done()
×
2864

×
2865
        // Before exiting, we'll make sure to remove the forwarding rules set
×
2866
        // up by the server.
×
2867
        defer s.removePortForwarding()
×
2868

×
2869
        // Keep track of the external IPs set by the user to avoid replacing
×
2870
        // them when detecting a new IP.
×
2871
        ipsSetByUser := make(map[string]struct{})
×
2872
        for _, ip := range s.cfg.ExternalIPs {
×
2873
                ipsSetByUser[ip.String()] = struct{}{}
×
2874
        }
×
2875

2876
        forwardedPorts := s.natTraversal.ForwardedPorts()
×
2877

×
2878
        ticker := time.NewTicker(15 * time.Minute)
×
2879
        defer ticker.Stop()
×
2880
out:
×
2881
        for {
×
2882
                select {
×
2883
                case <-ticker.C:
×
2884
                        // We'll start off by making sure a new IP address has
×
2885
                        // been detected.
×
2886
                        ip, err := s.natTraversal.ExternalIP()
×
2887
                        if err != nil {
×
2888
                                srvrLog.Debugf("Unable to retrieve the "+
×
2889
                                        "external IP address: %v", err)
×
2890
                                continue
×
2891
                        }
2892

2893
                        // Periodically renew the NAT port forwarding.
2894
                        for _, port := range forwardedPorts {
×
2895
                                err := s.natTraversal.AddPortMapping(port)
×
2896
                                if err != nil {
×
2897
                                        srvrLog.Warnf("Unable to automatically "+
×
2898
                                                "re-create port forwarding using %s: %v",
×
2899
                                                s.natTraversal.Name(), err)
×
2900
                                } else {
×
2901
                                        srvrLog.Debugf("Automatically re-created "+
×
2902
                                                "forwarding for port %d using %s to "+
×
2903
                                                "advertise external IP",
×
2904
                                                port, s.natTraversal.Name())
×
2905
                                }
×
2906
                        }
2907

2908
                        if ip.Equal(s.lastDetectedIP) {
×
2909
                                continue
×
2910
                        }
2911

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

×
2914
                        // Next, we'll craft the new addresses that will be
×
2915
                        // included in the new node announcement and advertised
×
2916
                        // to the network. Each address will consist of the new
×
2917
                        // IP detected and one of the currently advertised
×
2918
                        // ports.
×
2919
                        var newAddrs []net.Addr
×
2920
                        for _, port := range forwardedPorts {
×
2921
                                hostIP := fmt.Sprintf("%v:%d", ip, port)
×
2922
                                addr, err := net.ResolveTCPAddr("tcp", hostIP)
×
2923
                                if err != nil {
×
2924
                                        srvrLog.Debugf("Unable to resolve "+
×
2925
                                                "host %v: %v", addr, err)
×
2926
                                        continue
×
2927
                                }
2928

2929
                                newAddrs = append(newAddrs, addr)
×
2930
                        }
2931

2932
                        // Skip the update if we weren't able to resolve any of
2933
                        // the new addresses.
2934
                        if len(newAddrs) == 0 {
×
2935
                                srvrLog.Debug("Skipping node announcement " +
×
2936
                                        "update due to not being able to " +
×
2937
                                        "resolve any new addresses")
×
2938
                                continue
×
2939
                        }
2940

2941
                        // Now, we'll need to update the addresses in our node's
2942
                        // announcement in order to propagate the update
2943
                        // throughout the network. We'll only include addresses
2944
                        // that have a different IP from the previous one, as
2945
                        // the previous IP is no longer valid.
2946
                        currentNodeAnn := s.getNodeAnnouncement()
×
2947

×
2948
                        for _, addr := range currentNodeAnn.Addresses {
×
2949
                                host, _, err := net.SplitHostPort(addr.String())
×
2950
                                if err != nil {
×
2951
                                        srvrLog.Debugf("Unable to determine "+
×
2952
                                                "host from address %v: %v",
×
2953
                                                addr, err)
×
2954
                                        continue
×
2955
                                }
2956

2957
                                // We'll also make sure to include external IPs
2958
                                // set manually by the user.
2959
                                _, setByUser := ipsSetByUser[addr.String()]
×
2960
                                if setByUser || host != s.lastDetectedIP.String() {
×
2961
                                        newAddrs = append(newAddrs, addr)
×
2962
                                }
×
2963
                        }
2964

2965
                        // Then, we'll generate a new timestamped node
2966
                        // announcement with the updated addresses and broadcast
2967
                        // it to our peers.
2968
                        newNodeAnn, err := s.genNodeAnnouncement(
×
2969
                                nil, netann.NodeAnnSetAddrs(newAddrs),
×
2970
                        )
×
2971
                        if err != nil {
×
2972
                                srvrLog.Debugf("Unable to generate new node "+
×
2973
                                        "announcement: %v", err)
×
2974
                                continue
×
2975
                        }
2976

2977
                        err = s.BroadcastMessage(nil, &newNodeAnn)
×
2978
                        if err != nil {
×
2979
                                srvrLog.Debugf("Unable to broadcast new node "+
×
2980
                                        "announcement to peers: %v", err)
×
2981
                                continue
×
2982
                        }
2983

2984
                        // Finally, update the last IP seen to the current one.
2985
                        s.lastDetectedIP = ip
×
2986
                case <-s.quit:
×
2987
                        break out
×
2988
                }
2989
        }
2990
}
2991

2992
// initNetworkBootstrappers initializes a set of network peer bootstrappers
2993
// based on the server, and currently active bootstrap mechanisms as defined
2994
// within the current configuration.
2995
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
×
2996
        srvrLog.Infof("Initializing peer network bootstrappers!")
×
2997

×
2998
        var bootStrappers []discovery.NetworkPeerBootstrapper
×
2999

×
3000
        // First, we'll create an instance of the ChannelGraphBootstrapper as
×
3001
        // this can be used by default if we've already partially seeded the
×
3002
        // network.
×
3003
        chanGraph := autopilot.ChannelGraphFromDatabase(s.graphDB)
×
3004
        graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
×
3005
        if err != nil {
×
3006
                return nil, err
×
3007
        }
×
3008
        bootStrappers = append(bootStrappers, graphBootstrapper)
×
3009

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

×
3015
                // If we have a set of DNS seeds for this chain, then we'll add
×
3016
                // it as an additional bootstrapping source.
×
3017
                if ok {
×
3018
                        srvrLog.Infof("Creating DNS peer bootstrapper with "+
×
3019
                                "seeds: %v", dnsSeeds)
×
3020

×
3021
                        dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
×
3022
                                dnsSeeds, s.cfg.net, s.cfg.ConnectionTimeout,
×
3023
                        )
×
3024
                        bootStrappers = append(bootStrappers, dnsBootStrapper)
×
3025
                }
×
3026
        }
3027

3028
        return bootStrappers, nil
×
3029
}
3030

3031
// createBootstrapIgnorePeers creates a map of peers that the bootstrap process
3032
// needs to ignore, which is made of three parts,
3033
//   - the node itself needs to be skipped as it doesn't make sense to connect
3034
//     to itself.
3035
//   - the peers that already have connections with, as in s.peersByPub.
3036
//   - the peers that we are attempting to connect, as in s.persistentPeers.
3037
func (s *server) createBootstrapIgnorePeers() map[autopilot.NodeID]struct{} {
×
3038
        s.mu.RLock()
×
3039
        defer s.mu.RUnlock()
×
3040

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

×
3043
        // We should ignore ourselves from bootstrapping.
×
3044
        selfKey := autopilot.NewNodeID(s.identityECDH.PubKey())
×
3045
        ignore[selfKey] = struct{}{}
×
3046

×
3047
        // Ignore all connected peers.
×
3048
        for _, peer := range s.peersByPub {
×
3049
                nID := autopilot.NewNodeID(peer.IdentityKey())
×
3050
                ignore[nID] = struct{}{}
×
3051
        }
×
3052

3053
        // Ignore all persistent peers as they have a dedicated reconnecting
3054
        // process.
3055
        for pubKeyStr := range s.persistentPeers {
×
3056
                var nID autopilot.NodeID
×
3057
                copy(nID[:], []byte(pubKeyStr))
×
3058
                ignore[nID] = struct{}{}
×
3059
        }
×
3060

3061
        return ignore
×
3062
}
3063

3064
// peerBootstrapper is a goroutine which is tasked with attempting to establish
3065
// and maintain a target minimum number of outbound connections. With this
3066
// invariant, we ensure that our node is connected to a diverse set of peers
3067
// and that nodes newly joining the network receive an up to date network view
3068
// as soon as possible.
3069
func (s *server) peerBootstrapper(numTargetPeers uint32,
3070
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3071

×
3072
        defer s.wg.Done()
×
3073

×
3074
        // Before we continue, init the ignore peers map.
×
3075
        ignoreList := s.createBootstrapIgnorePeers()
×
3076

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

×
3081
        // Once done, we'll attempt to maintain our target minimum number of
×
3082
        // peers.
×
3083
        //
×
3084
        // We'll use a 15 second backoff, and double the time every time an
×
3085
        // epoch fails up to a ceiling.
×
3086
        backOff := time.Second * 15
×
3087

×
3088
        // We'll create a new ticker to wake us up every 15 seconds so we can
×
3089
        // see if we've reached our minimum number of peers.
×
3090
        sampleTicker := time.NewTicker(backOff)
×
3091
        defer sampleTicker.Stop()
×
3092

×
3093
        // We'll use the number of attempts and errors to determine if we need
×
3094
        // to increase the time between discovery epochs.
×
3095
        var epochErrors uint32 // To be used atomically.
×
3096
        var epochAttempts uint32
×
3097

×
3098
        for {
×
3099
                select {
×
3100
                // The ticker has just woken us up, so we'll need to check if
3101
                // we need to attempt to connect our to any more peers.
3102
                case <-sampleTicker.C:
×
3103
                        // Obtain the current number of peers, so we can gauge
×
3104
                        // if we need to sample more peers or not.
×
3105
                        s.mu.RLock()
×
3106
                        numActivePeers := uint32(len(s.peersByPub))
×
3107
                        s.mu.RUnlock()
×
3108

×
3109
                        // If we have enough peers, then we can loop back
×
3110
                        // around to the next round as we're done here.
×
3111
                        if numActivePeers >= numTargetPeers {
×
3112
                                continue
×
3113
                        }
3114

3115
                        // If all of our attempts failed during this last back
3116
                        // off period, then will increase our backoff to 5
3117
                        // minute ceiling to avoid an excessive number of
3118
                        // queries
3119
                        //
3120
                        // TODO(roasbeef): add reverse policy too?
3121

3122
                        if epochAttempts > 0 &&
×
3123
                                atomic.LoadUint32(&epochErrors) >= epochAttempts {
×
3124

×
3125
                                sampleTicker.Stop()
×
3126

×
3127
                                backOff *= 2
×
3128
                                if backOff > bootstrapBackOffCeiling {
×
3129
                                        backOff = bootstrapBackOffCeiling
×
3130
                                }
×
3131

3132
                                srvrLog.Debugf("Backing off peer bootstrapper to "+
×
3133
                                        "%v", backOff)
×
3134
                                sampleTicker = time.NewTicker(backOff)
×
3135
                                continue
×
3136
                        }
3137

3138
                        atomic.StoreUint32(&epochErrors, 0)
×
3139
                        epochAttempts = 0
×
3140

×
3141
                        // Since we know need more peers, we'll compute the
×
3142
                        // exact number we need to reach our threshold.
×
3143
                        numNeeded := numTargetPeers - numActivePeers
×
3144

×
3145
                        srvrLog.Debugf("Attempting to obtain %v more network "+
×
3146
                                "peers", numNeeded)
×
3147

×
3148
                        // With the number of peers we need calculated, we'll
×
3149
                        // query the network bootstrappers to sample a set of
×
3150
                        // random addrs for us.
×
3151
                        //
×
3152
                        // Before we continue, get a copy of the ignore peers
×
3153
                        // map.
×
3154
                        ignoreList = s.createBootstrapIgnorePeers()
×
3155

×
3156
                        peerAddrs, err := discovery.MultiSourceBootstrap(
×
3157
                                ignoreList, numNeeded*2, bootstrappers...,
×
3158
                        )
×
3159
                        if err != nil {
×
3160
                                srvrLog.Errorf("Unable to retrieve bootstrap "+
×
3161
                                        "peers: %v", err)
×
3162
                                continue
×
3163
                        }
3164

3165
                        // Finally, we'll launch a new goroutine for each
3166
                        // prospective peer candidates.
3167
                        for _, addr := range peerAddrs {
×
3168
                                epochAttempts++
×
3169

×
3170
                                go func(a *lnwire.NetAddress) {
×
3171
                                        // TODO(roasbeef): can do AS, subnet,
×
3172
                                        // country diversity, etc
×
3173
                                        errChan := make(chan error, 1)
×
3174
                                        s.connectToPeer(
×
3175
                                                a, errChan,
×
3176
                                                s.cfg.ConnectionTimeout,
×
3177
                                        )
×
3178
                                        select {
×
3179
                                        case err := <-errChan:
×
3180
                                                if err == nil {
×
3181
                                                        return
×
3182
                                                }
×
3183

3184
                                                srvrLog.Errorf("Unable to "+
×
3185
                                                        "connect to %v: %v",
×
3186
                                                        a, err)
×
3187
                                                atomic.AddUint32(&epochErrors, 1)
×
3188
                                        case <-s.quit:
×
3189
                                        }
3190
                                }(addr)
3191
                        }
3192
                case <-s.quit:
×
3193
                        return
×
3194
                }
3195
        }
3196
}
3197

3198
// bootstrapBackOffCeiling is the maximum amount of time we'll wait between
3199
// failed attempts to locate a set of bootstrap peers. We'll slowly double our
3200
// query back off each time we encounter a failure.
3201
const bootstrapBackOffCeiling = time.Minute * 5
3202

3203
// initialPeerBootstrap attempts to continuously connect to peers on startup
3204
// until the target number of peers has been reached. This ensures that nodes
3205
// receive an up to date network view as soon as possible.
3206
func (s *server) initialPeerBootstrap(ignore map[autopilot.NodeID]struct{},
3207
        numTargetPeers uint32,
3208
        bootstrappers []discovery.NetworkPeerBootstrapper) {
×
3209

×
3210
        srvrLog.Debugf("Init bootstrap with targetPeers=%v, bootstrappers=%v, "+
×
3211
                "ignore=%v", numTargetPeers, len(bootstrappers), len(ignore))
×
3212

×
3213
        // We'll start off by waiting 2 seconds between failed attempts, then
×
3214
        // double each time we fail until we hit the bootstrapBackOffCeiling.
×
3215
        var delaySignal <-chan time.Time
×
3216
        delayTime := time.Second * 2
×
3217

×
3218
        // As want to be more aggressive, we'll use a lower back off celling
×
3219
        // then the main peer bootstrap logic.
×
3220
        backOffCeiling := bootstrapBackOffCeiling / 5
×
3221

×
3222
        for attempts := 0; ; attempts++ {
×
3223
                // Check if the server has been requested to shut down in order
×
3224
                // to prevent blocking.
×
3225
                if s.Stopped() {
×
3226
                        return
×
3227
                }
×
3228

3229
                // We can exit our aggressive initial peer bootstrapping stage
3230
                // if we've reached out target number of peers.
3231
                s.mu.RLock()
×
3232
                numActivePeers := uint32(len(s.peersByPub))
×
3233
                s.mu.RUnlock()
×
3234

×
3235
                if numActivePeers >= numTargetPeers {
×
3236
                        return
×
3237
                }
×
3238

3239
                if attempts > 0 {
×
3240
                        srvrLog.Debugf("Waiting %v before trying to locate "+
×
3241
                                "bootstrap peers (attempt #%v)", delayTime,
×
3242
                                attempts)
×
3243

×
3244
                        // We've completed at least one iterating and haven't
×
3245
                        // finished, so we'll start to insert a delay period
×
3246
                        // between each attempt.
×
3247
                        delaySignal = time.After(delayTime)
×
3248
                        select {
×
3249
                        case <-delaySignal:
×
3250
                        case <-s.quit:
×
3251
                                return
×
3252
                        }
3253

3254
                        // After our delay, we'll double the time we wait up to
3255
                        // the max back off period.
3256
                        delayTime *= 2
×
3257
                        if delayTime > backOffCeiling {
×
3258
                                delayTime = backOffCeiling
×
3259
                        }
×
3260
                }
3261

3262
                // Otherwise, we'll request for the remaining number of peers
3263
                // in order to reach our target.
3264
                peersNeeded := numTargetPeers - numActivePeers
×
3265
                bootstrapAddrs, err := discovery.MultiSourceBootstrap(
×
3266
                        ignore, peersNeeded, bootstrappers...,
×
3267
                )
×
3268
                if err != nil {
×
3269
                        srvrLog.Errorf("Unable to retrieve initial bootstrap "+
×
3270
                                "peers: %v", err)
×
3271
                        continue
×
3272
                }
3273

3274
                // Then, we'll attempt to establish a connection to the
3275
                // different peer addresses retrieved by our bootstrappers.
3276
                var wg sync.WaitGroup
×
3277
                for _, bootstrapAddr := range bootstrapAddrs {
×
3278
                        wg.Add(1)
×
3279
                        go func(addr *lnwire.NetAddress) {
×
3280
                                defer wg.Done()
×
3281

×
3282
                                errChan := make(chan error, 1)
×
3283
                                go s.connectToPeer(
×
3284
                                        addr, errChan, s.cfg.ConnectionTimeout,
×
3285
                                )
×
3286

×
3287
                                // We'll only allow this connection attempt to
×
3288
                                // take up to 3 seconds. This allows us to move
×
3289
                                // quickly by discarding peers that are slowing
×
3290
                                // us down.
×
3291
                                select {
×
3292
                                case err := <-errChan:
×
3293
                                        if err == nil {
×
3294
                                                return
×
3295
                                        }
×
3296
                                        srvrLog.Errorf("Unable to connect to "+
×
3297
                                                "%v: %v", addr, err)
×
3298
                                // TODO: tune timeout? 3 seconds might be *too*
3299
                                // aggressive but works well.
3300
                                case <-time.After(3 * time.Second):
×
3301
                                        srvrLog.Tracef("Skipping peer %v due "+
×
3302
                                                "to not establishing a "+
×
3303
                                                "connection within 3 seconds",
×
3304
                                                addr)
×
3305
                                case <-s.quit:
×
3306
                                }
3307
                        }(bootstrapAddr)
3308
                }
3309

3310
                wg.Wait()
×
3311
        }
3312
}
3313

3314
// createNewHiddenService automatically sets up a v2 or v3 onion service in
3315
// order to listen for inbound connections over Tor.
3316
func (s *server) createNewHiddenService() error {
×
3317
        // Determine the different ports the server is listening on. The onion
×
3318
        // service's virtual port will map to these ports and one will be picked
×
3319
        // at random when the onion service is being accessed.
×
3320
        listenPorts := make([]int, 0, len(s.listenAddrs))
×
3321
        for _, listenAddr := range s.listenAddrs {
×
3322
                port := listenAddr.(*net.TCPAddr).Port
×
3323
                listenPorts = append(listenPorts, port)
×
3324
        }
×
3325

3326
        encrypter, err := lnencrypt.KeyRingEncrypter(s.cc.KeyRing)
×
3327
        if err != nil {
×
3328
                return err
×
3329
        }
×
3330

3331
        // Once the port mapping has been set, we can go ahead and automatically
3332
        // create our onion service. The service's private key will be saved to
3333
        // disk in order to regain access to this service when restarting `lnd`.
3334
        onionCfg := tor.AddOnionConfig{
×
3335
                VirtualPort: defaultPeerPort,
×
3336
                TargetPorts: listenPorts,
×
3337
                Store: tor.NewOnionFile(
×
3338
                        s.cfg.Tor.PrivateKeyPath, 0600, s.cfg.Tor.EncryptKey,
×
3339
                        encrypter,
×
3340
                ),
×
3341
        }
×
3342

×
3343
        switch {
×
3344
        case s.cfg.Tor.V2:
×
3345
                onionCfg.Type = tor.V2
×
3346
        case s.cfg.Tor.V3:
×
3347
                onionCfg.Type = tor.V3
×
3348
        }
3349

3350
        addr, err := s.torController.AddOnion(onionCfg)
×
3351
        if err != nil {
×
3352
                return err
×
3353
        }
×
3354

3355
        // Now that the onion service has been created, we'll add the onion
3356
        // address it can be reached at to our list of advertised addresses.
3357
        newNodeAnn, err := s.genNodeAnnouncement(
×
3358
                nil, func(currentAnn *lnwire.NodeAnnouncement) {
×
3359
                        currentAnn.Addresses = append(currentAnn.Addresses, addr)
×
3360
                },
×
3361
        )
3362
        if err != nil {
×
3363
                return fmt.Errorf("unable to generate new node "+
×
3364
                        "announcement: %v", err)
×
3365
        }
×
3366

3367
        // Finally, we'll update the on-disk version of our announcement so it
3368
        // will eventually propagate to nodes in the network.
3369
        selfNode := &models.LightningNode{
×
3370
                HaveNodeAnnouncement: true,
×
3371
                LastUpdate:           time.Unix(int64(newNodeAnn.Timestamp), 0),
×
3372
                Addresses:            newNodeAnn.Addresses,
×
3373
                Alias:                newNodeAnn.Alias.String(),
×
3374
                Features: lnwire.NewFeatureVector(
×
3375
                        newNodeAnn.Features, lnwire.Features,
×
3376
                ),
×
3377
                Color:        newNodeAnn.RGBColor,
×
3378
                AuthSigBytes: newNodeAnn.Signature.ToSignatureBytes(),
×
3379
        }
×
3380
        copy(selfNode.PubKeyBytes[:], s.identityECDH.PubKey().SerializeCompressed())
×
3381
        if err := s.graphDB.SetSourceNode(selfNode); err != nil {
×
3382
                return fmt.Errorf("can't set self node: %w", err)
×
3383
        }
×
3384

3385
        return nil
×
3386
}
3387

3388
// findChannel finds a channel given a public key and ChannelID. It is an
3389
// optimization that is quicker than seeking for a channel given only the
3390
// ChannelID.
3391
func (s *server) findChannel(node *btcec.PublicKey, chanID lnwire.ChannelID) (
3392
        *channeldb.OpenChannel, error) {
3✔
3393

3✔
3394
        nodeChans, err := s.chanStateDB.FetchOpenChannels(node)
3✔
3395
        if err != nil {
3✔
3396
                return nil, err
×
3397
        }
×
3398

3399
        for _, channel := range nodeChans {
6✔
3400
                if chanID.IsChanPoint(&channel.FundingOutpoint) {
6✔
3401
                        return channel, nil
3✔
3402
                }
3✔
3403
        }
3404

3405
        return nil, fmt.Errorf("unable to find channel")
3✔
3406
}
3407

3408
// getNodeAnnouncement fetches the current, fully signed node announcement.
3409
func (s *server) getNodeAnnouncement() lnwire.NodeAnnouncement {
3✔
3410
        s.mu.Lock()
3✔
3411
        defer s.mu.Unlock()
3✔
3412

3✔
3413
        return *s.currentNodeAnn
3✔
3414
}
3✔
3415

3416
// genNodeAnnouncement generates and returns the current fully signed node
3417
// announcement. The time stamp of the announcement will be updated in order
3418
// to ensure it propagates through the network.
3419
func (s *server) genNodeAnnouncement(features *lnwire.RawFeatureVector,
3420
        modifiers ...netann.NodeAnnModifier) (lnwire.NodeAnnouncement, error) {
3✔
3421

3✔
3422
        s.mu.Lock()
3✔
3423
        defer s.mu.Unlock()
3✔
3424

3✔
3425
        // First, try to update our feature manager with the updated set of
3✔
3426
        // features.
3✔
3427
        if features != nil {
6✔
3428
                proposedFeatures := map[feature.Set]*lnwire.RawFeatureVector{
3✔
3429
                        feature.SetNodeAnn: features,
3✔
3430
                }
3✔
3431
                err := s.featureMgr.UpdateFeatureSets(proposedFeatures)
3✔
3432
                if err != nil {
6✔
3433
                        return lnwire.NodeAnnouncement{}, err
3✔
3434
                }
3✔
3435

3436
                // If we could successfully update our feature manager, add
3437
                // an update modifier to include these new features to our
3438
                // set.
3439
                modifiers = append(
3✔
3440
                        modifiers, netann.NodeAnnSetFeatures(features),
3✔
3441
                )
3✔
3442
        }
3443

3444
        // Always update the timestamp when refreshing to ensure the update
3445
        // propagates.
3446
        modifiers = append(modifiers, netann.NodeAnnSetTimestamp)
3✔
3447

3✔
3448
        // Apply the requested changes to the node announcement.
3✔
3449
        for _, modifier := range modifiers {
6✔
3450
                modifier(s.currentNodeAnn)
3✔
3451
        }
3✔
3452

3453
        // Sign a new update after applying all of the passed modifiers.
3454
        err := netann.SignNodeAnnouncement(
3✔
3455
                s.nodeSigner, s.identityKeyLoc, s.currentNodeAnn,
3✔
3456
        )
3✔
3457
        if err != nil {
3✔
3458
                return lnwire.NodeAnnouncement{}, err
×
3459
        }
×
3460

3461
        return *s.currentNodeAnn, nil
3✔
3462
}
3463

3464
// updateAndBroadcastSelfNode generates a new node announcement
3465
// applying the giving modifiers and updating the time stamp
3466
// to ensure it propagates through the network. Then it broadcasts
3467
// it to the network.
3468
func (s *server) updateAndBroadcastSelfNode(features *lnwire.RawFeatureVector,
3469
        modifiers ...netann.NodeAnnModifier) error {
3✔
3470

3✔
3471
        newNodeAnn, err := s.genNodeAnnouncement(features, modifiers...)
3✔
3472
        if err != nil {
6✔
3473
                return fmt.Errorf("unable to generate new node "+
3✔
3474
                        "announcement: %v", err)
3✔
3475
        }
3✔
3476

3477
        // Update the on-disk version of our announcement.
3478
        // Load and modify self node istead of creating anew instance so we
3479
        // don't risk overwriting any existing values.
3480
        selfNode, err := s.graphDB.SourceNode()
3✔
3481
        if err != nil {
3✔
3482
                return fmt.Errorf("unable to get current source node: %w", err)
×
3483
        }
×
3484

3485
        selfNode.HaveNodeAnnouncement = true
3✔
3486
        selfNode.LastUpdate = time.Unix(int64(newNodeAnn.Timestamp), 0)
3✔
3487
        selfNode.Addresses = newNodeAnn.Addresses
3✔
3488
        selfNode.Alias = newNodeAnn.Alias.String()
3✔
3489
        selfNode.Features = s.featureMgr.Get(feature.SetNodeAnn)
3✔
3490
        selfNode.Color = newNodeAnn.RGBColor
3✔
3491
        selfNode.AuthSigBytes = newNodeAnn.Signature.ToSignatureBytes()
3✔
3492

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

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

3499
        // Finally, propagate it to the nodes in the network.
3500
        err = s.BroadcastMessage(nil, &newNodeAnn)
3✔
3501
        if err != nil {
3✔
3502
                rpcsLog.Debugf("Unable to broadcast new node "+
×
3503
                        "announcement to peers: %v", err)
×
3504
                return err
×
3505
        }
×
3506

3507
        return nil
3✔
3508
}
3509

3510
type nodeAddresses struct {
3511
        pubKey    *btcec.PublicKey
3512
        addresses []net.Addr
3513
}
3514

3515
// establishPersistentConnections attempts to establish persistent connections
3516
// to all our direct channel collaborators. In order to promote liveness of our
3517
// active channels, we instruct the connection manager to attempt to establish
3518
// and maintain persistent connections to all our direct channel counterparties.
3519
func (s *server) establishPersistentConnections() error {
3✔
3520
        // nodeAddrsMap stores the combination of node public keys and addresses
3✔
3521
        // that we'll attempt to reconnect to. PubKey strings are used as keys
3✔
3522
        // since other PubKey forms can't be compared.
3✔
3523
        nodeAddrsMap := map[string]*nodeAddresses{}
3✔
3524

3✔
3525
        // Iterate through the list of LinkNodes to find addresses we should
3✔
3526
        // attempt to connect to based on our set of previous connections. Set
3✔
3527
        // the reconnection port to the default peer port.
3✔
3528
        linkNodes, err := s.chanStateDB.LinkNodeDB().FetchAllLinkNodes()
3✔
3529
        if err != nil && err != channeldb.ErrLinkNodesNotFound {
3✔
3530
                return err
×
3531
        }
×
3532
        for _, node := range linkNodes {
6✔
3533
                pubStr := string(node.IdentityPub.SerializeCompressed())
3✔
3534
                nodeAddrs := &nodeAddresses{
3✔
3535
                        pubKey:    node.IdentityPub,
3✔
3536
                        addresses: node.Addresses,
3✔
3537
                }
3✔
3538
                nodeAddrsMap[pubStr] = nodeAddrs
3✔
3539
        }
3✔
3540

3541
        // After checking our previous connections for addresses to connect to,
3542
        // iterate through the nodes in our channel graph to find addresses
3543
        // that have been added via NodeAnnouncement messages.
3544
        sourceNode, err := s.graphDB.SourceNode()
3✔
3545
        if err != nil {
3✔
3546
                return err
×
3547
        }
×
3548

3549
        // TODO(roasbeef): instead iterate over link nodes and query graph for
3550
        // each of the nodes.
3551
        selfPub := s.identityECDH.PubKey().SerializeCompressed()
3✔
3552
        err = s.graphDB.ForEachNodeChannel(sourceNode.PubKeyBytes, func(
3✔
3553
                tx kvdb.RTx,
3✔
3554
                chanInfo *models.ChannelEdgeInfo,
3✔
3555
                policy, _ *models.ChannelEdgePolicy) error {
6✔
3556

3✔
3557
                // If the remote party has announced the channel to us, but we
3✔
3558
                // haven't yet, then we won't have a policy. However, we don't
3✔
3559
                // need this to connect to the peer, so we'll log it and move on.
3✔
3560
                if policy == nil {
3✔
3561
                        srvrLog.Warnf("No channel policy found for "+
×
3562
                                "ChannelPoint(%v): ", chanInfo.ChannelPoint)
×
3563
                }
×
3564

3565
                // We'll now fetch the peer opposite from us within this
3566
                // channel so we can queue up a direct connection to them.
3567
                channelPeer, err := s.graphDB.FetchOtherNode(
3✔
3568
                        tx, chanInfo, selfPub,
3✔
3569
                )
3✔
3570
                if err != nil {
3✔
3571
                        return fmt.Errorf("unable to fetch channel peer for "+
×
3572
                                "ChannelPoint(%v): %v", chanInfo.ChannelPoint,
×
3573
                                err)
×
3574
                }
×
3575

3576
                pubStr := string(channelPeer.PubKeyBytes[:])
3✔
3577

3✔
3578
                // Add all unique addresses from channel
3✔
3579
                // graph/NodeAnnouncements to the list of addresses we'll
3✔
3580
                // connect to for this peer.
3✔
3581
                addrSet := make(map[string]net.Addr)
3✔
3582
                for _, addr := range channelPeer.Addresses {
6✔
3583
                        switch addr.(type) {
3✔
3584
                        case *net.TCPAddr:
3✔
3585
                                addrSet[addr.String()] = addr
3✔
3586

3587
                        // We'll only attempt to connect to Tor addresses if Tor
3588
                        // outbound support is enabled.
3589
                        case *tor.OnionAddr:
×
3590
                                if s.cfg.Tor.Active {
×
3591
                                        addrSet[addr.String()] = addr
×
3592
                                }
×
3593
                        }
3594
                }
3595

3596
                // If this peer is also recorded as a link node, we'll add any
3597
                // additional addresses that have not already been selected.
3598
                linkNodeAddrs, ok := nodeAddrsMap[pubStr]
3✔
3599
                if ok {
6✔
3600
                        for _, lnAddress := range linkNodeAddrs.addresses {
6✔
3601
                                switch lnAddress.(type) {
3✔
3602
                                case *net.TCPAddr:
3✔
3603
                                        addrSet[lnAddress.String()] = lnAddress
3✔
3604

3605
                                // We'll only attempt to connect to Tor
3606
                                // addresses if Tor outbound support is enabled.
3607
                                case *tor.OnionAddr:
×
3608
                                        if s.cfg.Tor.Active {
×
3609
                                                addrSet[lnAddress.String()] = lnAddress
×
3610
                                        }
×
3611
                                }
3612
                        }
3613
                }
3614

3615
                // Construct a slice of the deduped addresses.
3616
                var addrs []net.Addr
3✔
3617
                for _, addr := range addrSet {
6✔
3618
                        addrs = append(addrs, addr)
3✔
3619
                }
3✔
3620

3621
                n := &nodeAddresses{
3✔
3622
                        addresses: addrs,
3✔
3623
                }
3✔
3624
                n.pubKey, err = channelPeer.PubKey()
3✔
3625
                if err != nil {
3✔
3626
                        return err
×
3627
                }
×
3628

3629
                nodeAddrsMap[pubStr] = n
3✔
3630
                return nil
3✔
3631
        })
3632
        if err != nil && !errors.Is(err, graphdb.ErrGraphNoEdgesFound) {
3✔
3633
                return err
×
3634
        }
×
3635

3636
        srvrLog.Debugf("Establishing %v persistent connections on start",
3✔
3637
                len(nodeAddrsMap))
3✔
3638

3✔
3639
        // Acquire and hold server lock until all persistent connection requests
3✔
3640
        // have been recorded and sent to the connection manager.
3✔
3641
        s.mu.Lock()
3✔
3642
        defer s.mu.Unlock()
3✔
3643

3✔
3644
        // Iterate through the combined list of addresses from prior links and
3✔
3645
        // node announcements and attempt to reconnect to each node.
3✔
3646
        var numOutboundConns int
3✔
3647
        for pubStr, nodeAddr := range nodeAddrsMap {
6✔
3648
                // Add this peer to the set of peers we should maintain a
3✔
3649
                // persistent connection with. We set the value to false to
3✔
3650
                // indicate that we should not continue to reconnect if the
3✔
3651
                // number of channels returns to zero, since this peer has not
3✔
3652
                // been requested as perm by the user.
3✔
3653
                s.persistentPeers[pubStr] = false
3✔
3654
                if _, ok := s.persistentPeersBackoff[pubStr]; !ok {
6✔
3655
                        s.persistentPeersBackoff[pubStr] = s.cfg.MinBackoff
3✔
3656
                }
3✔
3657

3658
                for _, address := range nodeAddr.addresses {
6✔
3659
                        // Create a wrapper address which couples the IP and
3✔
3660
                        // the pubkey so the brontide authenticated connection
3✔
3661
                        // can be established.
3✔
3662
                        lnAddr := &lnwire.NetAddress{
3✔
3663
                                IdentityKey: nodeAddr.pubKey,
3✔
3664
                                Address:     address,
3✔
3665
                        }
3✔
3666

3✔
3667
                        s.persistentPeerAddrs[pubStr] = append(
3✔
3668
                                s.persistentPeerAddrs[pubStr], lnAddr)
3✔
3669
                }
3✔
3670

3671
                // We'll connect to the first 10 peers immediately, then
3672
                // randomly stagger any remaining connections if the
3673
                // stagger initial reconnect flag is set. This ensures
3674
                // that mobile nodes or nodes with a small number of
3675
                // channels obtain connectivity quickly, but larger
3676
                // nodes are able to disperse the costs of connecting to
3677
                // all peers at once.
3678
                if numOutboundConns < numInstantInitReconnect ||
3✔
3679
                        !s.cfg.StaggerInitialReconnect {
6✔
3680

3✔
3681
                        go s.connectToPersistentPeer(pubStr)
3✔
3682
                } else {
3✔
3683
                        go s.delayInitialReconnect(pubStr)
×
3684
                }
×
3685

3686
                numOutboundConns++
3✔
3687
        }
3688

3689
        return nil
3✔
3690
}
3691

3692
// delayInitialReconnect will attempt a reconnection to the given peer after
3693
// sampling a value for the delay between 0s and the maxInitReconnectDelay.
3694
//
3695
// NOTE: This method MUST be run as a goroutine.
3696
func (s *server) delayInitialReconnect(pubStr string) {
×
3697
        delay := time.Duration(prand.Intn(maxInitReconnectDelay)) * time.Second
×
3698
        select {
×
3699
        case <-time.After(delay):
×
3700
                s.connectToPersistentPeer(pubStr)
×
3701
        case <-s.quit:
×
3702
        }
3703
}
3704

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

3✔
3711
        s.mu.Lock()
3✔
3712
        if perm, ok := s.persistentPeers[pubKeyStr]; ok && !perm {
6✔
3713
                delete(s.persistentPeers, pubKeyStr)
3✔
3714
                delete(s.persistentPeersBackoff, pubKeyStr)
3✔
3715
                delete(s.persistentPeerAddrs, pubKeyStr)
3✔
3716
                s.cancelConnReqs(pubKeyStr, nil)
3✔
3717
                s.mu.Unlock()
3✔
3718

3✔
3719
                srvrLog.Infof("Pruned peer %x from persistent connections, "+
3✔
3720
                        "peer has no open channels", compressedPubKey)
3✔
3721

3✔
3722
                return
3✔
3723
        }
3✔
3724
        s.mu.Unlock()
3✔
3725
}
3726

3727
// bannedPersistentPeerConnection does not actually "ban" a persistent peer. It
3728
// is instead used to remove persistent peer state for a peer that has been
3729
// disconnected for good cause by the server. Currently, a gossip ban from
3730
// sending garbage and the server running out of restricted-access
3731
// (i.e. "free") connection slots are the only way this logic gets hit. In the
3732
// future, this function may expand when more ban criteria is added.
3733
//
3734
// NOTE: The server's write lock MUST be held when this is called.
3735
func (s *server) bannedPersistentPeerConnection(remotePub string) {
×
3736
        if perm, ok := s.persistentPeers[remotePub]; ok && !perm {
×
3737
                delete(s.persistentPeers, remotePub)
×
3738
                delete(s.persistentPeersBackoff, remotePub)
×
3739
                delete(s.persistentPeerAddrs, remotePub)
×
3740
                s.cancelConnReqs(remotePub, nil)
×
3741
        }
×
3742
}
3743

3744
// BroadcastMessage sends a request to the server to broadcast a set of
3745
// messages to all peers other than the one specified by the `skips` parameter.
3746
// All messages sent via BroadcastMessage will be queued for lazy delivery to
3747
// the target peers.
3748
//
3749
// NOTE: This function is safe for concurrent access.
3750
func (s *server) BroadcastMessage(skips map[route.Vertex]struct{},
3751
        msgs ...lnwire.Message) error {
3✔
3752

3✔
3753
        // Filter out peers found in the skips map. We synchronize access to
3✔
3754
        // peersByPub throughout this process to ensure we deliver messages to
3✔
3755
        // exact set of peers present at the time of invocation.
3✔
3756
        s.mu.RLock()
3✔
3757
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
3758
        for pubStr, sPeer := range s.peersByPub {
6✔
3759
                if skips != nil {
6✔
3760
                        if _, ok := skips[sPeer.PubKey()]; ok {
6✔
3761
                                srvrLog.Tracef("Skipping %x in broadcast with "+
3✔
3762
                                        "pubStr=%x", sPeer.PubKey(), pubStr)
3✔
3763
                                continue
3✔
3764
                        }
3765
                }
3766

3767
                peers = append(peers, sPeer)
3✔
3768
        }
3769
        s.mu.RUnlock()
3✔
3770

3✔
3771
        // Iterate over all known peers, dispatching a go routine to enqueue
3✔
3772
        // all messages to each of peers.
3✔
3773
        var wg sync.WaitGroup
3✔
3774
        for _, sPeer := range peers {
6✔
3775
                srvrLog.Debugf("Sending %v messages to peer %x", len(msgs),
3✔
3776
                        sPeer.PubKey())
3✔
3777

3✔
3778
                // Dispatch a go routine to enqueue all messages to this peer.
3✔
3779
                wg.Add(1)
3✔
3780
                s.wg.Add(1)
3✔
3781
                go func(p lnpeer.Peer) {
6✔
3782
                        defer s.wg.Done()
3✔
3783
                        defer wg.Done()
3✔
3784

3✔
3785
                        p.SendMessageLazy(false, msgs...)
3✔
3786
                }(sPeer)
3✔
3787
        }
3788

3789
        // Wait for all messages to have been dispatched before returning to
3790
        // caller.
3791
        wg.Wait()
3✔
3792

3✔
3793
        return nil
3✔
3794
}
3795

3796
// NotifyWhenOnline can be called by other subsystems to get notified when a
3797
// particular peer comes online. The peer itself is sent across the peerChan.
3798
//
3799
// NOTE: This function is safe for concurrent access.
3800
func (s *server) NotifyWhenOnline(peerKey [33]byte,
3801
        peerChan chan<- lnpeer.Peer) {
3✔
3802

3✔
3803
        s.mu.Lock()
3✔
3804

3✔
3805
        // Compute the target peer's identifier.
3✔
3806
        pubStr := string(peerKey[:])
3✔
3807

3✔
3808
        // Check if peer is connected.
3✔
3809
        peer, ok := s.peersByPub[pubStr]
3✔
3810
        if ok {
6✔
3811
                // Unlock here so that the mutex isn't held while we are
3✔
3812
                // waiting for the peer to become active.
3✔
3813
                s.mu.Unlock()
3✔
3814

3✔
3815
                // Wait until the peer signals that it is actually active
3✔
3816
                // rather than only in the server's maps.
3✔
3817
                select {
3✔
3818
                case <-peer.ActiveSignal():
3✔
3819
                case <-peer.QuitSignal():
1✔
3820
                        // The peer quit, so we'll add the channel to the slice
1✔
3821
                        // and return.
1✔
3822
                        s.mu.Lock()
1✔
3823
                        s.peerConnectedListeners[pubStr] = append(
1✔
3824
                                s.peerConnectedListeners[pubStr], peerChan,
1✔
3825
                        )
1✔
3826
                        s.mu.Unlock()
1✔
3827
                        return
1✔
3828
                }
3829

3830
                // Connected, can return early.
3831
                srvrLog.Debugf("Notifying that peer %x is online", peerKey)
3✔
3832

3✔
3833
                select {
3✔
3834
                case peerChan <- peer:
3✔
3835
                case <-s.quit:
×
3836
                }
3837

3838
                return
3✔
3839
        }
3840

3841
        // Not connected, store this listener such that it can be notified when
3842
        // the peer comes online.
3843
        s.peerConnectedListeners[pubStr] = append(
3✔
3844
                s.peerConnectedListeners[pubStr], peerChan,
3✔
3845
        )
3✔
3846
        s.mu.Unlock()
3✔
3847
}
3848

3849
// NotifyWhenOffline delivers a notification to the caller of when the peer with
3850
// the given public key has been disconnected. The notification is signaled by
3851
// closing the channel returned.
3852
func (s *server) NotifyWhenOffline(peerPubKey [33]byte) <-chan struct{} {
3✔
3853
        s.mu.Lock()
3✔
3854
        defer s.mu.Unlock()
3✔
3855

3✔
3856
        c := make(chan struct{})
3✔
3857

3✔
3858
        // If the peer is already offline, we can immediately trigger the
3✔
3859
        // notification.
3✔
3860
        peerPubKeyStr := string(peerPubKey[:])
3✔
3861
        if _, ok := s.peersByPub[peerPubKeyStr]; !ok {
3✔
3862
                srvrLog.Debugf("Notifying that peer %x is offline", peerPubKey)
×
3863
                close(c)
×
3864
                return c
×
3865
        }
×
3866

3867
        // Otherwise, the peer is online, so we'll keep track of the channel to
3868
        // trigger the notification once the server detects the peer
3869
        // disconnects.
3870
        s.peerDisconnectedListeners[peerPubKeyStr] = append(
3✔
3871
                s.peerDisconnectedListeners[peerPubKeyStr], c,
3✔
3872
        )
3✔
3873

3✔
3874
        return c
3✔
3875
}
3876

3877
// FindPeer will return the peer that corresponds to the passed in public key.
3878
// This function is used by the funding manager, allowing it to update the
3879
// daemon's local representation of the remote peer.
3880
//
3881
// NOTE: This function is safe for concurrent access.
3882
func (s *server) FindPeer(peerKey *btcec.PublicKey) (*peer.Brontide, error) {
3✔
3883
        s.mu.RLock()
3✔
3884
        defer s.mu.RUnlock()
3✔
3885

3✔
3886
        pubStr := string(peerKey.SerializeCompressed())
3✔
3887

3✔
3888
        return s.findPeerByPubStr(pubStr)
3✔
3889
}
3✔
3890

3891
// FindPeerByPubStr will return the peer that corresponds to the passed peerID,
3892
// which should be a string representation of the peer's serialized, compressed
3893
// public key.
3894
//
3895
// NOTE: This function is safe for concurrent access.
3896
func (s *server) FindPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3897
        s.mu.RLock()
3✔
3898
        defer s.mu.RUnlock()
3✔
3899

3✔
3900
        return s.findPeerByPubStr(pubStr)
3✔
3901
}
3✔
3902

3903
// findPeerByPubStr is an internal method that retrieves the specified peer from
3904
// the server's internal state using.
3905
func (s *server) findPeerByPubStr(pubStr string) (*peer.Brontide, error) {
3✔
3906
        peer, ok := s.peersByPub[pubStr]
3✔
3907
        if !ok {
6✔
3908
                return nil, ErrPeerNotConnected
3✔
3909
        }
3✔
3910

3911
        return peer, nil
3✔
3912
}
3913

3914
// nextPeerBackoff computes the next backoff duration for a peer's pubkey using
3915
// exponential backoff. If no previous backoff was known, the default is
3916
// returned.
3917
func (s *server) nextPeerBackoff(pubStr string,
3918
        startTime time.Time) time.Duration {
3✔
3919

3✔
3920
        // Now, determine the appropriate backoff to use for the retry.
3✔
3921
        backoff, ok := s.persistentPeersBackoff[pubStr]
3✔
3922
        if !ok {
6✔
3923
                // If an existing backoff was unknown, use the default.
3✔
3924
                return s.cfg.MinBackoff
3✔
3925
        }
3✔
3926

3927
        // If the peer failed to start properly, we'll just use the previous
3928
        // backoff to compute the subsequent randomized exponential backoff
3929
        // duration. This will roughly double on average.
3930
        if startTime.IsZero() {
3✔
3931
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
×
3932
        }
×
3933

3934
        // The peer succeeded in starting. If the connection didn't last long
3935
        // enough to be considered stable, we'll continue to back off retries
3936
        // with this peer.
3937
        connDuration := time.Since(startTime)
3✔
3938
        if connDuration < defaultStableConnDuration {
6✔
3939
                return computeNextBackoff(backoff, s.cfg.MaxBackoff)
3✔
3940
        }
3✔
3941

3942
        // The peer succeed in starting and this was stable peer, so we'll
3943
        // reduce the timeout duration by the length of the connection after
3944
        // applying randomized exponential backoff. We'll only apply this in the
3945
        // case that:
3946
        //   reb(curBackoff) - connDuration > cfg.MinBackoff
3947
        relaxedBackoff := computeNextBackoff(backoff, s.cfg.MaxBackoff) - connDuration
×
3948
        if relaxedBackoff > s.cfg.MinBackoff {
×
3949
                return relaxedBackoff
×
3950
        }
×
3951

3952
        // Lastly, if reb(currBackoff) - connDuration <= cfg.MinBackoff, meaning
3953
        // the stable connection lasted much longer than our previous backoff.
3954
        // To reward such good behavior, we'll reconnect after the default
3955
        // timeout.
3956
        return s.cfg.MinBackoff
×
3957
}
3958

3959
// shouldDropLocalConnection determines if our local connection to a remote peer
3960
// should be dropped in the case of concurrent connection establishment. In
3961
// order to deterministically decide which connection should be dropped, we'll
3962
// utilize the ordering of the local and remote public key. If we didn't use
3963
// such a tie breaker, then we risk _both_ connections erroneously being
3964
// dropped.
3965
func shouldDropLocalConnection(local, remote *btcec.PublicKey) bool {
×
3966
        localPubBytes := local.SerializeCompressed()
×
3967
        remotePubPbytes := remote.SerializeCompressed()
×
3968

×
3969
        // The connection that comes from the node with a "smaller" pubkey
×
3970
        // should be kept. Therefore, if our pubkey is "greater" than theirs, we
×
3971
        // should drop our established connection.
×
3972
        return bytes.Compare(localPubBytes, remotePubPbytes) > 0
×
3973
}
×
3974

3975
// InboundPeerConnected initializes a new peer in response to a new inbound
3976
// connection.
3977
//
3978
// NOTE: This function is safe for concurrent access.
3979
func (s *server) InboundPeerConnected(conn net.Conn) {
3✔
3980
        // Exit early if we have already been instructed to shutdown, this
3✔
3981
        // prevents any delayed callbacks from accidentally registering peers.
3✔
3982
        if s.Stopped() {
3✔
3983
                return
×
3984
        }
×
3985

3986
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
3987
        pubSer := nodePub.SerializeCompressed()
3✔
3988
        pubStr := string(pubSer)
3✔
3989

3✔
3990
        var pubBytes [33]byte
3✔
3991
        copy(pubBytes[:], pubSer)
3✔
3992

3✔
3993
        s.mu.Lock()
3✔
3994
        defer s.mu.Unlock()
3✔
3995

3✔
3996
        // If the remote node's public key is banned, drop the connection.
3✔
3997
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
3998
        if err != nil {
3✔
3999
                // Clean up the persistent peer maps if we're dropping this
×
4000
                // connection.
×
4001
                s.bannedPersistentPeerConnection(pubStr)
×
4002

×
4003
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4004
                        "of restricted-access connection slots: %v.", pubSer,
×
4005
                        err)
×
4006

×
4007
                conn.Close()
×
4008

×
4009
                return
×
4010
        }
×
4011

4012
        // If we already have an outbound connection to this peer, then ignore
4013
        // this new connection.
4014
        if p, ok := s.outboundPeers[pubStr]; ok {
6✔
4015
                srvrLog.Debugf("Already have outbound connection for %v, "+
3✔
4016
                        "ignoring inbound connection from local=%v, remote=%v",
3✔
4017
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4018

3✔
4019
                conn.Close()
3✔
4020
                return
3✔
4021
        }
3✔
4022

4023
        // If we already have a valid connection that is scheduled to take
4024
        // precedence once the prior peer has finished disconnecting, we'll
4025
        // ignore this connection.
4026
        if p, ok := s.scheduledPeerConnection[pubStr]; ok {
3✔
4027
                srvrLog.Debugf("Ignoring connection from %v, peer %v already "+
×
4028
                        "scheduled", conn.RemoteAddr(), p)
×
4029
                conn.Close()
×
4030
                return
×
4031
        }
×
4032

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

3✔
4035
        // Check to see if we already have a connection with this peer. If so,
3✔
4036
        // we may need to drop our existing connection. This prevents us from
3✔
4037
        // having duplicate connections to the same peer. We forgo adding a
3✔
4038
        // default case as we expect these to be the only error values returned
3✔
4039
        // from findPeerByPubStr.
3✔
4040
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4041
        switch err {
3✔
4042
        case ErrPeerNotConnected:
3✔
4043
                // We were unable to locate an existing connection with the
3✔
4044
                // target peer, proceed to connect.
3✔
4045
                s.cancelConnReqs(pubStr, nil)
3✔
4046
                s.peerConnected(conn, nil, true, access)
3✔
4047

4048
        case nil:
×
4049
                // We already have a connection with the incoming peer. If the
×
4050
                // connection we've already established should be kept and is
×
4051
                // not of the same type of the new connection (inbound), then
×
4052
                // we'll close out the new connection s.t there's only a single
×
4053
                // connection between us.
×
4054
                localPub := s.identityECDH.PubKey()
×
4055
                if !connectedPeer.Inbound() &&
×
4056
                        !shouldDropLocalConnection(localPub, nodePub) {
×
4057

×
4058
                        srvrLog.Warnf("Received inbound connection from "+
×
4059
                                "peer %v, but already have outbound "+
×
4060
                                "connection, dropping conn", connectedPeer)
×
4061
                        conn.Close()
×
4062
                        return
×
4063
                }
×
4064

4065
                // Otherwise, if we should drop the connection, then we'll
4066
                // disconnect our already connected peer.
4067
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4068
                        connectedPeer)
×
4069

×
4070
                s.cancelConnReqs(pubStr, nil)
×
4071

×
4072
                // Remove the current peer from the server's internal state and
×
4073
                // signal that the peer termination watcher does not need to
×
4074
                // execute for this peer.
×
4075
                s.removePeer(connectedPeer)
×
4076
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4077
                s.scheduledPeerConnection[pubStr] = func() {
×
4078
                        s.peerConnected(conn, nil, true, access)
×
4079
                }
×
4080
        }
4081
}
4082

4083
// OutboundPeerConnected initializes a new peer in response to a new outbound
4084
// connection.
4085
// NOTE: This function is safe for concurrent access.
4086
func (s *server) OutboundPeerConnected(connReq *connmgr.ConnReq, conn net.Conn) {
3✔
4087
        // Exit early if we have already been instructed to shutdown, this
3✔
4088
        // prevents any delayed callbacks from accidentally registering peers.
3✔
4089
        if s.Stopped() {
3✔
4090
                return
×
4091
        }
×
4092

4093
        nodePub := conn.(*brontide.Conn).RemotePub()
3✔
4094
        pubSer := nodePub.SerializeCompressed()
3✔
4095
        pubStr := string(pubSer)
3✔
4096

3✔
4097
        var pubBytes [33]byte
3✔
4098
        copy(pubBytes[:], pubSer)
3✔
4099

3✔
4100
        s.mu.Lock()
3✔
4101
        defer s.mu.Unlock()
3✔
4102

3✔
4103
        access, err := s.peerAccessMan.assignPeerPerms(nodePub)
3✔
4104
        if err != nil {
3✔
4105
                // Clean up the persistent peer maps if we're dropping this
×
4106
                // connection.
×
4107
                s.bannedPersistentPeerConnection(pubStr)
×
4108

×
4109
                srvrLog.Debugf("Dropping connection for %x since we are out "+
×
4110
                        "of restricted-access connection slots: %v.", pubSer,
×
4111
                        err)
×
4112

×
4113
                if connReq != nil {
×
4114
                        s.connMgr.Remove(connReq.ID())
×
4115
                }
×
4116

4117
                conn.Close()
×
4118

×
4119
                return
×
4120
        }
4121

4122
        // If we already have an inbound connection to this peer, then ignore
4123
        // this new connection.
4124
        if p, ok := s.inboundPeers[pubStr]; ok {
6✔
4125
                srvrLog.Debugf("Already have inbound connection for %v, "+
3✔
4126
                        "ignoring outbound connection from local=%v, remote=%v",
3✔
4127
                        p, conn.LocalAddr(), conn.RemoteAddr())
3✔
4128

3✔
4129
                if connReq != nil {
6✔
4130
                        s.connMgr.Remove(connReq.ID())
3✔
4131
                }
3✔
4132
                conn.Close()
3✔
4133
                return
3✔
4134
        }
4135
        if _, ok := s.persistentConnReqs[pubStr]; !ok && connReq != nil {
3✔
4136
                srvrLog.Debugf("Ignoring canceled outbound connection")
×
4137
                s.connMgr.Remove(connReq.ID())
×
4138
                conn.Close()
×
4139
                return
×
4140
        }
×
4141

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

×
4148
                if connReq != nil {
×
4149
                        s.connMgr.Remove(connReq.ID())
×
4150
                }
×
4151

4152
                conn.Close()
×
4153
                return
×
4154
        }
4155

4156
        srvrLog.Infof("Established connection to: %x@%v", pubStr,
3✔
4157
                conn.RemoteAddr())
3✔
4158

3✔
4159
        if connReq != nil {
6✔
4160
                // A successful connection was returned by the connmgr.
3✔
4161
                // Immediately cancel all pending requests, excluding the
3✔
4162
                // outbound connection we just established.
3✔
4163
                ignore := connReq.ID()
3✔
4164
                s.cancelConnReqs(pubStr, &ignore)
3✔
4165
        } else {
6✔
4166
                // This was a successful connection made by some other
3✔
4167
                // subsystem. Remove all requests being managed by the connmgr.
3✔
4168
                s.cancelConnReqs(pubStr, nil)
3✔
4169
        }
3✔
4170

4171
        // If we already have a connection with this peer, decide whether or not
4172
        // we need to drop the stale connection. We forgo adding a default case
4173
        // as we expect these to be the only error values returned from
4174
        // findPeerByPubStr.
4175
        connectedPeer, err := s.findPeerByPubStr(pubStr)
3✔
4176
        switch err {
3✔
4177
        case ErrPeerNotConnected:
3✔
4178
                // We were unable to locate an existing connection with the
3✔
4179
                // target peer, proceed to connect.
3✔
4180
                s.peerConnected(conn, connReq, false, access)
3✔
4181

4182
        case nil:
×
4183
                // We already have a connection with the incoming peer. If the
×
4184
                // connection we've already established should be kept and is
×
4185
                // not of the same type of the new connection (outbound), then
×
4186
                // we'll close out the new connection s.t there's only a single
×
4187
                // connection between us.
×
4188
                localPub := s.identityECDH.PubKey()
×
4189
                if connectedPeer.Inbound() &&
×
4190
                        shouldDropLocalConnection(localPub, nodePub) {
×
4191

×
4192
                        srvrLog.Warnf("Established outbound connection to "+
×
4193
                                "peer %v, but already have inbound "+
×
4194
                                "connection, dropping conn", connectedPeer)
×
4195
                        if connReq != nil {
×
4196
                                s.connMgr.Remove(connReq.ID())
×
4197
                        }
×
4198
                        conn.Close()
×
4199
                        return
×
4200
                }
4201

4202
                // Otherwise, _their_ connection should be dropped. So we'll
4203
                // disconnect the peer and send the now obsolete peer to the
4204
                // server for garbage collection.
4205
                srvrLog.Debugf("Disconnecting stale connection to %v",
×
4206
                        connectedPeer)
×
4207

×
4208
                // Remove the current peer from the server's internal state and
×
4209
                // signal that the peer termination watcher does not need to
×
4210
                // execute for this peer.
×
4211
                s.removePeer(connectedPeer)
×
4212
                s.ignorePeerTermination[connectedPeer] = struct{}{}
×
4213
                s.scheduledPeerConnection[pubStr] = func() {
×
4214
                        s.peerConnected(conn, connReq, false, access)
×
4215
                }
×
4216
        }
4217
}
4218

4219
// UnassignedConnID is the default connection ID that a request can have before
4220
// it actually is submitted to the connmgr.
4221
// TODO(conner): move into connmgr package, or better, add connmgr method for
4222
// generating atomic IDs
4223
const UnassignedConnID uint64 = 0
4224

4225
// cancelConnReqs stops all persistent connection requests for a given pubkey.
4226
// Any attempts initiated by the peerTerminationWatcher are canceled first.
4227
// Afterwards, each connection request removed from the connmgr. The caller can
4228
// optionally specify a connection ID to ignore, which prevents us from
4229
// canceling a successful request. All persistent connreqs for the provided
4230
// pubkey are discarded after the operationjw.
4231
func (s *server) cancelConnReqs(pubStr string, skip *uint64) {
3✔
4232
        // First, cancel any lingering persistent retry attempts, which will
3✔
4233
        // prevent retries for any with backoffs that are still maturing.
3✔
4234
        if cancelChan, ok := s.persistentRetryCancels[pubStr]; ok {
6✔
4235
                close(cancelChan)
3✔
4236
                delete(s.persistentRetryCancels, pubStr)
3✔
4237
        }
3✔
4238

4239
        // Next, check to see if we have any outstanding persistent connection
4240
        // requests to this peer. If so, then we'll remove all of these
4241
        // connection requests, and also delete the entry from the map.
4242
        connReqs, ok := s.persistentConnReqs[pubStr]
3✔
4243
        if !ok {
6✔
4244
                return
3✔
4245
        }
3✔
4246

4247
        for _, connReq := range connReqs {
6✔
4248
                srvrLog.Tracef("Canceling %s:", connReqs)
3✔
4249

3✔
4250
                // Atomically capture the current request identifier.
3✔
4251
                connID := connReq.ID()
3✔
4252

3✔
4253
                // Skip any zero IDs, this indicates the request has not
3✔
4254
                // yet been schedule.
3✔
4255
                if connID == UnassignedConnID {
3✔
4256
                        continue
×
4257
                }
4258

4259
                // Skip a particular connection ID if instructed.
4260
                if skip != nil && connID == *skip {
6✔
4261
                        continue
3✔
4262
                }
4263

4264
                s.connMgr.Remove(connID)
3✔
4265
        }
4266

4267
        delete(s.persistentConnReqs, pubStr)
3✔
4268
}
4269

4270
// handleCustomMessage dispatches an incoming custom peers message to
4271
// subscribers.
4272
func (s *server) handleCustomMessage(peer [33]byte, msg *lnwire.Custom) error {
3✔
4273
        srvrLog.Debugf("Custom message received: peer=%x, type=%d",
3✔
4274
                peer, msg.Type)
3✔
4275

3✔
4276
        return s.customMessageServer.SendUpdate(&CustomMessage{
3✔
4277
                Peer: peer,
3✔
4278
                Msg:  msg,
3✔
4279
        })
3✔
4280
}
3✔
4281

4282
// SubscribeCustomMessages subscribes to a stream of incoming custom peer
4283
// messages.
4284
func (s *server) SubscribeCustomMessages() (*subscribe.Client, error) {
3✔
4285
        return s.customMessageServer.Subscribe()
3✔
4286
}
3✔
4287

4288
// notifyOpenChannelPeerEvent updates the access manager's maps and then calls
4289
// the channelNotifier's NotifyOpenChannelEvent.
4290
func (s *server) notifyOpenChannelPeerEvent(op wire.OutPoint,
4291
        remotePub *btcec.PublicKey) error {
3✔
4292

3✔
4293
        // Call newOpenChan to update the access manager's maps for this peer.
3✔
4294
        if err := s.peerAccessMan.newOpenChan(remotePub); err != nil {
6✔
4295
                return err
3✔
4296
        }
3✔
4297

4298
        // Notify subscribers about this open channel event.
4299
        s.channelNotifier.NotifyOpenChannelEvent(op)
3✔
4300

3✔
4301
        return nil
3✔
4302
}
4303

4304
// notifyPendingOpenChannelPeerEvent updates the access manager's maps and then
4305
// calls the channelNotifier's NotifyPendingOpenChannelEvent.
4306
func (s *server) notifyPendingOpenChannelPeerEvent(op wire.OutPoint,
4307
        pendingChan *channeldb.OpenChannel, remotePub *btcec.PublicKey) error {
3✔
4308

3✔
4309
        // Call newPendingOpenChan to update the access manager's maps for this
3✔
4310
        // peer.
3✔
4311
        if err := s.peerAccessMan.newPendingOpenChan(remotePub); err != nil {
3✔
4312
                return err
×
4313
        }
×
4314

4315
        // Notify subscribers about this event.
4316
        s.channelNotifier.NotifyPendingOpenChannelEvent(op, pendingChan)
3✔
4317

3✔
4318
        return nil
3✔
4319
}
4320

4321
// notifyFundingTimeoutPeerEvent updates the access manager's maps and then
4322
// calls the channelNotifier's NotifyFundingTimeout.
4323
func (s *server) notifyFundingTimeoutPeerEvent(op wire.OutPoint,
4324
        remotePub *btcec.PublicKey) error {
3✔
4325

3✔
4326
        // Call newPendingCloseChan to potentially demote the peer.
3✔
4327
        err := s.peerAccessMan.newPendingCloseChan(remotePub)
3✔
4328
        if errors.Is(err, ErrNoMoreRestrictedAccessSlots) {
3✔
4329
                // If we encounter an error while attempting to disconnect the
×
4330
                // peer, log the error.
×
4331
                if dcErr := s.DisconnectPeer(remotePub); dcErr != nil {
×
4332
                        srvrLog.Errorf("Unable to disconnect peer: %v\n", err)
×
4333
                }
×
4334
        }
4335

4336
        // Notify subscribers about this event.
4337
        s.channelNotifier.NotifyFundingTimeout(op)
3✔
4338

3✔
4339
        return nil
3✔
4340
}
4341

4342
// peerConnected is a function that handles initialization a newly connected
4343
// peer by adding it to the server's global list of all active peers, and
4344
// starting all the goroutines the peer needs to function properly. The inbound
4345
// boolean should be true if the peer initiated the connection to us.
4346
func (s *server) peerConnected(conn net.Conn, connReq *connmgr.ConnReq,
4347
        inbound bool, access peerAccessStatus) {
3✔
4348

3✔
4349
        brontideConn := conn.(*brontide.Conn)
3✔
4350
        addr := conn.RemoteAddr()
3✔
4351
        pubKey := brontideConn.RemotePub()
3✔
4352

3✔
4353
        srvrLog.Infof("Finalizing connection to %x@%s, inbound=%v",
3✔
4354
                pubKey.SerializeCompressed(), addr, inbound)
3✔
4355

3✔
4356
        peerAddr := &lnwire.NetAddress{
3✔
4357
                IdentityKey: pubKey,
3✔
4358
                Address:     addr,
3✔
4359
                ChainNet:    s.cfg.ActiveNetParams.Net,
3✔
4360
        }
3✔
4361

3✔
4362
        // With the brontide connection established, we'll now craft the feature
3✔
4363
        // vectors to advertise to the remote node.
3✔
4364
        initFeatures := s.featureMgr.Get(feature.SetInit)
3✔
4365
        legacyFeatures := s.featureMgr.Get(feature.SetLegacyGlobal)
3✔
4366

3✔
4367
        // Lookup past error caches for the peer in the server. If no buffer is
3✔
4368
        // found, create a fresh buffer.
3✔
4369
        pkStr := string(peerAddr.IdentityKey.SerializeCompressed())
3✔
4370
        errBuffer, ok := s.peerErrors[pkStr]
3✔
4371
        if !ok {
6✔
4372
                var err error
3✔
4373
                errBuffer, err = queue.NewCircularBuffer(peer.ErrorBufferSize)
3✔
4374
                if err != nil {
3✔
4375
                        srvrLog.Errorf("unable to create peer %v", err)
×
4376
                        return
×
4377
                }
×
4378
        }
4379

4380
        // If we directly set the peer.Config TowerClient member to the
4381
        // s.towerClientMgr then in the case that the s.towerClientMgr is nil,
4382
        // the peer.Config's TowerClient member will not evaluate to nil even
4383
        // though the underlying value is nil. To avoid this gotcha which can
4384
        // cause a panic, we need to explicitly pass nil to the peer.Config's
4385
        // TowerClient if needed.
4386
        var towerClient wtclient.ClientManager
3✔
4387
        if s.towerClientMgr != nil {
6✔
4388
                towerClient = s.towerClientMgr
3✔
4389
        }
3✔
4390

4391
        thresholdSats := btcutil.Amount(s.cfg.MaxFeeExposure)
3✔
4392
        thresholdMSats := lnwire.NewMSatFromSatoshis(thresholdSats)
3✔
4393

3✔
4394
        // Now that we've established a connection, create a peer, and it to the
3✔
4395
        // set of currently active peers. Configure the peer with the incoming
3✔
4396
        // and outgoing broadcast deltas to prevent htlcs from being accepted or
3✔
4397
        // offered that would trigger channel closure. In case of outgoing
3✔
4398
        // htlcs, an extra block is added to prevent the channel from being
3✔
4399
        // closed when the htlc is outstanding and a new block comes in.
3✔
4400
        pCfg := peer.Config{
3✔
4401
                Conn:                    brontideConn,
3✔
4402
                ConnReq:                 connReq,
3✔
4403
                Addr:                    peerAddr,
3✔
4404
                Inbound:                 inbound,
3✔
4405
                Features:                initFeatures,
3✔
4406
                LegacyFeatures:          legacyFeatures,
3✔
4407
                OutgoingCltvRejectDelta: lncfg.DefaultOutgoingCltvRejectDelta,
3✔
4408
                ChanActiveTimeout:       s.cfg.ChanEnableTimeout,
3✔
4409
                ErrorBuffer:             errBuffer,
3✔
4410
                WritePool:               s.writePool,
3✔
4411
                ReadPool:                s.readPool,
3✔
4412
                Switch:                  s.htlcSwitch,
3✔
4413
                InterceptSwitch:         s.interceptableSwitch,
3✔
4414
                ChannelDB:               s.chanStateDB,
3✔
4415
                ChannelGraph:            s.graphDB,
3✔
4416
                ChainArb:                s.chainArb,
3✔
4417
                AuthGossiper:            s.authGossiper,
3✔
4418
                ChanStatusMgr:           s.chanStatusMgr,
3✔
4419
                ChainIO:                 s.cc.ChainIO,
3✔
4420
                FeeEstimator:            s.cc.FeeEstimator,
3✔
4421
                Signer:                  s.cc.Wallet.Cfg.Signer,
3✔
4422
                SigPool:                 s.sigPool,
3✔
4423
                Wallet:                  s.cc.Wallet,
3✔
4424
                ChainNotifier:           s.cc.ChainNotifier,
3✔
4425
                BestBlockView:           s.cc.BestBlockTracker,
3✔
4426
                RoutingPolicy:           s.cc.RoutingPolicy,
3✔
4427
                Sphinx:                  s.sphinx,
3✔
4428
                WitnessBeacon:           s.witnessBeacon,
3✔
4429
                Invoices:                s.invoices,
3✔
4430
                ChannelNotifier:         s.channelNotifier,
3✔
4431
                HtlcNotifier:            s.htlcNotifier,
3✔
4432
                TowerClient:             towerClient,
3✔
4433
                DisconnectPeer:          s.DisconnectPeer,
3✔
4434
                GenNodeAnnouncement: func(...netann.NodeAnnModifier) (
3✔
4435
                        lnwire.NodeAnnouncement, error) {
6✔
4436

3✔
4437
                        return s.genNodeAnnouncement(nil)
3✔
4438
                },
3✔
4439

4440
                PongBuf: s.pongBuf,
4441

4442
                PrunePersistentPeerConnection: s.prunePersistentPeerConnection,
4443

4444
                FetchLastChanUpdate: s.fetchLastChanUpdate(),
4445

4446
                FundingManager: s.fundingMgr,
4447

4448
                Hodl:                    s.cfg.Hodl,
4449
                UnsafeReplay:            s.cfg.UnsafeReplay,
4450
                MaxOutgoingCltvExpiry:   s.cfg.MaxOutgoingCltvExpiry,
4451
                MaxChannelFeeAllocation: s.cfg.MaxChannelFeeAllocation,
4452
                CoopCloseTargetConfs:    s.cfg.CoopCloseTargetConfs,
4453
                MaxAnchorsCommitFeeRate: chainfee.SatPerKVByte(
4454
                        s.cfg.MaxCommitFeeRateAnchors * 1000).FeePerKWeight(),
4455
                ChannelCommitInterval:  s.cfg.ChannelCommitInterval,
4456
                PendingCommitInterval:  s.cfg.PendingCommitInterval,
4457
                ChannelCommitBatchSize: s.cfg.ChannelCommitBatchSize,
4458
                HandleCustomMessage:    s.handleCustomMessage,
4459
                GetAliases:             s.aliasMgr.GetAliases,
4460
                RequestAlias:           s.aliasMgr.RequestAlias,
4461
                AddLocalAlias:          s.aliasMgr.AddLocalAlias,
4462
                DisallowRouteBlinding:  s.cfg.ProtocolOptions.NoRouteBlinding(),
4463
                DisallowQuiescence:     s.cfg.ProtocolOptions.NoQuiescence(),
4464
                MaxFeeExposure:         thresholdMSats,
4465
                Quit:                   s.quit,
4466
                AuxLeafStore:           s.implCfg.AuxLeafStore,
4467
                AuxSigner:              s.implCfg.AuxSigner,
4468
                MsgRouter:              s.implCfg.MsgRouter,
4469
                AuxChanCloser:          s.implCfg.AuxChanCloser,
4470
                AuxResolver:            s.implCfg.AuxContractResolver,
4471
                AuxTrafficShaper:       s.implCfg.TrafficShaper,
4472
                ShouldFwdExpEndorsement: func() bool {
3✔
4473
                        if s.cfg.ProtocolOptions.NoExperimentalEndorsement() {
6✔
4474
                                return false
3✔
4475
                        }
3✔
4476

4477
                        return clock.NewDefaultClock().Now().Before(
3✔
4478
                                EndorsementExperimentEnd,
3✔
4479
                        )
3✔
4480
                },
4481
        }
4482

4483
        copy(pCfg.PubKeyBytes[:], peerAddr.IdentityKey.SerializeCompressed())
3✔
4484
        copy(pCfg.ServerPubKey[:], s.identityECDH.PubKey().SerializeCompressed())
3✔
4485

3✔
4486
        p := peer.NewBrontide(pCfg)
3✔
4487

3✔
4488
        // Update the access manager with the access permission for this peer.
3✔
4489
        s.peerAccessMan.addPeerAccess(pubKey, access)
3✔
4490

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

3✔
4494
        s.addPeer(p)
3✔
4495

3✔
4496
        // Once we have successfully added the peer to the server, we can
3✔
4497
        // delete the previous error buffer from the server's map of error
3✔
4498
        // buffers.
3✔
4499
        delete(s.peerErrors, pkStr)
3✔
4500

3✔
4501
        // Dispatch a goroutine to asynchronously start the peer. This process
3✔
4502
        // includes sending and receiving Init messages, which would be a DOS
3✔
4503
        // vector if we held the server's mutex throughout the procedure.
3✔
4504
        s.wg.Add(1)
3✔
4505
        go s.peerInitializer(p)
3✔
4506
}
4507

4508
// addPeer adds the passed peer to the server's global state of all active
4509
// peers.
4510
func (s *server) addPeer(p *peer.Brontide) {
3✔
4511
        if p == nil {
3✔
4512
                return
×
4513
        }
×
4514

4515
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4516

3✔
4517
        // Ignore new peers if we're shutting down.
3✔
4518
        if s.Stopped() {
3✔
4519
                srvrLog.Infof("Server stopped, skipped adding peer=%x",
×
4520
                        pubBytes)
×
4521
                p.Disconnect(ErrServerShuttingDown)
×
4522

×
4523
                return
×
4524
        }
×
4525

4526
        // Track the new peer in our indexes so we can quickly look it up either
4527
        // according to its public key, or its peer ID.
4528
        // TODO(roasbeef): pipe all requests through to the
4529
        // queryHandler/peerManager
4530

4531
        // NOTE: This pubStr is a raw bytes to string conversion and will NOT
4532
        // be human-readable.
4533
        pubStr := string(pubBytes)
3✔
4534

3✔
4535
        s.peersByPub[pubStr] = p
3✔
4536

3✔
4537
        if p.Inbound() {
6✔
4538
                s.inboundPeers[pubStr] = p
3✔
4539
        } else {
6✔
4540
                s.outboundPeers[pubStr] = p
3✔
4541
        }
3✔
4542

4543
        // Inform the peer notifier of a peer online event so that it can be reported
4544
        // to clients listening for peer events.
4545
        var pubKey [33]byte
3✔
4546
        copy(pubKey[:], pubBytes)
3✔
4547

3✔
4548
        s.peerNotifier.NotifyPeerOnline(pubKey)
3✔
4549
}
4550

4551
// peerInitializer asynchronously starts a newly connected peer after it has
4552
// been added to the server's peer map. This method sets up a
4553
// peerTerminationWatcher for the given peer, and ensures that it executes even
4554
// if the peer failed to start. In the event of a successful connection, this
4555
// method reads the negotiated, local feature-bits and spawns the appropriate
4556
// graph synchronization method. Any registered clients of NotifyWhenOnline will
4557
// be signaled of the new peer once the method returns.
4558
//
4559
// NOTE: This MUST be launched as a goroutine.
4560
func (s *server) peerInitializer(p *peer.Brontide) {
3✔
4561
        defer s.wg.Done()
3✔
4562

3✔
4563
        pubBytes := p.IdentityKey().SerializeCompressed()
3✔
4564

3✔
4565
        // Avoid initializing peers while the server is exiting.
3✔
4566
        if s.Stopped() {
3✔
4567
                srvrLog.Infof("Server stopped, skipped initializing peer=%x",
×
4568
                        pubBytes)
×
4569
                return
×
4570
        }
×
4571

4572
        // Create a channel that will be used to signal a successful start of
4573
        // the link. This prevents the peer termination watcher from beginning
4574
        // its duty too early.
4575
        ready := make(chan struct{})
3✔
4576

3✔
4577
        // Before starting the peer, launch a goroutine to watch for the
3✔
4578
        // unexpected termination of this peer, which will ensure all resources
3✔
4579
        // are properly cleaned up, and re-establish persistent connections when
3✔
4580
        // necessary. The peer termination watcher will be short circuited if
3✔
4581
        // the peer is ever added to the ignorePeerTermination map, indicating
3✔
4582
        // that the server has already handled the removal of this peer.
3✔
4583
        s.wg.Add(1)
3✔
4584
        go s.peerTerminationWatcher(p, ready)
3✔
4585

3✔
4586
        // Start the peer! If an error occurs, we Disconnect the peer, which
3✔
4587
        // will unblock the peerTerminationWatcher.
3✔
4588
        if err := p.Start(); err != nil {
6✔
4589
                srvrLog.Warnf("Starting peer=%x got error: %v", pubBytes, err)
3✔
4590

3✔
4591
                p.Disconnect(fmt.Errorf("unable to start peer: %w", err))
3✔
4592
                return
3✔
4593
        }
3✔
4594

4595
        // Otherwise, signal to the peerTerminationWatcher that the peer startup
4596
        // was successful, and to begin watching the peer's wait group.
4597
        close(ready)
3✔
4598

3✔
4599
        s.mu.Lock()
3✔
4600
        defer s.mu.Unlock()
3✔
4601

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

3✔
4605
        // TODO(guggero): Do a proper conversion to a string everywhere, or use
3✔
4606
        // route.Vertex as the key type of peerConnectedListeners.
3✔
4607
        pubStr := string(pubBytes)
3✔
4608
        for _, peerChan := range s.peerConnectedListeners[pubStr] {
6✔
4609
                select {
3✔
4610
                case peerChan <- p:
3✔
4611
                case <-s.quit:
×
4612
                        return
×
4613
                }
4614
        }
4615
        delete(s.peerConnectedListeners, pubStr)
3✔
4616
}
4617

4618
// peerTerminationWatcher waits until a peer has been disconnected unexpectedly,
4619
// and then cleans up all resources allocated to the peer, notifies relevant
4620
// sub-systems of its demise, and finally handles re-connecting to the peer if
4621
// it's persistent. If the server intentionally disconnects a peer, it should
4622
// have a corresponding entry in the ignorePeerTermination map which will cause
4623
// the cleanup routine to exit early. The passed `ready` chan is used to
4624
// synchronize when WaitForDisconnect should begin watching on the peer's
4625
// waitgroup. The ready chan should only be signaled if the peer starts
4626
// successfully, otherwise the peer should be disconnected instead.
4627
//
4628
// NOTE: This MUST be launched as a goroutine.
4629
func (s *server) peerTerminationWatcher(p *peer.Brontide, ready chan struct{}) {
3✔
4630
        defer s.wg.Done()
3✔
4631

3✔
4632
        p.WaitForDisconnect(ready)
3✔
4633

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

3✔
4636
        // If the server is exiting then we can bail out early ourselves as all
3✔
4637
        // the other sub-systems will already be shutting down.
3✔
4638
        if s.Stopped() {
6✔
4639
                srvrLog.Debugf("Server quitting, exit early for peer %v", p)
3✔
4640
                return
3✔
4641
        }
3✔
4642

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

3✔
4649
        pubKey := p.IdentityKey()
3✔
4650

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

3✔
4655
        // Tell the switch to remove all links associated with this peer.
3✔
4656
        // Passing nil as the target link indicates that all links associated
3✔
4657
        // with this interface should be closed.
3✔
4658
        //
3✔
4659
        // TODO(roasbeef): instead add a PurgeInterfaceLinks function?
3✔
4660
        links, err := s.htlcSwitch.GetLinksByInterface(p.PubKey())
3✔
4661
        if err != nil && err != htlcswitch.ErrNoLinksFound {
3✔
4662
                srvrLog.Errorf("Unable to get channel links for %v: %v", p, err)
×
4663
        }
×
4664

4665
        for _, link := range links {
6✔
4666
                s.htlcSwitch.RemoveLink(link.ChanID())
3✔
4667
        }
3✔
4668

4669
        s.mu.Lock()
3✔
4670
        defer s.mu.Unlock()
3✔
4671

3✔
4672
        // If there were any notification requests for when this peer
3✔
4673
        // disconnected, we can trigger them now.
3✔
4674
        srvrLog.Debugf("Notifying that peer %v is offline", p)
3✔
4675
        pubStr := string(pubKey.SerializeCompressed())
3✔
4676
        for _, offlineChan := range s.peerDisconnectedListeners[pubStr] {
6✔
4677
                close(offlineChan)
3✔
4678
        }
3✔
4679
        delete(s.peerDisconnectedListeners, pubStr)
3✔
4680

3✔
4681
        // If the server has already removed this peer, we can short circuit the
3✔
4682
        // peer termination watcher and skip cleanup.
3✔
4683
        if _, ok := s.ignorePeerTermination[p]; ok {
3✔
4684
                delete(s.ignorePeerTermination, p)
×
4685

×
4686
                pubKey := p.PubKey()
×
4687
                pubStr := string(pubKey[:])
×
4688

×
4689
                // If a connection callback is present, we'll go ahead and
×
4690
                // execute it now that previous peer has fully disconnected. If
×
4691
                // the callback is not present, this likely implies the peer was
×
4692
                // purposefully disconnected via RPC, and that no reconnect
×
4693
                // should be attempted.
×
4694
                connCallback, ok := s.scheduledPeerConnection[pubStr]
×
4695
                if ok {
×
4696
                        delete(s.scheduledPeerConnection, pubStr)
×
4697
                        connCallback()
×
4698
                }
×
4699
                return
×
4700
        }
4701

4702
        // First, cleanup any remaining state the server has regarding the peer
4703
        // in question.
4704
        s.removePeer(p)
3✔
4705

3✔
4706
        // Next, check to see if this is a persistent peer or not.
3✔
4707
        if _, ok := s.persistentPeers[pubStr]; !ok {
6✔
4708
                return
3✔
4709
        }
3✔
4710

4711
        // Get the last address that we used to connect to the peer.
4712
        addrs := []net.Addr{
3✔
4713
                p.NetAddress().Address,
3✔
4714
        }
3✔
4715

3✔
4716
        // We'll ensure that we locate all the peers advertised addresses for
3✔
4717
        // reconnection purposes.
3✔
4718
        advertisedAddrs, err := s.fetchNodeAdvertisedAddrs(pubKey)
3✔
4719
        switch {
3✔
4720
        // We found advertised addresses, so use them.
4721
        case err == nil:
3✔
4722
                addrs = advertisedAddrs
3✔
4723

4724
        // The peer doesn't have an advertised address.
4725
        case err == errNoAdvertisedAddr:
3✔
4726
                // If it is an outbound peer then we fall back to the existing
3✔
4727
                // peer address.
3✔
4728
                if !p.Inbound() {
6✔
4729
                        break
3✔
4730
                }
4731

4732
                // Fall back to the existing peer address if
4733
                // we're not accepting connections over Tor.
4734
                if s.torController == nil {
6✔
4735
                        break
3✔
4736
                }
4737

4738
                // If we are, the peer's address won't be known
4739
                // to us (we'll see a private address, which is
4740
                // the address used by our onion service to dial
4741
                // to lnd), so we don't have enough information
4742
                // to attempt a reconnect.
4743
                srvrLog.Debugf("Ignoring reconnection attempt "+
×
4744
                        "to inbound peer %v without "+
×
4745
                        "advertised address", p)
×
4746
                return
×
4747

4748
        // We came across an error retrieving an advertised
4749
        // address, log it, and fall back to the existing peer
4750
        // address.
4751
        default:
3✔
4752
                srvrLog.Errorf("Unable to retrieve advertised "+
3✔
4753
                        "address for node %x: %v", p.PubKey(),
3✔
4754
                        err)
3✔
4755
        }
4756

4757
        // Make an easy lookup map so that we can check if an address
4758
        // is already in the address list that we have stored for this peer.
4759
        existingAddrs := make(map[string]bool)
3✔
4760
        for _, addr := range s.persistentPeerAddrs[pubStr] {
6✔
4761
                existingAddrs[addr.String()] = true
3✔
4762
        }
3✔
4763

4764
        // Add any missing addresses for this peer to persistentPeerAddr.
4765
        for _, addr := range addrs {
6✔
4766
                if existingAddrs[addr.String()] {
3✔
4767
                        continue
×
4768
                }
4769

4770
                s.persistentPeerAddrs[pubStr] = append(
3✔
4771
                        s.persistentPeerAddrs[pubStr],
3✔
4772
                        &lnwire.NetAddress{
3✔
4773
                                IdentityKey: p.IdentityKey(),
3✔
4774
                                Address:     addr,
3✔
4775
                                ChainNet:    p.NetAddress().ChainNet,
3✔
4776
                        },
3✔
4777
                )
3✔
4778
        }
4779

4780
        // Record the computed backoff in the backoff map.
4781
        backoff := s.nextPeerBackoff(pubStr, p.StartTime())
3✔
4782
        s.persistentPeersBackoff[pubStr] = backoff
3✔
4783

3✔
4784
        // Initialize a retry canceller for this peer if one does not
3✔
4785
        // exist.
3✔
4786
        cancelChan, ok := s.persistentRetryCancels[pubStr]
3✔
4787
        if !ok {
6✔
4788
                cancelChan = make(chan struct{})
3✔
4789
                s.persistentRetryCancels[pubStr] = cancelChan
3✔
4790
        }
3✔
4791

4792
        // We choose not to wait group this go routine since the Connect
4793
        // call can stall for arbitrarily long if we shutdown while an
4794
        // outbound connection attempt is being made.
4795
        go func() {
6✔
4796
                srvrLog.Debugf("Scheduling connection re-establishment to "+
3✔
4797
                        "persistent peer %x in %s",
3✔
4798
                        p.IdentityKey().SerializeCompressed(), backoff)
3✔
4799

3✔
4800
                select {
3✔
4801
                case <-time.After(backoff):
3✔
4802
                case <-cancelChan:
3✔
4803
                        return
3✔
4804
                case <-s.quit:
3✔
4805
                        return
3✔
4806
                }
4807

4808
                srvrLog.Debugf("Attempting to re-establish persistent "+
3✔
4809
                        "connection to peer %x",
3✔
4810
                        p.IdentityKey().SerializeCompressed())
3✔
4811

3✔
4812
                s.connectToPersistentPeer(pubStr)
3✔
4813
        }()
4814
}
4815

4816
// connectToPersistentPeer uses all the stored addresses for a peer to attempt
4817
// to connect to the peer. It creates connection requests if there are
4818
// currently none for a given address and it removes old connection requests
4819
// if the associated address is no longer in the latest address list for the
4820
// peer.
4821
func (s *server) connectToPersistentPeer(pubKeyStr string) {
3✔
4822
        s.mu.Lock()
3✔
4823
        defer s.mu.Unlock()
3✔
4824

3✔
4825
        // Create an easy lookup map of the addresses we have stored for the
3✔
4826
        // peer. We will remove entries from this map if we have existing
3✔
4827
        // connection requests for the associated address and then any leftover
3✔
4828
        // entries will indicate which addresses we should create new
3✔
4829
        // connection requests for.
3✔
4830
        addrMap := make(map[string]*lnwire.NetAddress)
3✔
4831
        for _, addr := range s.persistentPeerAddrs[pubKeyStr] {
6✔
4832
                addrMap[addr.String()] = addr
3✔
4833
        }
3✔
4834

4835
        // Go through each of the existing connection requests and
4836
        // check if they correspond to the latest set of addresses. If
4837
        // there is a connection requests that does not use one of the latest
4838
        // advertised addresses then remove that connection request.
4839
        var updatedConnReqs []*connmgr.ConnReq
3✔
4840
        for _, connReq := range s.persistentConnReqs[pubKeyStr] {
6✔
4841
                lnAddr := connReq.Addr.(*lnwire.NetAddress).Address.String()
3✔
4842

3✔
4843
                switch _, ok := addrMap[lnAddr]; ok {
3✔
4844
                // If the existing connection request is using one of the
4845
                // latest advertised addresses for the peer then we add it to
4846
                // updatedConnReqs and remove the associated address from
4847
                // addrMap so that we don't recreate this connReq later on.
4848
                case true:
×
4849
                        updatedConnReqs = append(
×
4850
                                updatedConnReqs, connReq,
×
4851
                        )
×
4852
                        delete(addrMap, lnAddr)
×
4853

4854
                // If the existing connection request is using an address that
4855
                // is not one of the latest advertised addresses for the peer
4856
                // then we remove the connecting request from the connection
4857
                // manager.
4858
                case false:
3✔
4859
                        srvrLog.Info(
3✔
4860
                                "Removing conn req:", connReq.Addr.String(),
3✔
4861
                        )
3✔
4862
                        s.connMgr.Remove(connReq.ID())
3✔
4863
                }
4864
        }
4865

4866
        s.persistentConnReqs[pubKeyStr] = updatedConnReqs
3✔
4867

3✔
4868
        cancelChan, ok := s.persistentRetryCancels[pubKeyStr]
3✔
4869
        if !ok {
6✔
4870
                cancelChan = make(chan struct{})
3✔
4871
                s.persistentRetryCancels[pubKeyStr] = cancelChan
3✔
4872
        }
3✔
4873

4874
        // Any addresses left in addrMap are new ones that we have not made
4875
        // connection requests for. So create new connection requests for those.
4876
        // If there is more than one address in the address map, stagger the
4877
        // creation of the connection requests for those.
4878
        go func() {
6✔
4879
                ticker := time.NewTicker(multiAddrConnectionStagger)
3✔
4880
                defer ticker.Stop()
3✔
4881

3✔
4882
                for _, addr := range addrMap {
6✔
4883
                        // Send the persistent connection request to the
3✔
4884
                        // connection manager, saving the request itself so we
3✔
4885
                        // can cancel/restart the process as needed.
3✔
4886
                        connReq := &connmgr.ConnReq{
3✔
4887
                                Addr:      addr,
3✔
4888
                                Permanent: true,
3✔
4889
                        }
3✔
4890

3✔
4891
                        s.mu.Lock()
3✔
4892
                        s.persistentConnReqs[pubKeyStr] = append(
3✔
4893
                                s.persistentConnReqs[pubKeyStr], connReq,
3✔
4894
                        )
3✔
4895
                        s.mu.Unlock()
3✔
4896

3✔
4897
                        srvrLog.Debugf("Attempting persistent connection to "+
3✔
4898
                                "channel peer %v", addr)
3✔
4899

3✔
4900
                        go s.connMgr.Connect(connReq)
3✔
4901

3✔
4902
                        select {
3✔
4903
                        case <-s.quit:
3✔
4904
                                return
3✔
4905
                        case <-cancelChan:
3✔
4906
                                return
3✔
4907
                        case <-ticker.C:
3✔
4908
                        }
4909
                }
4910
        }()
4911
}
4912

4913
// removePeer removes the passed peer from the server's state of all active
4914
// peers.
4915
func (s *server) removePeer(p *peer.Brontide) {
3✔
4916
        if p == nil {
3✔
4917
                return
×
4918
        }
×
4919

4920
        srvrLog.Debugf("removing peer %v", p)
3✔
4921

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

3✔
4926
        // If this peer had an active persistent connection request, remove it.
3✔
4927
        if p.ConnReq() != nil {
6✔
4928
                s.connMgr.Remove(p.ConnReq().ID())
3✔
4929
        }
3✔
4930

4931
        // Ignore deleting peers if we're shutting down.
4932
        if s.Stopped() {
3✔
4933
                return
×
4934
        }
×
4935

4936
        pKey := p.PubKey()
3✔
4937
        pubSer := pKey[:]
3✔
4938
        pubStr := string(pubSer)
3✔
4939

3✔
4940
        delete(s.peersByPub, pubStr)
3✔
4941

3✔
4942
        if p.Inbound() {
6✔
4943
                delete(s.inboundPeers, pubStr)
3✔
4944
        } else {
6✔
4945
                delete(s.outboundPeers, pubStr)
3✔
4946
        }
3✔
4947

4948
        // Remove the peer's access permission from the access manager.
4949
        s.peerAccessMan.removePeerAccess(p.IdentityKey())
3✔
4950

3✔
4951
        // Copy the peer's error buffer across to the server if it has any items
3✔
4952
        // in it so that we can restore peer errors across connections.
3✔
4953
        if p.ErrorBuffer().Total() > 0 {
6✔
4954
                s.peerErrors[pubStr] = p.ErrorBuffer()
3✔
4955
        }
3✔
4956

4957
        // Inform the peer notifier of a peer offline event so that it can be
4958
        // reported to clients listening for peer events.
4959
        var pubKey [33]byte
3✔
4960
        copy(pubKey[:], pubSer)
3✔
4961

3✔
4962
        s.peerNotifier.NotifyPeerOffline(pubKey)
3✔
4963
}
4964

4965
// ConnectToPeer requests that the server connect to a Lightning Network peer
4966
// at the specified address. This function will *block* until either a
4967
// connection is established, or the initial handshake process fails.
4968
//
4969
// NOTE: This function is safe for concurrent access.
4970
func (s *server) ConnectToPeer(addr *lnwire.NetAddress,
4971
        perm bool, timeout time.Duration) error {
3✔
4972

3✔
4973
        targetPub := string(addr.IdentityKey.SerializeCompressed())
3✔
4974

3✔
4975
        // Acquire mutex, but use explicit unlocking instead of defer for
3✔
4976
        // better granularity.  In certain conditions, this method requires
3✔
4977
        // making an outbound connection to a remote peer, which requires the
3✔
4978
        // lock to be released, and subsequently reacquired.
3✔
4979
        s.mu.Lock()
3✔
4980

3✔
4981
        // Ensure we're not already connected to this peer.
3✔
4982
        peer, err := s.findPeerByPubStr(targetPub)
3✔
4983
        if err == nil {
6✔
4984
                s.mu.Unlock()
3✔
4985
                return &errPeerAlreadyConnected{peer: peer}
3✔
4986
        }
3✔
4987

4988
        // Peer was not found, continue to pursue connection with peer.
4989

4990
        // If there's already a pending connection request for this pubkey,
4991
        // then we ignore this request to ensure we don't create a redundant
4992
        // connection.
4993
        if reqs, ok := s.persistentConnReqs[targetPub]; ok {
6✔
4994
                srvrLog.Warnf("Already have %d persistent connection "+
3✔
4995
                        "requests for %v, connecting anyway.", len(reqs), addr)
3✔
4996
        }
3✔
4997

4998
        // If there's not already a pending or active connection to this node,
4999
        // then instruct the connection manager to attempt to establish a
5000
        // persistent connection to the peer.
5001
        srvrLog.Debugf("Connecting to %v", addr)
3✔
5002
        if perm {
6✔
5003
                connReq := &connmgr.ConnReq{
3✔
5004
                        Addr:      addr,
3✔
5005
                        Permanent: true,
3✔
5006
                }
3✔
5007

3✔
5008
                // Since the user requested a permanent connection, we'll set
3✔
5009
                // the entry to true which will tell the server to continue
3✔
5010
                // reconnecting even if the number of channels with this peer is
3✔
5011
                // zero.
3✔
5012
                s.persistentPeers[targetPub] = true
3✔
5013
                if _, ok := s.persistentPeersBackoff[targetPub]; !ok {
6✔
5014
                        s.persistentPeersBackoff[targetPub] = s.cfg.MinBackoff
3✔
5015
                }
3✔
5016
                s.persistentConnReqs[targetPub] = append(
3✔
5017
                        s.persistentConnReqs[targetPub], connReq,
3✔
5018
                )
3✔
5019
                s.mu.Unlock()
3✔
5020

3✔
5021
                go s.connMgr.Connect(connReq)
3✔
5022

3✔
5023
                return nil
3✔
5024
        }
5025
        s.mu.Unlock()
3✔
5026

3✔
5027
        // If we're not making a persistent connection, then we'll attempt to
3✔
5028
        // connect to the target peer. If the we can't make the connection, or
3✔
5029
        // the crypto negotiation breaks down, then return an error to the
3✔
5030
        // caller.
3✔
5031
        errChan := make(chan error, 1)
3✔
5032
        s.connectToPeer(addr, errChan, timeout)
3✔
5033

3✔
5034
        select {
3✔
5035
        case err := <-errChan:
3✔
5036
                return err
3✔
5037
        case <-s.quit:
×
5038
                return ErrServerShuttingDown
×
5039
        }
5040
}
5041

5042
// connectToPeer establishes a connection to a remote peer. errChan is used to
5043
// notify the caller if the connection attempt has failed. Otherwise, it will be
5044
// closed.
5045
func (s *server) connectToPeer(addr *lnwire.NetAddress,
5046
        errChan chan<- error, timeout time.Duration) {
3✔
5047

3✔
5048
        conn, err := brontide.Dial(
3✔
5049
                s.identityECDH, addr, timeout, s.cfg.net.Dial,
3✔
5050
        )
3✔
5051
        if err != nil {
6✔
5052
                srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
3✔
5053
                select {
3✔
5054
                case errChan <- err:
3✔
5055
                case <-s.quit:
×
5056
                }
5057
                return
3✔
5058
        }
5059

5060
        close(errChan)
3✔
5061

3✔
5062
        srvrLog.Tracef("Brontide dialer made local=%v, remote=%v",
3✔
5063
                conn.LocalAddr(), conn.RemoteAddr())
3✔
5064

3✔
5065
        s.OutboundPeerConnected(nil, conn)
3✔
5066
}
5067

5068
// DisconnectPeer sends the request to server to close the connection with peer
5069
// identified by public key.
5070
//
5071
// NOTE: This function is safe for concurrent access.
5072
func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
3✔
5073
        pubBytes := pubKey.SerializeCompressed()
3✔
5074
        pubStr := string(pubBytes)
3✔
5075

3✔
5076
        s.mu.Lock()
3✔
5077
        defer s.mu.Unlock()
3✔
5078

3✔
5079
        // Check that were actually connected to this peer. If not, then we'll
3✔
5080
        // exit in an error as we can't disconnect from a peer that we're not
3✔
5081
        // currently connected to.
3✔
5082
        peer, err := s.findPeerByPubStr(pubStr)
3✔
5083
        if err == ErrPeerNotConnected {
6✔
5084
                return fmt.Errorf("peer %x is not connected", pubBytes)
3✔
5085
        }
3✔
5086

5087
        srvrLog.Infof("Disconnecting from %v", peer)
3✔
5088

3✔
5089
        s.cancelConnReqs(pubStr, nil)
3✔
5090

3✔
5091
        // If this peer was formerly a persistent connection, then we'll remove
3✔
5092
        // them from this map so we don't attempt to re-connect after we
3✔
5093
        // disconnect.
3✔
5094
        delete(s.persistentPeers, pubStr)
3✔
5095
        delete(s.persistentPeersBackoff, pubStr)
3✔
5096

3✔
5097
        // Remove the peer by calling Disconnect. Previously this was done with
3✔
5098
        // removePeer, which bypassed the peerTerminationWatcher.
3✔
5099
        peer.Disconnect(fmt.Errorf("server: DisconnectPeer called"))
3✔
5100

3✔
5101
        return nil
3✔
5102
}
5103

5104
// OpenChannel sends a request to the server to open a channel to the specified
5105
// peer identified by nodeKey with the passed channel funding parameters.
5106
//
5107
// NOTE: This function is safe for concurrent access.
5108
func (s *server) OpenChannel(
5109
        req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
3✔
5110

3✔
5111
        // The updateChan will have a buffer of 2, since we expect a ChanPending
3✔
5112
        // + a ChanOpen update, and we want to make sure the funding process is
3✔
5113
        // not blocked if the caller is not reading the updates.
3✔
5114
        req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
3✔
5115
        req.Err = make(chan error, 1)
3✔
5116

3✔
5117
        // First attempt to locate the target peer to open a channel with, if
3✔
5118
        // we're unable to locate the peer then this request will fail.
3✔
5119
        pubKeyBytes := req.TargetPubkey.SerializeCompressed()
3✔
5120
        s.mu.RLock()
3✔
5121
        peer, ok := s.peersByPub[string(pubKeyBytes)]
3✔
5122
        if !ok {
3✔
5123
                s.mu.RUnlock()
×
5124

×
5125
                req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
×
5126
                return req.Updates, req.Err
×
5127
        }
×
5128
        req.Peer = peer
3✔
5129
        s.mu.RUnlock()
3✔
5130

3✔
5131
        // We'll wait until the peer is active before beginning the channel
3✔
5132
        // opening process.
3✔
5133
        select {
3✔
5134
        case <-peer.ActiveSignal():
3✔
5135
        case <-peer.QuitSignal():
×
5136
                req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
×
5137
                return req.Updates, req.Err
×
5138
        case <-s.quit:
×
5139
                req.Err <- ErrServerShuttingDown
×
5140
                return req.Updates, req.Err
×
5141
        }
5142

5143
        // If the fee rate wasn't specified at this point we fail the funding
5144
        // because of the missing fee rate information. The caller of the
5145
        // `OpenChannel` method needs to make sure that default values for the
5146
        // fee rate are set beforehand.
5147
        if req.FundingFeePerKw == 0 {
3✔
5148
                req.Err <- fmt.Errorf("no FundingFeePerKw specified for " +
×
5149
                        "the channel opening transaction")
×
5150

×
5151
                return req.Updates, req.Err
×
5152
        }
×
5153

5154
        // Spawn a goroutine to send the funding workflow request to the funding
5155
        // manager. This allows the server to continue handling queries instead
5156
        // of blocking on this request which is exported as a synchronous
5157
        // request to the outside world.
5158
        go s.fundingMgr.InitFundingWorkflow(req)
3✔
5159

3✔
5160
        return req.Updates, req.Err
3✔
5161
}
5162

5163
// Peers returns a slice of all active peers.
5164
//
5165
// NOTE: This function is safe for concurrent access.
5166
func (s *server) Peers() []*peer.Brontide {
3✔
5167
        s.mu.RLock()
3✔
5168
        defer s.mu.RUnlock()
3✔
5169

3✔
5170
        peers := make([]*peer.Brontide, 0, len(s.peersByPub))
3✔
5171
        for _, peer := range s.peersByPub {
6✔
5172
                peers = append(peers, peer)
3✔
5173
        }
3✔
5174

5175
        return peers
3✔
5176
}
5177

5178
// computeNextBackoff uses a truncated exponential backoff to compute the next
5179
// backoff using the value of the exiting backoff. The returned duration is
5180
// randomized in either direction by 1/20 to prevent tight loops from
5181
// stabilizing.
5182
func computeNextBackoff(currBackoff, maxBackoff time.Duration) time.Duration {
3✔
5183
        // Double the current backoff, truncating if it exceeds our maximum.
3✔
5184
        nextBackoff := 2 * currBackoff
3✔
5185
        if nextBackoff > maxBackoff {
6✔
5186
                nextBackoff = maxBackoff
3✔
5187
        }
3✔
5188

5189
        // Using 1/10 of our duration as a margin, compute a random offset to
5190
        // avoid the nodes entering connection cycles.
5191
        margin := nextBackoff / 10
3✔
5192

3✔
5193
        var wiggle big.Int
3✔
5194
        wiggle.SetUint64(uint64(margin))
3✔
5195
        if _, err := rand.Int(rand.Reader, &wiggle); err != nil {
3✔
5196
                // Randomizing is not mission critical, so we'll just return the
×
5197
                // current backoff.
×
5198
                return nextBackoff
×
5199
        }
×
5200

5201
        // Otherwise add in our wiggle, but subtract out half of the margin so
5202
        // that the backoff can tweaked by 1/20 in either direction.
5203
        return nextBackoff + (time.Duration(wiggle.Uint64()) - margin/2)
3✔
5204
}
5205

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

5210
// fetchNodeAdvertisedAddrs attempts to fetch the advertised addresses of a node.
5211
func (s *server) fetchNodeAdvertisedAddrs(pub *btcec.PublicKey) ([]net.Addr, error) {
3✔
5212
        vertex, err := route.NewVertexFromBytes(pub.SerializeCompressed())
3✔
5213
        if err != nil {
3✔
5214
                return nil, err
×
5215
        }
×
5216

5217
        node, err := s.graphDB.FetchLightningNode(vertex)
3✔
5218
        if err != nil {
6✔
5219
                return nil, err
3✔
5220
        }
3✔
5221

5222
        if len(node.Addresses) == 0 {
6✔
5223
                return nil, errNoAdvertisedAddr
3✔
5224
        }
3✔
5225

5226
        return node.Addresses, nil
3✔
5227
}
5228

5229
// fetchLastChanUpdate returns a function which is able to retrieve our latest
5230
// channel update for a target channel.
5231
func (s *server) fetchLastChanUpdate() func(lnwire.ShortChannelID) (
5232
        *lnwire.ChannelUpdate1, error) {
3✔
5233

3✔
5234
        ourPubKey := s.identityECDH.PubKey().SerializeCompressed()
3✔
5235
        return func(cid lnwire.ShortChannelID) (*lnwire.ChannelUpdate1, error) {
6✔
5236
                info, edge1, edge2, err := s.graphBuilder.GetChannelByID(cid)
3✔
5237
                if err != nil {
6✔
5238
                        return nil, err
3✔
5239
                }
3✔
5240

5241
                return netann.ExtractChannelUpdate(
3✔
5242
                        ourPubKey[:], info, edge1, edge2,
3✔
5243
                )
3✔
5244
        }
5245
}
5246

5247
// applyChannelUpdate applies the channel update to the different sub-systems of
5248
// the server. The useAlias boolean denotes whether or not to send an alias in
5249
// place of the real SCID.
5250
func (s *server) applyChannelUpdate(update *lnwire.ChannelUpdate1,
5251
        op *wire.OutPoint, useAlias bool) error {
3✔
5252

3✔
5253
        var (
3✔
5254
                peerAlias    *lnwire.ShortChannelID
3✔
5255
                defaultAlias lnwire.ShortChannelID
3✔
5256
        )
3✔
5257

3✔
5258
        chanID := lnwire.NewChanIDFromOutPoint(*op)
3✔
5259

3✔
5260
        // Fetch the peer's alias from the lnwire.ChannelID so it can be used
3✔
5261
        // in the ChannelUpdate if it hasn't been announced yet.
3✔
5262
        if useAlias {
6✔
5263
                foundAlias, _ := s.aliasMgr.GetPeerAlias(chanID)
3✔
5264
                if foundAlias != defaultAlias {
6✔
5265
                        peerAlias = &foundAlias
3✔
5266
                }
3✔
5267
        }
5268

5269
        errChan := s.authGossiper.ProcessLocalAnnouncement(
3✔
5270
                update, discovery.RemoteAlias(peerAlias),
3✔
5271
        )
3✔
5272
        select {
3✔
5273
        case err := <-errChan:
3✔
5274
                return err
3✔
5275
        case <-s.quit:
×
5276
                return ErrServerShuttingDown
×
5277
        }
5278
}
5279

5280
// SendCustomMessage sends a custom message to the peer with the specified
5281
// pubkey.
5282
func (s *server) SendCustomMessage(peerPub [33]byte, msgType lnwire.MessageType,
5283
        data []byte) error {
3✔
5284

3✔
5285
        peer, err := s.FindPeerByPubStr(string(peerPub[:]))
3✔
5286
        if err != nil {
3✔
5287
                return err
×
5288
        }
×
5289

5290
        // We'll wait until the peer is active.
5291
        select {
3✔
5292
        case <-peer.ActiveSignal():
3✔
5293
        case <-peer.QuitSignal():
×
5294
                return fmt.Errorf("peer %x disconnected", peerPub)
×
5295
        case <-s.quit:
×
5296
                return ErrServerShuttingDown
×
5297
        }
5298

5299
        msg, err := lnwire.NewCustom(msgType, data)
3✔
5300
        if err != nil {
6✔
5301
                return err
3✔
5302
        }
3✔
5303

5304
        // Send the message as low-priority. For now we assume that all
5305
        // application-defined message are low priority.
5306
        return peer.SendMessageLazy(true, msg)
3✔
5307
}
5308

5309
// newSweepPkScriptGen creates closure that generates a new public key script
5310
// which should be used to sweep any funds into the on-chain wallet.
5311
// Specifically, the script generated is a version 0, pay-to-witness-pubkey-hash
5312
// (p2wkh) output.
5313
func newSweepPkScriptGen(
5314
        wallet lnwallet.WalletController,
5315
        netParams *chaincfg.Params) func() fn.Result[lnwallet.AddrWithKey] {
3✔
5316

3✔
5317
        return func() fn.Result[lnwallet.AddrWithKey] {
6✔
5318
                sweepAddr, err := wallet.NewAddress(
3✔
5319
                        lnwallet.TaprootPubkey, false,
3✔
5320
                        lnwallet.DefaultAccountName,
3✔
5321
                )
3✔
5322
                if err != nil {
3✔
5323
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5324
                }
×
5325

5326
                addr, err := txscript.PayToAddrScript(sweepAddr)
3✔
5327
                if err != nil {
3✔
5328
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5329
                }
×
5330

5331
                internalKeyDesc, err := lnwallet.InternalKeyForAddr(
3✔
5332
                        wallet, netParams, addr,
3✔
5333
                )
3✔
5334
                if err != nil {
3✔
5335
                        return fn.Err[lnwallet.AddrWithKey](err)
×
5336
                }
×
5337

5338
                return fn.Ok(lnwallet.AddrWithKey{
3✔
5339
                        DeliveryAddress: addr,
3✔
5340
                        InternalKey:     internalKeyDesc,
3✔
5341
                })
3✔
5342
        }
5343
}
5344

5345
// shouldPeerBootstrap returns true if we should attempt to perform peer
5346
// bootstrapping to actively seek our peers using the set of active network
5347
// bootstrappers.
5348
func shouldPeerBootstrap(cfg *Config) bool {
3✔
5349
        isSimnet := cfg.Bitcoin.SimNet
3✔
5350
        isSignet := cfg.Bitcoin.SigNet
3✔
5351
        isRegtest := cfg.Bitcoin.RegTest
3✔
5352
        isDevNetwork := isSimnet || isSignet || isRegtest
3✔
5353

3✔
5354
        // TODO(yy): remove the check on simnet/regtest such that the itest is
3✔
5355
        // covering the bootstrapping process.
3✔
5356
        return !cfg.NoNetBootstrap && !isDevNetwork
3✔
5357
}
3✔
5358

5359
// fetchClosedChannelSCIDs returns a set of SCIDs that have their force closing
5360
// finished.
5361
func (s *server) fetchClosedChannelSCIDs() map[lnwire.ShortChannelID]struct{} {
3✔
5362
        // Get a list of closed channels.
3✔
5363
        channels, err := s.chanStateDB.FetchClosedChannels(false)
3✔
5364
        if err != nil {
3✔
5365
                srvrLog.Errorf("Failed to fetch closed channels: %v", err)
×
5366
                return nil
×
5367
        }
×
5368

5369
        // Save the SCIDs in a map.
5370
        closedSCIDs := make(map[lnwire.ShortChannelID]struct{}, len(channels))
3✔
5371
        for _, c := range channels {
6✔
5372
                // If the channel is not pending, its FC has been finalized.
3✔
5373
                if !c.IsPending {
6✔
5374
                        closedSCIDs[c.ShortChanID] = struct{}{}
3✔
5375
                }
3✔
5376
        }
5377

5378
        // Double check whether the reported closed channel has indeed finished
5379
        // closing.
5380
        //
5381
        // NOTE: There are misalignments regarding when a channel's FC is
5382
        // marked as finalized. We double check the pending channels to make
5383
        // sure the returned SCIDs are indeed terminated.
5384
        //
5385
        // TODO(yy): fix the misalignments in `FetchClosedChannels`.
5386
        pendings, err := s.chanStateDB.FetchPendingChannels()
3✔
5387
        if err != nil {
3✔
5388
                srvrLog.Errorf("Failed to fetch pending channels: %v", err)
×
5389
                return nil
×
5390
        }
×
5391

5392
        for _, c := range pendings {
6✔
5393
                if _, ok := closedSCIDs[c.ShortChannelID]; !ok {
6✔
5394
                        continue
3✔
5395
                }
5396

5397
                // If the channel is still reported as pending, remove it from
5398
                // the map.
5399
                delete(closedSCIDs, c.ShortChannelID)
×
5400

×
5401
                srvrLog.Warnf("Channel=%v is prematurely marked as finalized",
×
5402
                        c.ShortChannelID)
×
5403
        }
5404

5405
        return closedSCIDs
3✔
5406
}
5407

5408
// getStartingBeat returns the current beat. This is used during the startup to
5409
// initialize blockbeat consumers.
5410
func (s *server) getStartingBeat() (*chainio.Beat, error) {
3✔
5411
        // beat is the current blockbeat.
3✔
5412
        var beat *chainio.Beat
3✔
5413

3✔
5414
        // We should get a notification with the current best block immediately
3✔
5415
        // by passing a nil block.
3✔
5416
        blockEpochs, err := s.cc.ChainNotifier.RegisterBlockEpochNtfn(nil)
3✔
5417
        if err != nil {
3✔
5418
                return beat, fmt.Errorf("register block epoch ntfn: %w", err)
×
5419
        }
×
5420
        defer blockEpochs.Cancel()
3✔
5421

3✔
5422
        // We registered for the block epochs with a nil request. The notifier
3✔
5423
        // should send us the current best block immediately. So we need to
3✔
5424
        // wait for it here because we need to know the current best height.
3✔
5425
        select {
3✔
5426
        case bestBlock := <-blockEpochs.Epochs:
3✔
5427
                srvrLog.Infof("Received initial block %v at height %d",
3✔
5428
                        bestBlock.Hash, bestBlock.Height)
3✔
5429

3✔
5430
                // Update the current blockbeat.
3✔
5431
                beat = chainio.NewBeat(*bestBlock)
3✔
5432

5433
        case <-s.quit:
×
5434
                srvrLog.Debug("LND shutting down")
×
5435
        }
5436

5437
        return beat, nil
3✔
5438
}
5439

5440
// ChanHasRbfCoopCloser returns true if the channel as identifier by the channel
5441
// point has an active RBF chan closer.
5442
func (s *server) ChanHasRbfCoopCloser(peerPub *btcec.PublicKey,
5443
        chanPoint wire.OutPoint) bool {
3✔
5444

3✔
5445
        pubBytes := peerPub.SerializeCompressed()
3✔
5446

3✔
5447
        s.mu.RLock()
3✔
5448
        targetPeer, ok := s.peersByPub[string(pubBytes)]
3✔
5449
        s.mu.RUnlock()
3✔
5450
        if !ok {
3✔
5451
                return false
×
5452
        }
×
5453

5454
        return targetPeer.ChanHasRbfCoopCloser(chanPoint)
3✔
5455
}
5456

5457
// attemptCoopRbfFeeBump attempts to look up the active chan closer for a
5458
// channel given the outpoint. If found, we'll attempt to do a fee bump,
5459
// returning channels used for updates. If the channel isn't currently active
5460
// (p2p connection established), then his function will return an error.
5461
func (s *server) attemptCoopRbfFeeBump(ctx context.Context,
5462
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5463
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5464

3✔
5465
        // First, we'll attempt to look up the channel based on it's
3✔
5466
        // ChannelPoint.
3✔
5467
        channel, err := s.chanStateDB.FetchChannel(chanPoint)
3✔
5468
        if err != nil {
3✔
5469
                return nil, fmt.Errorf("unable to fetch channel: %w", err)
×
5470
        }
×
5471

5472
        // From the channel, we can now get the pubkey of the peer, then use
5473
        // that to eventually get the chan closer.
5474
        peerPub := channel.IdentityPub.SerializeCompressed()
3✔
5475

3✔
5476
        // Now that we have the peer pub, we can look up the peer itself.
3✔
5477
        s.mu.RLock()
3✔
5478
        targetPeer, ok := s.peersByPub[string(peerPub)]
3✔
5479
        s.mu.RUnlock()
3✔
5480
        if !ok {
3✔
5481
                return nil, fmt.Errorf("peer for ChannelPoint(%v) is "+
×
5482
                        "not online", chanPoint)
×
5483
        }
×
5484

5485
        closeUpdates, err := targetPeer.TriggerCoopCloseRbfBump(
3✔
5486
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5487
        )
3✔
5488
        if err != nil {
3✔
5489
                return nil, fmt.Errorf("unable to trigger coop rbf fee bump: "+
×
5490
                        "%w", err)
×
5491
        }
×
5492

5493
        return closeUpdates, nil
3✔
5494
}
5495

5496
// AttemptRBFCloseUpdate attempts to trigger a new RBF iteration for a co-op
5497
// close update. This route it to be used only if the target channel in question
5498
// is no longer active in the link. This can happen when we restart while we
5499
// already have done a single RBF co-op close iteration.
5500
func (s *server) AttemptRBFCloseUpdate(ctx context.Context,
5501
        chanPoint wire.OutPoint, feeRate chainfee.SatPerKWeight,
5502
        deliveryScript lnwire.DeliveryAddress) (*peer.CoopCloseUpdates, error) {
3✔
5503

3✔
5504
        // If the channel is present in the switch, then the request should flow
3✔
5505
        // through the switch instead.
3✔
5506
        chanID := lnwire.NewChanIDFromOutPoint(chanPoint)
3✔
5507
        if _, err := s.htlcSwitch.GetLink(chanID); err == nil {
3✔
5508
                return nil, fmt.Errorf("ChannelPoint(%v) is active in link, "+
×
5509
                        "invalid request", chanPoint)
×
5510
        }
×
5511

5512
        // At this point, we know that the channel isn't present in the link, so
5513
        // we'll check to see if we have an entry in the active chan closer map.
5514
        updates, err := s.attemptCoopRbfFeeBump(
3✔
5515
                ctx, chanPoint, feeRate, deliveryScript,
3✔
5516
        )
3✔
5517
        if err != nil {
3✔
5518
                return nil, fmt.Errorf("unable to attempt coop rbf fee bump "+
×
5519
                        "ChannelPoint(%v)", chanPoint)
×
5520
        }
×
5521

5522
        return updates, nil
3✔
5523
}
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